Seg Fault error reading from file with fgets

你说的曾经没有我的故事 提交于 2019-12-02 08:37:20

Well, I see a few problems...

  • size is not initialized
  • calling gets() twice in a row seems odd, see feof()
  • you aren't doing anything after testing the fopen() result against NULL, so the first gets() could bomb out for that reason ... do you get that message?

Only the last thing seems likely to throw an exception, but my philosophy is always fix the known problems and retest ... it's a waste of time to predict interactions between bugs.

I think that the filename that you are providing in the argument either does-not exists or some access violations. You can check this by printing the errno just after doing the fopen command.

fprintf (stderr, "Couldn't open file %s; %s\n", argv[1], strerror (errno));

also can you try this code once:

#include<errno.h>
#include<stdio.h>
int main(int argc, char **argv)
{
    int **aryReturn;
    int size=0;
    char trashdata[100];

    //open file
    FILE *inFilePtr = fopen(*(argv + 1), "r" );

    printf(" the value of argv 1 is %s \n", argv[1]);
    if (inFilePtr == NULL)
    {
        fprintf (stderr, "Couldn't open file %s; %d\n", argv[1],errno);
        exit(0);
    }
    while (!feof(inFilePtr)){
    fgets(trashdata, 10, inFilePtr);
    printf("%s",trashdata);
    size++;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!