首页 > 系统相关 >Linux系统编程19-fcntl

Linux系统编程19-fcntl

时间:2022-10-14 22:36:00浏览次数:41  
标签:fcntl 19 描述符 int flag fd Linux include

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

int fcntl(int fd, int cmd, ...); // arg
    参数:
        fd : 需要操作的文件描述符
        cmd: 对文件描述符如何操作
            - F_DUPFD 复制文件描述符 ,返回一个新的文件描述符
                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(非阻塞)
                    阻塞与非阻塞: 描述的是函数调用的行为

实例:为文件追加状态

fcntl.c

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

int main(int argc, char const *argv[])
{
    int fd = open("a.txt", O_RDWR);
    if (fd == -1)
    {
        perror("open err");
        return -1;
    }
    //复制文件描述符
    // int ret = fcntl(fd,F_DUPFD);

    //修改或者获取文件状态FLAG
    int flag = fcntl(fd, F_GETFL);
    //加入O_APPEND标记
    flag |= O_APPEND;
    int ret = fcntl(fd, F_SETFL, flag);
    if (ret == -1)
    {
        perror("fcntl err");
        return -1;
    }
    char *str = "\nnihao";
    write(fd, str, strlen(str));
    close(fd);

    return 0;
}

标签:fcntl,19,描述符,int,flag,fd,Linux,include
From: https://www.cnblogs.com/anqwjoe/p/16793209.html

相关文章

  • Linux系统编程08-lseek.md
    #include<sys/types.h>#include<unistd.h>off_tlseek(intfd,off_toffset,intwhence);参数:fd:文件描述符,通过open得到,用来操作某个文件offset:偏......
  • Linux系统编程09-stat和lstat
    #include<sys/types.h>#include<sys/stat.h>#include<unistd.h>intstat(constchar*pathname,structstat*statbuf);作用:获取......
  • Linux系统编程11-access
    #include<unistd.h>intaccess(constchar*pathname,intmode);作用:判断某个文件是否有某个权限,或者判断文件是否存在参数:-pathname:判断的文......
  • Linux系统编程10-模拟实现 ls -l 命令
    //-rw-rw-r--1usernamegroupname112WedSep1422:08:302022hello.txt#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<unistd.h>#......
  • Linux系统编程12-chmod
    #include<sys/stat.h>intchmod(constchar*pathname,mode_tmode);修改文件的权限参数:-pathname:需要修改文件的路径-mode:需要修......
  • Linux系统编程13-truncate.md
    #include<unistd.h>#include<sys/types.h>inttruncate(constchar*path,off_tlength);作用:缩减或扩展文件尺寸至指定的大小,长的截断,短的扩展参数:......
  • Linux系统编程15-chdir与getcwd
    #include<unistd.h>intchdir(constchar*path);作用:修改进程的工作目录比如在/home/nowcoder启动了一个可执行程序a.out,进程的工作目录就是......
  • Linux系统编程14-rename
    #include<stdio.h>intrename(constchar*oldpath,constchar*newpath);作用:重命名文件或文件夹返回值:执行成功则返回0,失败返回-1,错误原因存于errno实例:重命名目......
  • Linux系统编程16-mkdir与rmdir
    #include<sys/stat.h>#include<sys/types.h>intmkdir(constchar*pathname,mode_tmode);作用:创建一个目录参数:pathname:创建的目录的路径......
  • Linux系统编程17-opendir,readdir与closedir.md
    #include<sys/types.h>#include<dirent.h>DIR*opendir(constchar*name);作用:打开一个目录参数:-name:需要打开的目录流返回值:......