关于open函数的在不创建新文件时,打开不存在的文件的测试

来源:互联网 发布:游戏编程师工资高吗 编辑:程序博客网 时间:2024/06/02 07:00

虽然文件IO函数用过了很多次,但是发现编程总是会有疑问的地方,随着时间的渐进,我慢慢发现以前觉得懂的东西中还有很多不懂的东西和更深层次的东西等着自己的发现。
首先,我测试了open函数在不创建不存在的文件时(即不加O_CREATE),打开不存在的文件。

#include<stdio.h>#include<stdlib.h>#include<fcntl.h>#include<errno.h>int main(int argc, char *argv[]){    int fd;    if((fd = open(argv[1], O_RDWR)) == -1){        printf("%d\n", errno);        perror("open");        exit(1);    }    printf("%d\n", fd);    return 0;}

在执行打开一个并不存在的文件后,例如

willing@willing:~/TEST/open$ ./open ./a2open: No such file or directory

然后在前面的代码中加入O_CREAT进行测试,

#include<stdio.h>#include<stdlib.h>#include<fcntl.h>#include<errno.h>#include<errno.h>#include<errno.h>int main(int argc, char *argv[]){    int fd;    if((fd = open(argv[1], O_RDWR | O_CREAT)) == -1){        printf("%d\n", errno);             perror("open");                    exit(1);                       }                                  printf("%d\n", fd);    return 0;}

执行程序前:

willing@willing:~/TEST/open$ ls -ltotal 12-rwxr-xr-x 1 willing willing 5344 May 18 08:51 open-rw-r--r-- 1 willing willing  302 May 18 08:57 open.c

执行程序后

willing@willing:~/TEST/open$ ./open ./a3willing@willing:~/TEST/open$ ls -ltotal 12---------- 1 willing willing    0 May 18 08:58 a-rwxr-xr-x 1 willing willing 5344 May 18 08:58 open-rw-r--r-- 1 willing willing  302 May 18 08:57 open.c

可以看到a文件已经被建立了。

0 0
原创粉丝点击