Linux open()函数练习

来源:互联网 发布:cmd登录oracle数据库 编辑:程序博客网 时间:2024/05/16 19:10

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;}


0 0