C fopen write failure with errno is 2

I don't understand why this seems to fail with errno 2:

char debugText [256]; sprintf (debugText, "C:\\List.txt"); dfile = fopen( debugText, "w"); fprintf ( dfile, " err %d \n", errno); 

I say, apparently, because while dfile is NULL, the file is created and populated with my output.

So what is going on?

+3
source share
3 answers

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; } 
+6
source
 2 ENOENT No such file or directory. A component of a specified pathname did not exist, or the pathname was an empty string. 

Here is a list of error codes:

http://www.thegeekstuff.com/2010/10/linux-error-codes/

But you have to check if fopen() returned NULL , because this value in errno could be left from something else.

+4
source

No library function ever sets errno to zero.

errno should only be errno after the function reports an error.

For example, your code should be:

 if ((dfile = fopen(debugText, "w")) == 0) ...then fopen() failed and errno is relevant... 

If the function does not report an error, the value in errno can be any. For example, on Solaris, you often end up with errno installing ENOTTY after a successful operation because stdout not connected to the terminal. This does not mean that something really went wrong; it just means that the test that standard output is a terminal failed (because it is not a terminal).

+3
source

All Articles