What kind of errors faced by what kind of library functions affect the errno and set it to non-zero value? In my following program, I intended to use if(errno!=0)
as a condition to check if the library functions I used functioned properly or not, and this is what I found (see the code below):
First I used if(errno!=0)
to test if a file has been opened successfully with fopen()
or not. If I try to open a non-existent file, then errno
is set to non-zero (2 in my case) and it is verified by printing out the value of errno
at each stage. But if I open an existing file, then the value of errno remains zero as fopen()
opens the file properly. In this matter,if(errno!=0)
acts as the perfect substitute to if(pFile==NULL)
which I have commented out.
If the file is opened successfully, with errno
still 0
, the control moves to the first else
block. This is where I find confusions about the behavior of errno
. Here, since I have opened the file in r(read) mode and attempting to write to it using fputc()
, I expect the resulting write-error to set errno
to non-zero just as it is set by fopen()
when it couldn't open the file successfully. But the value of errno
continues to be zero even after that unsuccessful write using fputc()
. (This is verifiable by printing value of errno
after the faulty write).
Why is it so? Why is I/O error faced by one function fopen()
setting the errno
while write error faced by other function fputc()
not affecting errno
? If it's so, how can we reliably use errno
as an indicator of error? Is my use of errno to test if fopen() worked successfully, instead of "if(pFile==NULL)" unwise? I will appreciate your analytic answers to this.
#include <stdio.h>
#include <errno.h>
int main ()
{
FILE * pFile;
printf("%d\n",errno);
pFile = fopen("D:\\decrypt.txt","r");
printf("%d\n",errno); // Prints 0 if fopen() successful,else 2
//if(pFile==NULL) perror("Error opening file");
if (errno!=0) perror ("Error opening file");
else
{
fputc ('x',pFile);
printf("%d\n",errno); //errno shows 0 even after write error
//if (ferror (pFile))
if (errno!=0) //Condition evaluates false even if faulty write
{
printf ("Error Writing to decrypt.txt\n");
}
fclose (pFile);
}
return 0;
}
..when it is indicated to be valid by a function's return value.
?Can you put it in an answer with more details please? – Ramrod