I am experiencing an unexpected value of errno
when using perror
with glibc
. When an non-existent file is specified as arg[1]
it prints Error: 2
( which isENOENT
) as expected. However when the perror
line below is uncommented it throws error 22 (EINVAL
) no matter what I pass it. Can anyone please explain why this is getting set?
EDIT: Looks like this is some sort of Eclipse bug. The IDE seems to be causing perror to throw some sort of error, the program works perfectly on the command line, and works perfectly when a correct file is specified in the argument list in Eclipse. It fails incorrectly when run inside of Eclipse.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *input_file;
input_file = fopen(argv[argc - 1], "r");
if (!input_file) {
// perror(argv[argc-1]);
fprintf(stderr, "Error: %d\n", errno);
return (EXIT_FAILURE);
}
else {
fclose(input_file);
}
return (EXIT_SUCCESS);
}
You can't rely on the value of
errno
after calling into other library functions, in other words your call to perror() itself may be modifying the value oferrno
You need to save it in a temporary variable if you want to be able to use it after calls into other library procedures.