On Oct 30, 7:59 am, "V.Subramanian, India"
Hello V. Subramanian
I also learned a few things, thanks to your posting.
The results are from Mac OS X 10.6.8, they may not apply to RedHat
Linux.
Allow me to point out some observations.
1. fscanf's behaviour
What I take away is that fscanf(3) does not set errno, whether the
call succeeds or not.
Modifying your original source code, errno is always -234 below.
Calling ferror(fp) after fscanf has no effect.
2. Format used
You assumed that two numbers are adjacent ("%d%d").
This is rather misleading.
Say the input were 193.
Should that be read as "1" followed by "93" (case 1), or "19" followed
by "3" (case 2).
The solution is to specify "%1d%2d" for case 1 and "%2d%1d" for case
2.
Another solution is to separate the numbers with a white-space, like
below.
3. Writing and reading to/from the same file
As pointed out, you must create the file with "r+" or "w+".
4. File position
After writing to the file, you are at the end of the file.
If you want to read from it, you must re-position the reader to the
beginning, with fseek or rewind.
Or you could call fclose(fp) followed by fopen(...).
Here's the code:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int
main (int argc, char *argv[])
{
int a, b, count = -1, status = EXIT_SUCCESS;
FILE *fp = fopen ("data.txt", "w+");
fprintf (fp, "23 57"); // valid input
//fprintf (fp, "no number"); // invalid input
if (0 != errno) {
fprintf (stderr, "Could not write data: '%s'\n", strerror
(errno));
return EXIT_FAILURE;
}
// re-set the position to the beginning
rewind (fp);
// unfortunately, errno is not set, whether fscanf succeeds or
not!
errno = -234;
count = fscanf (fp, "%d %d", &a, &b);
if (2 == count) {
fprintf (stdout, "a=%d, b=%d, errno=%d\n", a, b, errno);
}
else {
fprintf (stderr, "Expected 2 tokens, got %d; errno=%d\n",
count, errno);
status = EXIT_FAILURE;
}
fclose (fp);
return status;
}
Regards,
--
Carlo