V
V.Subramanian, India
This question is for learning purpose only.
Consider the program sample.c :
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
errno = 0;
FILE *fp = fopen("data.txt", "w");
if (fp == NULL)
{
fprintf(stderr,
"Could not open input file - data.txt\n%s\n",
strerror(errno));
return EXIT_FAILURE;
}
if (fprintf(fp, "test data") < 1)
{
fprintf(stderr,
"could not write message into data.txt\n");
return EXIT_FAILURE;
}
fflush(fp);
int a;
int b;
errno = 0;
// I deliberately try to read from the file
// opened in 'write' mode
if (fscanf(fp, "%d%d", &a, &b) == 2)
{
fprintf(stdout,
"a = %d, b= %d\n",
a,
b);
fflush(stdout);
fclose(fp);
return EXIT_SUCCESS;
}
int err = errno;
if (ferror(fp))
{
fprintf(stderr,
"Error encountered while reading input"
" from file\n%s\n",
strerror(err));
fclose(fp);
return EXIT_FAILURE;
}
fclose(fp);
return EXIT_SUCCESS;
}
In this program I open a file 'data.txt' in 'write' mode.
Subsequently, I write something into this file. Then I read
from this file using 'fscanf'. This operation should fail.
But when I test the error indicator for the stream by
calling 'ferror(fp)', the statements inside the
if (ferror(fp))
{
}
are NOT executed.
Does this mean that error inidcator for the stream is not set
by 'fscanf' ? Isn't the operation 'reading from a file
opened in "write" mode' an error ?
I am unable to understand this.
Kindly explain.
Thanks
V.Subramanian
Consider the program sample.c :
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
errno = 0;
FILE *fp = fopen("data.txt", "w");
if (fp == NULL)
{
fprintf(stderr,
"Could not open input file - data.txt\n%s\n",
strerror(errno));
return EXIT_FAILURE;
}
if (fprintf(fp, "test data") < 1)
{
fprintf(stderr,
"could not write message into data.txt\n");
return EXIT_FAILURE;
}
fflush(fp);
int a;
int b;
errno = 0;
// I deliberately try to read from the file
// opened in 'write' mode
if (fscanf(fp, "%d%d", &a, &b) == 2)
{
fprintf(stdout,
"a = %d, b= %d\n",
a,
b);
fflush(stdout);
fclose(fp);
return EXIT_SUCCESS;
}
int err = errno;
if (ferror(fp))
{
fprintf(stderr,
"Error encountered while reading input"
" from file\n%s\n",
strerror(err));
fclose(fp);
return EXIT_FAILURE;
}
fclose(fp);
return EXIT_SUCCESS;
}
In this program I open a file 'data.txt' in 'write' mode.
Subsequently, I write something into this file. Then I read
from this file using 'fscanf'. This operation should fail.
But when I test the error indicator for the stream by
calling 'ferror(fp)', the statements inside the
if (ferror(fp))
{
}
are NOT executed.
Does this mean that error inidcator for the stream is not set
by 'fscanf' ? Isn't the operation 'reading from a file
opened in "write" mode' an error ?
I am unable to understand this.
Kindly explain.
Thanks
V.Subramanian