fcntl函数



    #include <unistd.h>
    #include <fcntl.h>

    int fcntl(int fd, int cmd, ...);
    参数:
        fd : 表示需要操作的文件描述符
        cmd: 表示对文件描述符进行如何操作
            - F_DUPFD : 复制文件描述符,复制的是第一个参数fd,得到一个新的文件描述符(返回值)
                int ret = fcntl(fd, F_DUPFD);

            - F_GETFL : 获取指定的文件描述符文件状态flag
              获取的flag和我们通过open函数传递的flag是一个东西。

            - F_SETFL : 设置文件描述符文件状态flag
              必选项:O_RDONLY, O_WRONLY, O_RDWR 不可以被修改
              可选性:O_APPEND, O_NONBLOCK
                O_APPEND 表示追加数据
                NONBLOK 设置成非阻塞
        
        阻塞和非阻塞:描述的是函数调用的行为。
*/
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(){

    //复制文件描述符
    //int fd = open("1.txt",O_RDONLY);
    //int ret = fcntl(fd, F_DUPFD);

    //2.修改或者获取文件状态flag
    int fd = open("a.txt",O_RDWR);
    if(fd == -1){
        perror("open");
        return -1;
    }

    //获取文件描述符状态flag
    int flag = fcntl(fd, F_GETFL);
    flag |= O_APPEND;
    //修改文件描述符状态的flag,给flag加上O_APPEND这个标记
    int ret = fcntl(fd, F_SETFL, flag); 
    if(ret == -1){
        perror("fcntl");
        return -1;
    }

    char * str = "nihaoya";
    int ret1 = write(fd,str,strlen(str));
    if(ret1 == -1){
        perror("write");
        return -1;
    }

    close(fd);
    return 0;
}

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值