Reputation: 54
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
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.
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