fprintf not working

2020-02-14 17:30发布

问题:

I'm testing the usage of fprintf() and it is not working. When I first wrote the code I forgot to add \n inside fprintf() and it worked. However, when I added \n at the start of "test 1 2" it stopped working.

#include <stdio.h>
#include <stdlib.h>

int main ()
{
    FILE* f = fopen("test.txt", "r+");
    if( f == NULL) return 0;

    char str[4][10];

    for(int a = 0; a <= 3; ++a)
    {
        fscanf(f, " %[^\t\n]s", str[a]);
        printf("%s\n", str[a]);
    }

    fprintf(f, "\ntest 1 2\n");

    fclose(f);
    system("pause");
    return 0;
}

and my test.txt contains ( instead of \t and \n I pressed tab and enter in the file but I couldn't manage it here)

a b\t c d\t e\n f g

回答1:

For files open for appending (those which include a "+" sign), on which both input and output operations are allowed, the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a writing operation followed by a reading operation or a reading operation which did not reach the end-of-file followed by a writing operation.

Source

So add this:

fflush(f);

before your fprintf if you want to append to the file without deleting its previous contents, or this:

rewind(f);

if you want to overwrite the content, as pointed by your comment.



标签: c io