zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    JAVA练习3
    JAVA练习2
    找出一个整型数组中元素最大值,使用面向对象方法
    类和对象应用例题
    用指针变量作函数形参接收数组地址,解决10个整数按由大到小顺序排序问题
    把指针作为函数参数的方法处理从大到小排序问题。
    通过指针变量访问整型变量
    用选择法对数组中10个整数进行排列
    有参函数的调用
    函数模板
  • 原文地址:https://www.cnblogs.com/edan/p/8833486.html
Copyright © 2011-2022 走看看