美文网首页
linux下 C语言perror、strerror函数的作用

linux下 C语言perror、strerror函数的作用

作者: Magic11 | 来源:发表于2019-07-05 14:24 被阅读0次

void perror(const char *s);
perror ("open_port");
函数说明
  perror()用 来 将 上 一 个 函 数 发 生 错 误 的 原 因 输 出 到 标 准 设备 (stderr) 。参数 s 所指的字符串会先打印出,后面再加上错误原因字符串。此错误原因依照全局变量errno 的值来决定要输出的字符串。   在库函数中有个errno变量,每个errno值对应着以字符串表示的错误类型。当你调用"某些"函数出错时,该函数已经重新设置了errno的值。perror函数只是将你输入的一些信息和现在的errno所对应的错误一起输出。
范例:

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    FILE *fp;
    fp = fopen("noexitfile", "r+");
    if (NULL == fp) {
        printf("error code = %d, error msg = %s\n", errno, strerror(errno));
        perror("noexitfile");
    }
    return 0;
}

运行结果:
@ubuntu:~/work/dev/testgcc perrortest.c -o perrortest @ubuntu:~/work/dev/test ./perrortest
error code = 2, error msg = No such file or directory
noexitfile: No such file or directory

相关文章

网友评论

      本文标题:linux下 C语言perror、strerror函数的作用

      本文链接:https://www.haomeiwen.com/subject/dbxehctx.html