简体   繁体   中英

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.

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

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.

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.

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