【问题标题】:errno, strerror and Linux system callserrno、strerror 和 Linux 系统调用
【发布时间】:2011-08-06 20:34:30
【问题描述】:

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

【问题讨论】:

    标签: c linux error-handling


    【解决方案1】:

    是的,您的代码可能类似于(未经测试):

       #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
       }
    

    【讨论】:

    • errmsg 临时变量没有用处。只需将strerror(errno) 直接放在printf 的参数列表中即可。
    【解决方案2】:

    是的

    是的

    里面有perror

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

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2012-10-07
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2016-06-23
      • 2016-05-12
      相关资源
      最近更新 更多