正确使用fgets?

标签 c fgets

在这个程序中,由于行,我遇到了段错误:

fgets( string , 50, in );  

如果我将其注释掉,程序可以正常退出,但我不确定我做错了什么? 我检查了函数 fgets 的声明,它似乎适合该程序。

//char *fgets(char *str, int n, FILE *stream)


#include <stdio.h>

int main(int argc, char const *argv[])
{
  FILE *in;
  char string[100];

  in = fopen("in.txt", "r" );

  // if i remove this line segmentation fault is no more.
  fgets( string , 50, in );  

  fclose(in);

  return 0;
}

最佳答案

fopen() 可能没有成功,在尝试读取之前检查它的返回值。

关于正确使用fgets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22078697/

相关文章:

c - 重置c中变量的数量

c - 如何使用 Pennsim 和 LC-3 编程语言开始基本编程任务?

c - 在 fgets 中检测换行符

c - 使用 fgets() 在同一行打印两个字符串

c - 使用 Fgets 读取 cpp 文件的所有行

c - 被标记化的 fgets() 字符串是否能够被索引到字符中? :line[0], 错误:段

c - C中的重定向输入 : fgets() end of line "\n" interfering with strcmp()

c - Malloc使用的内存是所需内存的10倍

c - 在不同迭代中使用 fscanf/fgets 读取文件时随机崩溃

在 C 中正确使用 free() 函数