errno、strerror 和 Linux 系统调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5685973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:40:47  来源:igfitidea点击:

errno, strerror and Linux system calls

clinuxerror-handling

提问by Alex F

I can use strerror to get text representation of errno value after using CRT functions, like fopen. If I use openLinux 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?

在使用 CRT 函数(如fopen)后,我可以使用 strerror 来获取 errno 值的文本表示。如果我使用openLinux 系统调用而不是 CRT 函数,它也会在失败时设置 errno 值。将 strerror 应用于此 errno 值是否正确?如果没有,是否有一些与 strerror 相同的 Linux 系统调用?

采纳答案by sehe

Yes

是的

Yes

是的

In there is perror

里面有 perror

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

回答by Pete Wilson

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
   }