open命令用于打开文件,使用时需要引用头文件<fcntl.h>,若失败,返回-1,否则返回正整数,0是标准输入流,1是标准输出流,2是标准错误流,其他文件从3开始递增。函数定义如下
__extern_always_inline int open (__const char *__path, int __oflag, ...) { if (__va_arg_pack_len () > 1) __open_too_many_args (); if (__builtin_constant_p (__oflag)) { if ((__oflag & O_CREAT) != 0 && __va_arg_pack_len () < 1) { __open_missing_mode (); return __open_2 (__path, __oflag); } return __open_alias (__path, __oflag, __va_arg_pack ()); } if (__va_arg_pack_len () < 1) return __open_2 (__path, __oflag); return __open_alias (__path, __oflag, __va_arg_pack ()); }
其中,__path是要打开或创建的文件路径,__oflag是标记,用来标识要打开或创建的文件所拥有的权限,由主flag和备flag组成,主flag有O_RDONLY, O_WRONLY, O_RDWR,分别表示只读,只写,读写,三者必有其一,备flag可以自由选择,常用的一个备flag是O_CREAT,用于在没有该文件的时候,在__path路径下创建该文件。一个示例代码:
#ifdef _cplusplus extern "C" { #endif #include <stdio.h> #include <string.h> #include <fcntl.h> //for open #include <stdlib.h> //for printf void main(argc, argv) int argc; char ** argv; { char * filename = "lala"; //要创建的文件 char * str = "hello, world\n"; //要向文件中写入的内容 int fd1 = open(filename, O_RDWR | O_CREAT, 0644); printf("tmp = %d\n", fd1); write(fd1, str, strlen(str) + 1); system("cat lala"); int fd2 = open(filename, O_CREAT | O_WRONLY | O_EXCL, 0600); if (-1 == fd2) { fd2 = open(filename, O_WRONLY | O_EXCL | O_TRUNC, 0600); printf("fd = %d\n", fd2); //fd2的值会比fd1大1 } close(fd1); close(fd2); system("cat lala"); } #ifdef _cplusplus } #endif
文章来源: linux open命令