Hi all,

I'm writing a program to read from a stream file, one line at a time,
I used getline() and fgets(), both gives a correct result,
but they give a "segmentation fault" when reading the last line of the file, I think because of the NULL character at the end of the file.
do they supposed to give such an error when reading a NULL character?
and what are other alternatives that could work for my code?
I'm using Ubuntu.

thanks in advance,

segmentation fault results from trying to read/write from/to an invalid address..

Here's what happens when fgets() encounters the end of file or an error...Quote from my man files

"char *fgets(char *s, int size, FILE *stream);

gets() and fgets() return s on success, and NULL on error or when end
of file occurs while no characters have been read."

Could you post your code so we could have a look at it.

here it is: (This is one function I call it to read one tuple (i.e. line) from the file)

OrderTupleType ReadOrder(FILE* fp, bool &finished)
{
     char * result;
     OrderTupleType RealOrderTuple;
     TupleType CharOrderTuple;
     fgets(CharOrderTuple, sizeof(CharOrderTuple), fp);
     if(feof(fp))
          finished = true;
     else
          finished = false;

     result = strtok(CharOrderTuple, "|");
     RealOrderTuple.OrderKey = atoi(result);
     result = strtok(NULL, "|");
     result = strtok(NULL, "|");
     result = strtok(NULL, "|");
     result = strtok(NULL, "|");
     RealOrderTuple.OrderDate = result;

     return RealOrderTuple;
}

thanks,

For debugging purposes I would set up a char buffer the size of CharOrderTuple and read the file into it. Then take the strlen of it and see if it is the correct length. If it is, copy it over to CharOrderTuple with memcpy. If it's too short, I'm guessing that's your seg fault. Test for good input and only do the strtok calls if the test passes.

Lines 7 - 10 might be sufficient too, but you don't check the finished variable prior to doing the strtok, so maybe you are parsing an empty line. Read a line from the file, test for valid input, and parse only if the test passes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.