errno, strerror and Linux system calls

2019-02-15 02:20发布

问题:

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?

回答1:

Yes

Yes

In there is perror

if (-1 == open(....))
{
    perror("Could not open input file");
    exit(255)
}


回答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
   }