章贡区网站建设一个新品牌怎样营销推广
作用:使用open()打开或创建文件,为后面对文件进行操作做准备。
ubuntu所在目录:usr/include/fcntl.h
在<fcntl.h>里声明
extern int open (const char *__file, int __oflag, …);
参数解析:
一、第一个参数filename:指定路径的文件名字
二、第二个参数flags:对打开或创建的文件的操作权限
1.必选项
1).O_RDONLY //只读
2).O_WRONLY //只写
3).O_RDWR //读写
2.可选项
1).O_CREAT //如果指定文件不存在,创建文件
注:Linux用open创建的文件,其实际的操作权限为代码里设置的权限和本地掩码按位与(&)
2).O_EXCL //和O_CREAT一起使用,可以判断文件是否存在
3).O_TRUNC //截断文件,当文件存在且可写打开时,使文件长度为0,并清空文件的内容
三、第三个参数,一般在创建文件的时候给创建的文件操作权限,与O_CREAT一起使用
测试代码
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h> //open()
#include<unistd.h> //close()
#include<stdlib.h> //exit()
#include<stdio.h> //perror()int main(void)
{int fd1; //文件描述符:一个整形数组(0~1023),0~2为系统默认打开的文件int res;#ifdef HELLO//打开一个不存在的文件fd1 = open("hello",O_RDWR); //返回对应的文件描述符,第一个参数是文件路径及名称,第二个参数为操作方式,O_RDWR为读操作if(fd1 == -1) //-1 表示失败{perror("open file hello"); //perror打印错误信息,系统的errno代表的文字信息exit(1);}else{printf("open hello fd1 = %d\n",fd1);//关闭文件res = close(fd1); //传递要关闭的文件的文件描述符printf("close fd1 res = %d\n",res); //返回0关闭成功,-1失败if(res == -1){perror("close fd1");exit(1);}}
#endif//打开一个已经存在的文件int fd2 = open("hello_open.c",O_RDWR);if(fd2 == -1){perror("open file hello_open.c");exit(1);}else{printf("hello_open.c fd2 = %d\n",fd2);res = close(fd2); printf("close fd2 res = %d\n",res); if(res == -1){perror("close fd2");exit(1);}}//创建新文件:O_CREATint fd3 = open("CreateFile", O_CREAT | O_RDWR, 0777); if(fd3 == -1){perror("create file");exit(1);}else {printf("CreatFile fd3 = %d\n",fd3);res = close(fd3); printf("close fd3 res = %d\n",res); if(res == -1){perror("close fd3");exit(1);}}//#define EXCL
#ifdef EXCL//判断文件是否存在:O_EXCLint fd4 = open("CreateFile", O_CREAT | O_EXCL | O_RDWR, 0777);if(fd4 == -1){ //文件已经存在,创建失败perror("create and testEXCL file");exit(1);}else {printf("EXCLtest fd4 = %d\n",fd4);res = close(fd4); printf("close fd4 res = %d\n",res); if(res == -1){perror("close fd4");exit(1);}}
#endif#define TRUNC
#ifdef TRUNC //将文件截断为0int fd5 = open("hello_open.c", O_RDWR | O_TRUNC);if(fd5 == -1){perror("trunc file");exit(1);}else {printf("trunc fd5 = %d\n",fd5);res = close(fd5); printf("close fd5 res = %d\n",res); if(res == -1){perror("close fd5");exit(1);}}
#endif return 0;
}
注:O_TRUNC 使用前后对比
zhangqu@zhangqu:~/system_function_test/IO/open$ ls -l hello_open.c
-rw-rw-r-- 1 zhangqu zhangqu 97 5月 6 22:02 hello_open.c
zhangqu@zhangqu:~/system_function_test/IO/open$ gcc open_test.c -o myopen
zhangqu@zhangqu:~/system_function_test/IO/open$ ./myopen
hello_open.c fd2 = 3
close fd2 res = 0
CreatFile fd3 = 3
close fd3 res = 0
trunc fd5 = 3
close fd5 res = 0
zhangqu@zhangqu:~/system_function_test/IO/open$ ls -l hello_open.c
-rw-rw-r-- 1 zhangqu zhangqu 0 5月 6 22:05 hello_open.c
zhangqu@zhangqu:~/system_function_test/IO/open$