环境:Vmware Workstation;CentOS-6.4-x86_64
查看官方文档,open函数返回值的说明:
-1 if an error occurred (in which case, errno is set appro-priately)
如果返回的是-1,那么errno就会被设置。
也就是说,打开文件失败,那么错误信息就会被存放在errno中。
说明:
1、errno的头文件#include <errno.h>
2、errno需要函数strerror包装
3、strerror的头文件#include <string.h>
使用图解:
打开文件的完整操作过程:
#include <stdio.h>
// 包含open所需要的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// 包含close所需要的头文件
#include <unistd.h>
// 包含errno所需要的头文件
#include <errno.h>
// 包含strerror所需要的头文件
#include <string.h>
int main(int argc, char *args[])
{
// 打开文件,获取返回值
int fd = open("a.txt", O_RDONLY);
// 判断打开文件是否成功
// 如果打开文件不成功
if (fd == -1)
{
// 打印错误信息
printf("Message : %s\n", strerror(errno));
}
// 如果打开文件成功,操作文件并关闭
close(fd);
return 0;
}
PS:根据传智播客视频学习整理得出。