引言:在linux的文件i/o函数中在打开一个文件的时候,在不关闭文件的前提下,追加写入内容是一个很常见的操作
fcntl就是这样子的一个函数,当然他的功能可不止这些。
fcntl函数的详细说明
函数格式:
int fcntl(int fd ,int cmd ,…/arg/)
该函数是一个变参函数,但是fd和cmd是必须要有的,而后面的参数取决于cmd指令,arg常为int型
fd:文件描述符
cmd:传入的指令(一会儿详细说明)
返回值:
-1 函数执行失败(可用perror来查看具体错误原因)
取决于传入的cmd,cmd不同返回值不同,但是基本上是非零int类型
具体的fcntl函数说明可以查询man文档(原文800多页,我这只是冰山一角,如有错误还望见谅)
函数案例
以只写方式打开一个文件,然后在文件中写内容会删除原来的内容,用fcntl改变文件描述符的状态(追加写),查看文件是否被删除
代码
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc,char* argv[]){
//判断输入格式
if(argc < 2){
printf("./a.out filename mode");
exit(1);
}
//打开文件
int fd = open(argv[1],O_CREAT|O_WRONLY,777);
if( fd == -1 ){
perror("openfile");
exit(1);
}
//获取当前文件状态描述符
int flag = fcntl(fd,F_GETFL,0);
//打印未修改的时候文件状态描述符
printf("file flag is %d\n",flag);
//向文件中写内容---->此时会覆盖文件的原有内容
//因为只有一个文件指针,而且是只写打开,故会从头开始写
char buf[512]={"hello world \n"};
int count=write(fd,buf,sizeof(buf));
printf("has write %d\n",count);
//追加写操作
flag |= O_APPEND;
//改变文件状态描述符
int flg=fcntl(fd,F_SETFL,0);
//判断是否成功更改
if(flg == -1){
perror("f_setfl");
exit(1);
}
printf("==============now file flag has been changed==================\n");
//写文件
char buf2[512]={"file flag has been changed \n "};
int count1=write(fd,buf2,sizeof(buf2));
//打印添加追加写后文件状态描述符
printf("file flag is %d\n",flag);
printf("has write %d\n",count);
//关闭文件
close(fd);
return 0;
}
运行结果
未追加
添加追加写