G
Gary Baydo
The following program illustrates a question I have about fscanf()
behavior:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE *testfile;
char s1[] = "01234567890123456789";
int c;
/* create a file and write some test data */
testfile = fopen("test.dat", "w+");
if (testfile == NULL) {
printf("Could not open file\n");
return EXIT_FAILURE;
}
fprintf(testfile, "%s", s1);
/* rewind() testfile and fputc() a character ... */
rewind(testfile);
fputc('Z', testfile);
/* ... and read-in s1 with fscanf() */
strcpy(s1, "overwriteMe");
c = fscanf(testfile, "%s", s1);
/* print the results */
printf("%d %s\n", c, s1);
fclose(testfile);
return EXIT_SUCCESS;
}
After rewinding the file and printing a character to it, I would expect
fscanf() to begin reading at position 1, but it returns EOF and leaves the
string s1 unchanged (at least with Borland's compiler on my Win XP
machine.) I've googled on this, but haven't found an answer. Neither
have I found an answer in _C A Reference Manual_, fifth edition. From
what I understand a file position indicater is maintained in the FILE
structure, but I'm not expert enough (yet) to know how to check that.
Thanks for any help.
--Gary
behavior:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE *testfile;
char s1[] = "01234567890123456789";
int c;
/* create a file and write some test data */
testfile = fopen("test.dat", "w+");
if (testfile == NULL) {
printf("Could not open file\n");
return EXIT_FAILURE;
}
fprintf(testfile, "%s", s1);
/* rewind() testfile and fputc() a character ... */
rewind(testfile);
fputc('Z', testfile);
/* ... and read-in s1 with fscanf() */
strcpy(s1, "overwriteMe");
c = fscanf(testfile, "%s", s1);
/* print the results */
printf("%d %s\n", c, s1);
fclose(testfile);
return EXIT_SUCCESS;
}
After rewinding the file and printing a character to it, I would expect
fscanf() to begin reading at position 1, but it returns EOF and leaves the
string s1 unchanged (at least with Borland's compiler on my Win XP
machine.) I've googled on this, but haven't found an answer. Neither
have I found an answer in _C A Reference Manual_, fifth edition. From
what I understand a file position indicater is maintained in the FILE
structure, but I'm not expert enough (yet) to know how to check that.
Thanks for any help.
--Gary