C fopen fails for write with errno is 2

JPM picture JPM · Apr 2, 2013 · Viewed 51.1k times · Source

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 ?

Answer

Keith Thompson picture Keith Thompson · Apr 2, 2013

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

  • Set errno to 0 before the call;
  • Make the call and check the value it returned to see whether it succeeded or failed; and
  • Check the value of 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;
}