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 it 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()
?
3 Answers
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
}

- 8,610
- 6
- 39
- 51
-
4There is no use for the `errmsg` temp variable. Just put `strerror(errno)` directly in the argument list for `printf`. – R.. GitHub STOP HELPING ICE Apr 16 '11 at 12:55
Yes
Yes
In there is perror
if (-1 == open(....))
{
perror("Could not open input file");
exit(255)
}

- 374,641
- 47
- 450
- 633
Most of the Linux system calls are encapsulated by C library routines. open()
system call is actually a function defined in the C library which calls the actual open()
system call of the kernel.
errno is a variable defined and managed by the C library, not by the kernel. It is set upon the return of the system call with the error code returned by the kernel.
As an example, in the GNU C library, open()
is defined in sysdeps/unix/sysv/linux/open.c as:
int
__libc_open (const char *file, int oflag, ...)
{
int mode = 0;
if (__OPEN_NEEDS_MODE (oflag))
{
va_list arg;
va_start (arg, oflag);
mode = va_arg (arg, int);
va_end (arg);
}
return SYSCALL_CANCEL (openat, AT_FDCWD, file, oflag, mode);
}
libc_hidden_def (__libc_open)
weak_alias (__libc_open, __open)
libc_hidden_weak (__open)
weak_alias (__libc_open, open)
The bottom macros establish a equivalence between __libc_open() and open().
The SYSCALL_CANCEL() macros invokes the actual system call (which is openat()
) and sets errno with the error code if any error condition occured.

- 4,490
- 3
- 11
- 30