今天学习的内容有比较多:
我计划今天多学习一些,学太少了需要耗费太多时间了,我准备抓紧进度了
=======================================================
文件的创建与打开的补充:
O_EXCL:
当文件已经存在时,则打开失败;那么我们便这样编写代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;
fd=open("./file1",O_RDWR|O_CREAT|O_EXCL,0600);
if(fd==-1)
{
printf("file1 has created!\n"); //文件存在打开失败,fd=-1
}
if(fd > 0)
{
printf("file1 creat success\n");
}
return 0;
}
我们运行看看结果,看看是否是正确的。
删除之后,我们运行./a.out则新建file1成功,当file1存在时我们再运行一次试试:
这个时候便是文件已经创建完成!
O_APPEND:
在了解这个之前,我们先看看下面的这些代码:这是之前用过的文件的写入
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "Hello Wrold!Linux";
fd=open("./file1",O_RDWR);
printf("open success : fd=%d",fd);
write(fd,buf,strlen(buf));
return 0;
}
当我们在文本中写入东西的时候
我们再运行./a.out试试看看现象
不过呢,我们也需要知道一个小现象,那就是他是从头开始覆盖,如果原先的文本内容字节数超过新覆盖的内容的话,则新内容只会覆盖掉自己字节数对应的原先的部分,就例如:
原先12345678
我要覆盖的内容是abcde
那么我们最后得到的内容就是:abcde678
之前写入的东西都被覆盖掉了,该如何解决不要覆盖,又可以写入东西呢?我们就需要用到它了:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "Hello Wrold!Linux";
fd=open("./file1",O_RDWR|O_APPEND);
printf("open success : fd=%d",fd);
write(fd,buf,strlen(buf));
return 0;
}
我们运行一下并看看结果如何
便可以发现,文本内容没被覆盖,新的文本内容另起了一行编写进去
这个功能就让我们想到了之前玩过的宝可梦游戏,我们可以新建存档,也可以覆盖掉一个存档,大致原理也应该如此吧哈哈哈哈!
O_TRUNC:
这个与上面的大同小异,它是完完全全舍弃掉原先的所有文本内容,转而写入新的文本内容,可以看作新建重写:
我们的代码如下,让我们来测试一下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "Hello Wrold!Linux";
fd=open("./file1",O_RDWR|O_TRUNC);
printf("open success : fd=%d",fd);
write(fd,buf,strlen(buf));
return 0;
}
开始我们编写这么长的文本,我们运行一下我们代码试试: 结果显而易见,已经完全覆盖掉了。
创建文件creat函数
老规矩使用man命令查看手册看一下使用指南:
我们这么编写代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "Hello Wrold!Linux";
fd= creat("/home/tang/桌面/file1",S_IRWXU); //s_irwxu 可读写执行
//int open(const char *pathname, int flags, mode_t mode);
}
我们编译一下:
在这可以看到file1创建成功,而且file1是一个可读写执行的文件
完成!