I do not understand why this is seemingly failing with errno of 2:
char debugText [256];
sprintf (debugText, "C:\\List.txt");
dfile = fopen( debugText, "w");
fprintf ( dfile, " err %d \n", errno);
I say seemingly because while dfile is NULL the file gets created and is filled with my output.
so what is going on ?
All this tells you is that errno
had the value 2 after your fopen
call. You don't know that the call failed, because you didn't check whether dfile == NULL
. If the output was actually written to the file, presumably the fopen
call succeeded and the errno
value was left over from some previous call, likely one you didn't make explicitly.
Failing calls can set errno
to some non-zero value, but successful calls don't set errno
to 0. To check for errors, you need to
errno
to 0 before the call;errno
after the call -- but only if you know it failed (otherwise the value of errno
is meaningless).If defile == NULL
, then the fprintf
call has undefined behavior; it will probably fail.
On the other hand, you say that dfile
is NULL
. How do you know that? Your code doesn't check it. (If the fopen
call really did fail, could the contents of C:\List.txt
be left over from a previous run of your program?)
What output do you get from this program?
#include <stdio.h>
#include <errno.h>
int main(void) {
char debugText [256];
FILE *dfile;
sprintf (debugText, "C:\\List.txt");
dfile = fopen( debugText, "w");
if (dfile == NULL) {
printf("fopen failed, errno = %d\n", errno);
}
else {
printf("fopen succeeded\n");
}
return 0;
}