1

the following code i wrote is supposed to open a file given as an input, write to it and the read.

  • fopen() works properly and i have access to the file.
  • fprintf() also works as expected.

but as to fgets -if i use the if command as shown the condition is true, and if i dont i get that input[0] is the '\n' character while input[1] is 'h', and the loop runs without stopping since fgets() keep reading the first char again and again.

also, it seems like fgets() does not advance and has read all of the file into input - i can print input[3] and get 'l' as expected, although fgets() is ordered to read only 2 chars.

int main(int argc, char *argv[])
{
    FILE* read = NULL;
    read = fopen(name, "a+");

    char* input = "";

    fprintf(read, "hello world\n");
    fprintf(read, "hello world\n");

    assert(ferror(read) == 0);

    while(!feof(read))
    {
        if(fgets(input, 2, read)==NULL)
            return 0;
        printf("%c\n", input[1]);


    }
return 0;
}
proton
  • 393
  • 6
  • 31
  • 4
    `char* input = "";`. That makes `input` point to a string literal. String literals cannot be modified. So your program has Undefined Behaviour. You need to allocate a memory buffer for `input`. Also, after the `fprintf` you need to `rewind` the file pointer if you want to read back what you just wrote. And finally, see [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – kaylum Mar 27 '16 at 21:20

2 Answers2

1

printf("%c\n", input[1]); Will allways print nul char

Man pages are your friends.

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer.

xvan
  • 4,554
  • 1
  • 22
  • 37
1
char* input = "";

This makes input point to a string constant, specifically an empty string.

    if(fgets(input, 2, read)==NULL)

This tries to modify what input points to. Since input points to a string constant, this tries to modify a string constant. But, by definition, you can't modify a constant -- that's what makes it constant.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278