Linux open()函数练习

1、先用man 2 open查看一下open函数接口


2、最简单的open函数代码

  #include <sys/types.h>
  #include <sys/stat.h>
  #include <fcntl.h>
  #include<stdio.h>
  int main()
  {
           int fd;
           fd=open("abc",O_CREAT,0777);
          printf("fd=%d\n",fd);
  
          return 0;
  
  }



3、open()一个文件,返回的文件描述符从3开始增加,参数O_CREAT表示当“abc”不存在时创建一个,但是由于umask一开始是002,所以创建出来的权限不是777,而是775,设置umask为000之后再执行一下创建出来的abc的权限位就是777了。


4、open时传入一个参数

#include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
#include<stdlib.h>
#include<stdio.h>
int main(int argc,char *argv[])
{
        int fd; 
        if(argc<2){
                printf("./open filename\n");
                exit(1);//<stdlib.h>
        }
        fd=open(argv[1],O_CREAT,0644);
        printf("fd=%d\n",fd);
    
        return 0;

}


4、open()一个文件,不存在的话就创建一个,并且往文件里面写东西

 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main(int argc,char *argv[])
{
        int fd; 
        char buf[1024]="hello tengfei";
        if(argc<2){
                printf("./open filename\n");
                exit(1);//<stdlib.h>
        }
        fd=open(argv[1],O_CREAT | O_RDWR,0644);
        write(fd,buf,strlen(buf));
        printf("fd=%d\n",fd);
        close(fd);     
        return 0;

}


  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值