All this suggests that errno has a value of 2 after your fopen call. You do not know that the call failed because you did not check if dfile == NULL . If the output was actually written to a file, it is assumed that the fopen call succeeded and the errno value was left after the previous call, you probably did not explicitly specify.
Failed calls may set errno to some nonzero value, but successful calls do not set errno to 0. To check for errors, you need to
- Before calling set
errno to 0; - Make a call and check the return value to see if it succeeded or failed; and
- Check the
errno value after the call - but only if you know that it failed (otherwise the errno value does not make sense).
If defile == NULL , then the call to fprintf has undefined behavior; he is likely to fail.
On the other hand, you say that dfile is NULL . How do you know? Your code does not check. (If the fopen call really failed, is it possible to leave the contents of C:\List.txt in the 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; }
source share