如何使用fgets()从文件中提取一行文本?

时间:2015-02-04 22:56:40

标签: c file fgets

我正在编写一个程序,必须从文件中提取一行文本并检查字母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

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

1 个答案:

答案 0 :(得分: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