fcntl()函数之文件打开状态

比较有用的就两个。

1、获得/设置文件打开状态标志

  oldflag=fcntl(fd,F_GETFL);

  获得打开文件的状态标志。

  arg=oldflag|O_APPEND;

  fcntl(fd,F_SETFL,arg).//追加文件标志

代码如下:

/获取/设置文件打开状态标志
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
/*
#define O_CREAT 00000100 // not fcntl
#define O_EXCL 00000200 // not fcntl
#define O_NOCTTY 00000400 // not fcntl
#define O_TRUNC 00001000 // not fcntl
*/

void showFlags(int flag)
{

//O_ACCMODE 0x3 由于O_RDONLY O_WRONLY O_RDWR用低两个比特表示
switch(flag&O_ACCMODE){
case O_RDONLY:printf("O_RDONLY ");break;
case O_WRONLY:printf("O_WRONLY ");break;
case O_RDWR :printf("O_RDWR "); break;
};
////////////////////////
if(flag & O_NONBLOCK){
printf("O_NONBLOCK ");
}
if(flag & O_ASYNC){
printf("O_ASYNC ");
}
if(flag & O_APPEND){
printf("O_APPEND ");
}
putchar(' ');
}

int main(void)
{
int ret,flag,fd;

fd=open("./test.txt",O_WRONLY|O_TRUNC|O_CREAT|O_NONBLOCK|O_ASYNC,0644);
if(fd==-1)
{
perror("open");
return 1;
}
printf("open fd:%d ",fd);

//get
flag=fcntl(fd,F_GETFL);
if(flag==-1) return 2;
showFlags(flag);

printf("增加O_APPEND ");
/*
* On Linux this command can change onlythe O_APPEND,and O_NONBLOCK flags.
*/
//加入一个O_APPEND
//int arg=O_APPEND;//影响原来
int arg=flag|O_APPEND;//不影响原来
ret=fcntl(fd,F_SETFL,arg);
if(ret==-1) return 3;

//get
flag=fcntl(fd,F_GETFL);
if(flag==-1) return 2;
showFlags(flag);


printf("移除O_NONBLOCK ");
//移除O_NONBLOCK
arg=flag & (~O_NONBLOCK);
ret=fcntl(fd,F_SETFL,arg);
if(ret==-1) return 3;

//get
flag=fcntl(fd,F_GETFL);
if(flag==-1) return 2;
showFlags(flag);


close(fd);

return 0;
}

原文地址:https://www.cnblogs.com/edan/p/8833486.html