errno, strerror and Linux system calls

2019-02-15 02:13发布

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?

2条回答
神经病院院长
2楼-- · 2019-02-15 02:41

Yes

Yes

In there is perror

if (-1 == open(....))
{
    perror("Could not open input file");
    exit(255)
}
查看更多
Ridiculous、
3楼-- · 2019-02-15 02:41

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
   }
查看更多
登录 后发表回答