Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding errno and strerror()

Considering fopen() fails, in the following piece of code:

FILE *fp = fopen("file.txt", "w");
if (fp == NULL) {
    printf("Error occurred while opening file, errno=%d, %s\n", 
                         errno, strerror(errno));
    exit(1);
}

Since the order in which function arguments are evaluated is unspecified in C, while invoking printf(), in case call to strerror() is evaluated (invoked) first and it fails, wouldn't errno be set to something else when the line actually gets printed? Or, is it that errno would have been copied into the activation record of printf() even before evaluating strerror() and hence would remain unchanged? Is this unspecified behaviour?

EDIT: Yes, I do understand that I can save errno to some int right after fopen(), but that's not my point here. I am trying to figure out how the above piece of code behaves.

like image 913
babon Avatar asked Oct 29 '25 20:10

babon


1 Answers

Since no return value is reserved to indicate an error, an application wishing to check for error situations should set errno to 0, then call strerror(), then check errno.

From the same article that you used. Very likely it's unspecified behaviour. MAN tells the same

POSIX.1-2001 and POSIX.1-2008 require that a successful call to strerror() or strerror_l() shall leave errno unchanged, and note that, since no function return value is reserved to indicate an error, an application that wishes to check for errors should initialize errno to zero before the call, and then check errno after the call.

So you can save errno of fopen, and then get errno of strerror. Or simply use perror.

like image 59
anast3t Avatar answered Nov 01 '25 10:11

anast3t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!