在上一篇中学习了一下open函数的基本用法,这里就要练习一下。计算机就是要实践嘛。
用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 ", fd); return 0; }
open函数第二个参数是文件打开的标志,比如只读(O_RDONLY)等,还有副标志(O_CREAT,O_TRUNC)等。主标志是互斥的,但是我不知道居然可以不指定主标志,而只用副标志。
然后第三个参数指定了创建文件的权限位。
open()一个文件,返回的描述符从3开始增加(0,1,2分别是标准输出,标准输入和标准错误)
由于umask一开始是022(我用的是root),所以创建出来的权限不是777,而是755,设置umask为000之后再执行以下创建出的abc的权限位就是777了。
传入参数作为文件名
/* * open a file with pathname from arguments * tuhooo */ #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("usage: ./open filename "); exit(1); } if((fd = open(argv[1], O_CREAT | O_RDWR, 0644)) == -1) { printf("file open error! "); exit(1); } printf("fd = %d ", fd); }
原来O_CREAT如果在文件存在的时候不会去创建的,我还以为会把原来文件的内容清空呢。
果然在标志位加上O_TRUNC之后文件的内容就被清空掉了。
直接在权限位写数字是不是有点硬编码了。
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, world this is first sentence I write to this file"; /* argc */ if(argc < 2) { printf("./open filename "); exit(1); } /* if open file correctly */ if((fd = open(argv[1], O_CREAT | O_RDWR, 0644)) == -1) { printf("open file error "); exit(1); } /* write something */ write(fd, buf, strlen(buf)); printf("fd = %d ", fd); /* close fd */ close(fd); return 0; }
这个例子看上去还挺简单的,就是加了一个write函数在这里了。
好像这就把open函数学完了,掌握了这几个例子,打开或者创建文件就不是问题啦。
原文:https://blog.csdn.net/tengfei_scut/article/details/70213099