同步拷贝文件read write fcntl

本文介绍如何使用fcntl函数获取文件状态标志,并通过F_SETFL和F_GETFL进行设置和修改。包括同步写入、只读、写入、读写、追加、非阻塞和同步写入等文件操作模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用fcntl获取文件状态标志,修改之后再设置回去


不能只是执行 F_SETFD 或者 F_SETFL,这样会关闭以前设置的标志位


#include <apue.h>
#include <errno.h>
#include <fcntl.h>

#define BUFSIZE 4096

int main(void)
{
    char buf[BUFSIZE];

    /*
     * enable to write synchronously
     * to avoid missing data while the 
     * system ecounter an error or exception
     * */
    set_fl(STDOUT_FILENO, O_SYNC);

    while(1) {
        if (read(STDIN_FILENO, buf, BUFSIZE) == BUFSIZE) 
            write(STDOUT_FILENO, buf, BUFSIZE);
        else {
            fprintf(stderr, "%s", strerror(errno)); 
            exit(EXIT_FAILURE);
        }
    }
}

/*
 * us fcntl() to set the flags
 * you should get the flags first
 * then to change the flags
 */
void set_fl(int fd, int flags)
{
    int val;

    if ((val = fcntl(fd, F_GETFL, 0)) < 0) {
        fprintf(stderr, "%s", strerror(errno));    
        exit(EXIT_FAILURE);
    }
    
    /* turn on the flags */
    val |= flags;
    //to move off you should type: val &= ~flags;
    
    if (fcntl(fd, F_SETFL, val) < 0) {
        fprintf(stderr, "%s", strerror(errno)); 
        exit(EXIT_FAILURE);
    }
}


使用 fcntl 打印文件标志符


#include<apue.h>
#include<fcntl.h>

int main( int argc, char *argv[] )
{
    int val;
    printf("%d, %s, %s \n\n", argc, argv[0], argv[1] );

    if( argc != 2 )
        printf("usage: a.out <descriptor#>");

    if( (val = fcntl( atoi(argv[1]), F_GETFL, 0 )) < 0 )     // 0 is O_RDONLY 
        printf("fcntl error for fd : %d\n", atoi(argv[1]) );

    switch( val & O_ACCMODE ){          //use O_ACCMODE to gain the visit
        case O_RDONLY :
            printf("read only\n");
            break;
        case O_WRONLY :
            printf("write only\n");
            break;
        case O_RDWR :
            printf("read write\n");
            break;
        default :
            printf("unknown access mode\n");
    }
    
    if( val & O_APPEND )
        printf("append\n");
    if( val & O_NONBLOCK ) 
        printf("nonblocking\n");
    if( val & O_SYNC )
        printf("synchronous writes\n");

#if !defined( _POSIX_C_SOURCE ) && defined( O_FSYNC ) && ( O_FSYNC != O_SYNC )
    if( val & O_FSYNC )
        printf("synchronous writes\n");
#endif

    putchar('\n');
    exit( 0 );
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值