c - C 中的奇怪段错误

标签 c segmentation-fault

好的,所以我不太确定这里发生了什么。我有一个简单的函数,int foo(char *filename),它接受 filename 并计算文件中的单词数。

int foo(char *filename){

  FILE *inFile;
  int wordCount = 0;    

  printf("foo\n"); // test printf() statement (currently prints)

  char word[50];
  inFile = (&filename, "r");

  printf("infile\n");  // test printf() statement (currently prints)

  while (1){
    printf("while");   // test printf() statement (doesn't print)
    fscanf(inFile, "%s", word);
    if (feof(inFile))
        break;
    printf("%d", wordCount); //test printf() statement
    wordCount++;
  }
  fclose(inFile);
  return wordCount;

}

如您所见,我打印了“infile”,而不是“while”。我遇到段错误。有谁知道为什么这不起作用另外,我的 inFile = (&filename, "r"); 语句是否正确?我不太擅长指点。

最佳答案

我很惊讶这一行实际上编译:

inFile = (&filename, "r");

如果您尝试打开一个文件:

inFile = fopen(filename, "r");

编辑:

如前所述,您需要使用 \n 结束您的 printf 或调用 fflush(stdout) 否则它将被缓冲并不打印。

关于c - C 中的奇怪段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7577311/

相关文章:

将字符转换为位于 argv[1] 内字符串内的 int

c - C 编译器如何处理枚举?

c - 在send和recv套接字系统调用中以什么格式发送和接收SMPP协议(protocol)数据单元(PDU)?

c - 简单的 C 应用程序出现段错误

c++ - 在 Linux x64 下使用 libmozjs-52 (SpiderMonkey) 的段错误

c - Malloc 之后的 Strcpy 段错误

c - Segmentation fault (core dumped) 错误,但程序运行正常

c - 如何编译这个库以供使用?

c - .so 和 .so.x 的区别

c - 递归 main() - 为什么会出现段错误?