在LINUX里打开和创建文件

在LINUX里打开和创建文件

1 open函数的头文件以及格式

在linux里面 输入 man 2 open函数就能得到

 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>

 int open(const char *pathname, int flags);
 int open(const char *pathname, int flags, mode_t mode);

2 open参数pathname中常用的三种文件打开方式

O_RDONLY 以只读方式打开文件

O_WRONLY 以只写方式打开文件

O_RDWR 以可读写方式打开文件。上述三种旗标是互斥的,也就是不可同时使用,但可与下列的旗标利用OR(|)运算符组合。

3 打开当前目录下已存在的文件

我们可以先在当前目录下创建一个file1,并且在代码中打开,并且输出open函数的返回值。

  1 #include <stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <fcntl.h>
  5 int main()
  6 {
  7         int fd;
  8         fd = open("./file1",O_RDWR);
  9         printf("fd = %d\n",fd);
 10         return 0;
 11 }
~       

当前目录下有这个文件时,会打开文件file1并且打印fd = 3没有这个文件时,就会打印fd = -1,打开文件失败;

4 如果当前目录没有这个文件,那我们就创造这个文件 并且将文件格式设置为可读可写

  1 #include <stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <fcntl.h>
  5 int main()
  6 {
  7         int fd;
  8         fd = open("./file1",O_RDWR);
  9         if (fd == -1){
 10                 printf("open file failed!\n");
 11         		fd = open("./file1",O_RDWR|O_CREAT,0600);
 12         }
 13         printf("file creat\n");
 14         printf("fd = %d\n",fd);
 15         return 0;
 16 }
~        

当fd等于-1时,打印打开文件失败,并且创建一个文件,文件为可读可写

fd = open("./file1",O_RDWR|O_CREAT,0600);

0_RDWR和O_CREAT是打开文件方式是可读可写,或者是如果当前目录下没有,就创建文件,权限是0600,6是读4 加上写 2等于6。

5 open函数的返回值

open的返回值是整型数,可以直接int fd 一个参数来接收open函数的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值