简体   繁体   中英

Seg Fault error reading from file with fgets

//declare double pointer so that create array can "return" an array
int **aryReturn;
int size;
char trashdata[100];

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

if (inFilePtr != NULL)
    printf(" the value of argv 1 is %s \n", argv[1]); 

while (fgets(trashdata, sizeof(int) * 10, inFilePtr) != NULL){
    fgets(trashdata, 10, inFilePtr);
    size++;
}

can anyone tell me why my loop condition will not work! I get a seg fault that says fp(0x0) at fgets. I have tried

while (!feof(inFilePtr))

And I basically get the same error, but it says feof is the problem.

My file seems to open correctly because the if statement prints.. and argv has the expected file name

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++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM