1.O_TRUNC标志
使用这个标志,在调用open函数打开文件的时候会将文件原本内容全部丢弃,文件大小变为0;
测试代码
/*
* @Descripttion: sky
* @version: 1.0.0
* @Author: GECHENG
* @Date: 2021-07-26 22:38:21
* @note:
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int fd;
// 打开文件
fd =open("./src_file",O_WRONLY|O_TRUNC);
if(-1 ==fd)
{
perror("sky error");
exit(-1);
}
close(fd);
exit(0);
}
2.O_APPEND标志
如果open函数带了O_APPEND标志,调用open函数打开文件,当每次使用write()函数对文件进行写操作时,都会把文件当前位置偏移量移动到文件末尾,从文件末尾写入数据。测试代码如下
/*
* @Descripttion: sky
* @version: 1.0.0
* @Author: GECHENG
* @Date: 2021-07-26 22:38:21
* @note:
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char buffer[16];
int fd;
int ret;
fd =open("./src_file",O_RDWR|O_APPEND);
if(-1 ==fd)
{
perror("sky error");
exit(-1);
}
memset(buffer,0x55,sizeof(buffer));
ret =write(fd,buffer,4);
if(-1 ==ret)
{
perror("write error");
goto err;
}
memset(buffer,0,sizeof(buffer));
ret=lseek(fd, -4, SEEK_END);
if(-1 ==ret)
{
perror("lseek error");
goto err;
}
ret =read(fd, buffer, 4);
if(-1 ==ret)
{
perror("read error");
goto err;
}
printf("0x%x 0x%x 0x%x 0x%x\n",buffer[0],buffer[1],buffer[2],buffer[3]);
ret =0;
err:
close(fd);
exit(ret);
}