I was learning about file i/o and stucked, that when i use fprintf() to print a string in a file and then read that string using fscanf() then instead of string it prints some garbage value in output.
#include <stdio.h>
int main ()
{
FILE *ptr = NULL;
char string[6] = "Hello";
char string1[6];
ptr = fopen ("text.txt", "a ");
fprintf (ptr, "%s", string);
fscanf (ptr, "%s", string1);
printf ("%s", string1);
fclose(ptr);
return 0;
}
CodePudding user response:
Your best bet is to close the file and reopen it if you intend to read back what you just wrote. You can have a file open for read and write but its just asking for trouble
#include <stdio.h>
int main ()
{
FILE *ptr = NULL;
char string[6] = "Hello";
char string1[6];
ptr = fopen ("text.txt", "a ");
fprintf (ptr, "%s", string);
fclose(ptr); <<<<=== close it
fopen ("text.txt", "r"); <<<<=== reopen in read
fscanf (ptr, "%s", string1);
printf ("%s", string1);
fclose(ptr);
return 0;
}
CodePudding user response:
As posted, the program has undefined behavior because there is no seek operation between the fprintf()
output operation and the fscanf()
input request.
There are different ways to modify the program:
Resetting the file position at the start of file using rewind(ptr)
or fseek(ptr, 0L, SEEK_SET)
will cause fscanf()
to read the first word in the file, which is not necessarily the one you just wrote as the file is open for append and read. Furthermore, you should give fscanf()
a maximum number of characters to read for the word to avoid a buffer overrun. Also check for failure to open the file and report the error.
#include <stdio.h>
int main() {
FILE *ptr = NULL;
char string[6] = "Hello";
char string1[100];
ptr = fopen("text.txt", "a ");
if (ptr == NULL) {
fprintf(stderr, "cannot open text.txt for a \n");
return 1;
}
fprintf(ptr, "%s", string); // string written at the end of file
rewind(ptr); // seek back to the beginning of file
fscanf(ptr, "