linux系统编程:open常用参数详解,linux参数详解


open用于打开一个文件,通过设置不同的flag,可以让进程只读,只写,可读/可写等操作

一、对一个不存在或者存在的文件(test.txt),进行写入操作

1 /*================================================================ 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名称:cp.c 5 * 创 建 者:ghostwu(吴华) 6 * 创建日期:2018年01月10日 7 * 描 述:用open和write实现cp命令 8 * 9 ================================================================*/ 10 11 #include <stdio.h> 12 #include <sys/types.h> 13 #include <sys/stat.h> 14 #include <fcntl.h> 15 #include <errno.h> 16 17 int main(int argc, char *argv[]) 18 { 19 int fd, openflags; 20 21 //openflags = O_WRONLY | O_CREAT; 22 23 openflags = O_WRONLY; 24 25 fd = open( "test.txt" , openflags ); 26 if( fd < 0 ) { 27 printf( "%d\n", errno ); 28 perror( "write to file" ); 29 } 30 return 0; 31 } View Code

1)当test.txt不存在时, 文件打开失败,会把操作系统的全局变量errno设置一个错误号, 这里设置的是2,对于一个2,我们完全不知道是什么错误,所以调用perror函数,他会把编号2解释成可读性的错误信息,

那么这里被解读成"No such file or directory",可以通过"grep "No such file or directory" /usr/include/*/*.h" 找到errno为2对应的头文件

2)如果test.txt文件存在,不会报错,打开一个正常的文件描述符,文件原来的内容不会受影响

二、加入O_CREAT标志

1 /*================================================================ 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名称:cp.c 5 * 创 建 者:ghostwu(吴华) 6 * 创建日期:2018年01月10日 7 * 描 述:用open和write实现cp命令 8 * 9 ================================================================*/ 10 11 #include <stdio.h> 12 #include <sys/types.h> 13 #include <sys/stat.h> 14 #include <fcntl.h> 15 #include <errno.h> 16 17 int main(int argc, char *argv[]) 18 { 19 int fd, openflags; 20 21 //openflags = O_WRONLY | O_CREAT; 22 23 openflags = O_WRONLY | O_CREAT; 24 25 fd = open( "test.txt" , openflags ); 26 printf( "fd = %d\n", fd ); 27 if( fd < 0 ) { 28 printf( "%d\n", errno ); 29 perror( "write to file" ); 30 } 31 return 0; 32 } View Code

1)如果test.txt不存在,那就创建test.txt,不会报错

2)如果test.txt存在,test.txt原内容不会受到影响

三、加入O_TRUNC标志

openflags = O_WRONLY | O_CREAT | O_TRUNC;

1)如果test.txt不存在,那就创建test.txt,不会报错

2)如果test.txt存在,test.txt原内容会被清空

四、权限位

1 /*================================================================ 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名称:cp.c 5 * 创 建 者:ghostwu(吴华) 6 * 创建日期:2018年01月10日 7 * 描 述:用open和write实现cp命令 8 * 9 ================================================================*/ 10 11 #include <stdio.h> 12 #include <sys/types.h> 13 #include <sys/stat.h> 14 #include <fcntl.h> 15 #include <errno.h> 16 17 int main(int argc, char *argv[]) 18 { 19 int fd, openflags; 20 mode_t fileperms; 21 22 openflags = O_WRONLY | O_CREAT | O_TRUNC; 23 24 //rwxrw-r-x 25 fileperms = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IXOTH; 26 27 fd = open( "test.txt" , openflags, fileperms ); 28 printf( "fd = %d\n", fd ); 29 if( fd < 0 ) { 30 printf( "%d\n", errno ); 31 perror( "write to file" ); 32 } 33 return 0; 34 } View Code

 五、O_APPEND追加

相关内容