1 首先 perror 函数比较简单。头文件 <stdio.h>
所以只需要直接使用就行了

1 #include <stdio.h>
2
3 int main ()
4 {
5 FILE *fp;
6
7 fp = fopen("file.txt", "r");
//这个文件没有
8 if( fp == NULL ) {
9 perror("Error: "); //只需添加这一句
10 return(-1);
11 }
12 fclose(fp);
13
14 return(0);
15 }

打印

Error: : No such file

2 一般 errno strerror 都是配套使用的
errno 在 errno.h 库里面,但是是个全局变量,所以不用示例话。
而 strerror 函数在 string.h 库里面
使用这个方法要添加这两个库。

1 #include <stdio.h>
2 #include <errno.h>
3 #include<string.h>
4
5 int main ()
6 {
7 FILE *fp;
8
9
10 fp = fopen("file.txt", "r");
11 if( fp == NULL ) {
12 printf("erorr is %d perror is %s\n",errno,strerror(errno));
13 return(-1);
14 }
15 fclose(fp);
16
17 return(0);
18 }

打印

erorr is 2

更多详细信息
​linux下的错误捕获errno和strerror()