proton
proton

Reputation: 431

c - weird fgets() behavior

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

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

Upvotes: 1

Views: 1082

Answers (2)

xvan
xvan

Reputation: 4875

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.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182847

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.

Upvotes: 1

Related Questions