错误处理与文件操作技术详解
1. 处理更多的 errno 宏
在使用 errno
时,应先检查函数或系统调用的返回值。因为 errno
变量不会在系统调用后自动清除,如果直接检查 errno
,它可能包含之前错误的错误码。
1.1 准备工作
需要用到手册页、GCC 编译器和 Make 工具。
1.2 操作步骤
- 阅读
creat()
的手册页:- 使用
man 2 creat
命令查看手册页。 - 滚动到
ERRORS
标题,找到表示路径名不存在的宏ENOENT
(Error No Entry)。
- 使用
- 实现处理
ENOENT
的新if
语句:- 创建
simple-touch-v4.c
文件,代码如下:
- 创建
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <linux/limits.h>
int main