天天看点

Linux系统编程中O_APPEND和O_TRUNC标志的使用方法。

      大家好!

      今天主要和大家聊一聊,open函数的的flags标志,譬如:O_APPEND和O_TRUNC标志的使用方法。

Linux系统编程中O_APPEND和O_TRUNC标志的使用方法。

目录

​​第一:O_TRUNC标志使用方法​​

​​第二:O_APPEND使用方法​​

​第一:O_TRUNC标志使用方法

       使用该标志O_TRUNC的时候,调用open函数打开文件的时候会将文件原本的内容全部丢弃,文件大小变为0;下面对文件的操作代码如下:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#icclude <stdlib.h>
int main(void)
{
 int fd;
 /* 打开文件 */
 fd = open("./test_file", O_WRONLY | O_TRUNC);
 if (-1 == fd) {
 perror("open error");
 exit(-1);
 }
 /* 关闭文件 */
 close(fd);
 exit(0);
}      

     在当前目录下有一个文件test_file,测试代码中使用了O_TRUNC标志打开该文件,代码中仅仅只是打开文件,并没有对其进行读写操作,接下来编译运行来看看测试结果;

Linux系统编程中O_APPEND和O_TRUNC标志的使用方法。

第二:O_APPEND使用方法

    接下来聊一聊,使用O_APPEND标志方法,如果open函数携带并使用了O_APPEND标志,调用open函数打开文件,当每次使用write()函数对文件进行读写操作时,都会自动把文件当前位置偏移量移动到文件末尾,从文件末尾开始写入数据,也就是意味着每次写入数据都是从文件末尾开始。这里我们直接进行测试,测试代码如下所示:

#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("./test_file", O_RDWR | O_APPEND);
 if (-1 == fd) {
 perror("open error");
 exit(-1);
 }
 /* 初始化 buffer 中的数据 */
 memset(buffer, 0x55, sizeof(buffer));
 /* 写入数据: 写入 4 个字节数据 */
 ret = write(fd, buffer, 4);
 if (-1 == ret) {
 perror("write error");
 goto err;
 }
 /* 将 buffer 缓冲区中的数据全部清 0 */
 memset(buffer, 0x00, sizeof(buffer));
 /* 将位置偏移量移动到距离文件末尾 4 个字节处 */
 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);  
}      

继续阅读