errno, strerror and Linux system calls
13,221
Solution 1
Yes
Yes
In there is perror
if (-1 == open(....))
{
perror("Could not open input file");
exit(255)
}
Solution 2
Yes, and your code might be something like (untested) this:
#include <stdio.h>
#include <errno.h>
#include <string.h> // declares: char *strerror(int errnum);
FILE *
my_fopen ( char *path_to_file, char *mode ) {
FILE *fp;
char *errmsg;
if ( fp = fopen( path_to_file, mode )) {
errmsg = strerror( errno ); // fopen( ) failed, fp is set to NULL
printf( "%s %s\n", errmsg, path_to_file );
}
else { // fopen( ) succeeded
...
}
return fp; // return NULL (failed) or open file * on success
}
Author by
Alex F
Updated on June 28, 2022Comments
-
Alex F almost 2 years
I can use strerror to get text representation of errno value after using CRT functions, like fopen. If I use open Linux system call instead of CRT function, it also sets errno value when fails. Is this correct to apply strerror to this errno value? If not, is there some Linux system call, which does the same as strerror?