虽然文件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 ./a
2
open: 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 -l
total 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 ./a
3
willing@willing:~/TEST/open$ ls -l
total 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文件已经被建立了。
版权声明:本文为u011770788原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。