【问题标题】:How do I use fgets() to pull a line of text out from a file?如何使用 fgets() 从文件中提取一行文本?
【发布时间】:2015-02-04 22:56:39
【问题描述】:

我正在编写一个程序,它必须从文件中提取一行文本并检查字母 C 是否在所述行中。我正在尝试使用 fgets() 从行中提取我需要的文本,但到目前为止完全无法产生任何输出。

这是我尝试过的代码:

fgets(char 1, int maxlen, FILE input_file)

它从中提取的输入文件名为input_file,其中的文本格式如下:

25,F
32,F
-40,C
-20,C
-20,F
-40,F
0,C

谁能告诉我我做错了什么?

【问题讨论】:

  • 你写的代码不是有效的C。
  • char buf[100]; if (fgets(buf, sizeof buf, stdin) != NULL) {

标签: c file fgets


【解决方案1】:

对于函数调用,代码需要传递值,而不是变量声明。

请务必检查fgets() 的结果以及执行的任何解析。

FILE *ifile;
// add code to open file
char buf[100];

// fgets(char 1, int maxlen, FILE input_file)
while (fgets(buf, sizeof buf, ifile) != NULL) { 
  int temp;
  char scale;
  if (2 != sscanf(buf, "%d , %c", &temp, &scale) {
    // Oops, bad input
    break;
  }

  // Do something with data
  printf("Temperature %d degrees %c\n", temp,scale);
}

// code to close file

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2021-12-27
    • 2020-08-19
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多