strerror() 函数能够将错误号 errno 转换成对应的错误消息字符串。
#include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { FILE *fp; fp = fopen("no_this_file", "r"); perror("fopen"); printf("fopen: %s\n", strerror(errno)); return EXIT_SUCCESS; }
输出
fopen: No such file or directory fopen: No such file or directory
strerror(errno) 输出了和 perror() 相同的错误消息。不过使用 strerror() 可以配合 printf() 定制客制化输出,如:
printf("fopen %s: %s\n", file_name, strerror(errno));
而 preeor() 由于不支持可变参数,有时稍显呆板。