/* 打开一个已经存在的文件 #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int flags); 参数: pathname: 文件路径 flags: 文件的操作权限设置 必选项:O_RDONLY, O_WRONLY, O_RDWR 可选项:O_CREAT等 用|连接 返回值: 返回文件描述符,调用失败返回-1 有错误号时,如何打印错误描述? #include <stdio.h> void perror(const char *s); s为用户描述错误 输出 "s:实际错误描述" perror会自动捕捉当前错误 创建一个新的文件 int open(const char *pathname, int flags, mode_t mode); mode: 八进制的数,表示创建出的新文件的操作权限 三种权限:读写执行 因此是8进制 三种用户:此用户,用户所在组,其它用户,因此3个八进制数,加一个符号位,如0777,表示三种用户均可读可写可执行 最终的权限:mode & ~umask umask的作用是操作系统抹去某些权限,保证安全 关闭文件 #include <unistd.h> int close(int fd); */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> int main() { // 打开一个文件 // int fd = open("a.txt", O_RDONLY); int fd = open("a.txt", O_RDONLY | O_CREAT, 0777); if(fd == -1) { perror("hello"); } close(fd); return 0; }