flag函数原型:
int fcntl(int fd, int cmd, ... /* arg */ );
追加操作步骤
1.获取文件的flag属性,cmd:F_GETFL
2.修改当前的flag属性(添加新属性);
3.设置属性,cmd:F_SETFL
代码如下:
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
using namespace std;
int main(int argc,char*argv[])
{
//打开文件
int fd =open(argv[1],O_RDWR);
if(fd<0)
{
cout<<"打开失败"<<endl;
return -1;
}
//获取文件属性
int flags=fcntl(fd,F_GETFL,0);
flags=flags |O_APPEND;
fcntl(fd,F_SETFL,flags);
//写文件
write(fd,"hello,my guys!!",strlen("hello,my guys!!"));
close(fd);
return 0;
}
预期结果实在原有文件的内容后面直接追加,而并不是直接覆盖掉原有内容,检查原有文件123.log内容
更改flag属性后内容:
成功的利用fcntl函数实现文件追加。完结!!!!!!