bgun
bgun

Reputation: 54

fprintf not working

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

Upvotes: 3

Views: 20084

Answers (1)

Adri&#225;n
Adri&#225;n

Reputation: 6255

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.

Upvotes: 9

Related Questions