c - 为什么我会出现段错误?

标签 c segmentation-fault fopen

我对 C 非常陌生,我正在尝试逐字符读取一个文件的内容并将它们输出到流中。但即使我的 fopen() 命令被注释掉,我也会收到段错误(核心转储)。

我必须运行命令:./a.out < testWords.in > myOut.txt 才能正确执行我的文件。

这是我到目前为止所拥有的:

#include  <stdio.h>
void main(char *fileName[]) 
{
  printf("filename is %s.\n",fileName[0]);
  //Get file based on a string inputed
  FILE *fp=fopen(fileName[0],"r"); //Fetches our file as read only
  char ch;
  int lineCount = 0;
  int wordCount = 0;
  int charCount = 0;

  //Failed to find/open file. NULL character.
  if (fp == 0) printf("Woops! Couldn't open file!\n");

  //While not at end of file, grab next char.
  else while( (ch=fgetc(fp)) != EOF) 
    {
      if (ch == '\n') //on newline
      {
    //Prints (charCount,wordCount)\n lineCount:
    printf("(%d,%d)%c%d:",charCount,wordCount,ch,lineCount);
    charCount = 0;
    lineCount += 1;
      }
      else printf("%c",ch); //mirrors char.
    }
  fclose(fp); //Closes file (gotta be tidy!)

}

最佳答案

你不能仅仅发明一种调用main的方法。您需要使用其中一种标准方法,如下所示:

int main(int argc, char *argv[])
{
    if (argc < 2) {
        fprintf(stderr, "Missing filename\n");
        return -1;
    }
    FILE *fp = fopen(argv[1], "r");
    // ...
}

请注意,argv[0] 包含程序名称(如果可用;如果不存在,则包含空字符串)。

您的程序出现段错误,因为您将 int argc 参数接收到 char *filename[] 参数中。如果您使用单个命令行参数运行程序,则作为第一个参数传入的值将为 2,这不是有效的指针值。表达式filename[0]取消引用该地址并导致段错误。

关于c - 为什么我会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21591914/

相关文章:

c - 我在这里删除堆栈吗?

c - printf参数相互影响

php - fopen 并获取系统文件描述符

c - fopen() 在 c 中第二次使用时崩溃

c++ - 字符串 "sizeof"的意外结果

c - 如何在 C 中将数组作为函数参数传递?

c++ - 为什么 C++ 数组创建会导致段错误?

C - strcpy() 处的段错误

c++ - 仅当我将 stdout 重定向到/dev/null 时才会出现段错误?

c - fopen() 中 r+ 和 w+ 的区别