linux-【IO系统编程】

概述

linux内核主要有五大管理功能

  • 文件管理
  • 进程管理
  • 设备管理
  • 内存管理
  • 网络管理

而本章的内容主要的内容为各种文件IO管理相关的系统接口函数的使用和讲解

0. 文件描述符

0.0 文件描述符

在 Linux 操作系统中的一切都被抽象成了文件,那么一个打开的文件是如何与应用程序进行对应呢?解决方案是使用文件描述符(file descriptor,简称fd),当在进程中打开一个现有文件或者创建一个新文件时,内核向该进程返回一个文件描述符,用于对应这个打开/新建的文件。这些文件描述符都存储在内核为每个进程维护的一个文件描述符表中。

在程序设计中,一些涉及底层的程序编写往往会围绕着文件描述符展开。但是文件描述符这一概念往往只适用于 UNIX、Linux 这样的操作系统。

在 Linux 系统中一切皆文件,系统中一切都被抽象成了文件。对这些文件的读写都需要通过文件描述符来完成。标准 C 库的文件 IO 函数使用的文件指针 FILE* 在 Linux 中也需要通过文件描述符的辅助才能完成读写操作。FILE 其实是一个结构体,其内部有一个成员就是文件描述符(下面结构体的第 25 行)。

0.1 文件描述符表

前面讲到启动一个进程就会得到一个对应的虚拟地址空间,这个虚拟地址空间分为两大部分,在内核区有专门用于进程管理的模块。Linux 的进程控制块 PCB(process control block)本质是一个叫做 task_struct 的结构体,里边包括管理进程所需的各种信息,其中有一个结构体叫做 file ,我们将它叫做文件描述符表,里边有一个整形索引表,用于存储文件描述符。

内核为每一个进程维护了一个文件描述符表,索引表中的值都是从 0 开始的,所以在不同的进程中你会看到相同的文件描述符,但是它们指向的不一定是同一个磁盘文件。

image-20230203163709426

  • 打开的最大文件数

    每一个进程对应的文件描述符表能够存储的打开的文件数是有限制的,默认为 1024 个,这个默认值是可以修改的,支持打开的最大文件数据取决于操作系统的硬件配置。

  • 默认分配的文件描述符

    当一个进程被启动之后,内核 PCB 的文件描述符表中就已经分配了三个文件描述符,这三个文件描述符对应的都是当前启动这个进程的终端文件(Linux 中一切皆文件,终端就是一个设备文件,在 /dev 目录中)

    • STDIN_FILENO:标准输入,可以通过这个文件描述符将数据输入到终端文件中,宏值为 0。
    • STDOUT_FILENO:标准输出,可以通过这个文件描述符将数据通过终端输出出来,宏值为 1。
    • STDERR_FILENO:标准错误,可以通过这个文件描述符将错误信息通过终端输出出来,宏值为 2。

    这三个默认分配的文件描述符是可以通过 close() 函数关闭掉,但是关闭之后当前进程也就不能和当前终端进行输入或者输出的信息交互了。

  • 给新打开的文件分配文件描述符

    • 因为进程启动之后,文件描述符表中的 0,1,2 就被分配出去了,因此从 3 开始分配
    • 在进程中每打开一个文件,就会给这个文件分配一个新的文件描述符,比如:
      • 通过 open() 函数打开 /hello.txt,文件描述符 3 被分配给了这个文件,保持这个打开状态,再次通过 open() 函数打开 /hello.txt,文件描述符 4 被分配给了这个文件,也就是说一个进程中不同的文件描述符打开的磁盘文件可能是同一个。
      • 通过 open() 函数打开 /hello.txt,文件描述符 3 被分配给了这个文件,将打开的文件关闭,此时文件描述符 3 就被释放了。再次通过 open() 函数打开 /hello.txt,文件描述符 3 被分配给了这个文件,也就是说打开的新文件会关联文件描述符表中最小的没有被占用的文件描述符。

0.2 总结

  1. 每个进程对应的文件描述符表默认支持打开的最大文件数为 1024,可以修改
  2. 每个进程的文件描述符表中都已经默认分配了三个文件描述符,对应的都是当前终端文件(/dev/tty)
  3. 每打开新的文件,内核会从进程的文件描述符表中找到一个空闲的没有别占用的文件描述符与其进行关联
    文件描述符表中不同的文件描述符可以对应同一个磁盘文件
  4. 每个进程文件描述符表中的文件描述符值是唯一的,不会重复

1. 系统文件IO函数

这里主要讲解文件IO主要四个函数:open read write close

1.1 open

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// 通过可变参数实现的函数重载
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

功能

打开或者创建一个文件

参数

  • char *pathname:文件路径和文件名

  • int flags:文件的打开方式,flags是一个int类型,占四个字节,32位,每一位都是一个标志位。代表着可读 可写 创建…

    • O_RDONLY 只读
    • O_WRONLY 只写
    • O_RDWR 读写

    以上三种类型必须存在一个,下面类型可选用|来连接,这样的话我们就能添加功能,如果用&的话可能就是失去一些功能

    • O_CREAT 创建一个文件
    • O_EXCL 如果使用O_CREAT时文件存在,则可以返回错误消息,这个参数可测试文件是否存在
    • O_TRUNC 打开文件(会把已经存在的内容给删除)
    • O_APPEND 追加方式打开文件(不会把已经存在的内容给删除)

返回值:

  • 成功:返回一个文件描述符,它是一个非负的正整数,即文件的ID号,相当于人的身份证,用来区别不同的文件
  • 出错:

使用例子:

场景:用open这个函数来实现linux的touch命令

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

int main(int argc, char *argv[])
{
    int fd;
    // 0777的第一个零代表八进制
    fd = open(argv[1],O_CREAT | O_RDWR, 0777);
    if (fd < 0)
    {
        printf("create file %s 失败\n", argv[1]);
        return -1;
    }
    printf("create file: %s successfully! fd = %d\n", argv[1], fd);
    close(fd);
    return 0;
}

我们尝试在命令行去编译这个c文件 输入命令运行

xrgeek@ubuntu:~/Desktop/pthread$ ./sem  junhao.txt
create file: junhao.txt successfully! fd = 3
xrgeek@ubuntu:~/Desktop/pthread$ ls -l
总用量 60
-rwxrwxr-x 1 xrgeek xrgeek 13384 1月  16 06:07 app
drwxrwxr-x 5 xrgeek xrgeek  4096 1月  19 07:14 cmake-build-debug
-rw-rw-r-- 1 xrgeek xrgeek   144 1月  19 07:03 CMakeLists.txt
-rwxrwxr-x 1 xrgeek xrgeek     0 1月  18 05:15 file.c
-rwxrwxr-x 1 xrgeek xrgeek     0 1月  20 06:46 junhao.txt
-rwxrwxr-x 1 xrgeek xrgeek 13112 1月  15 00:32 main
-rw-rw-r-- 1 xrgeek xrgeek   129 1月  20 06:42 main.c
-rw-rw-r-- 1 xrgeek xrgeek     0 1月   9 19:11 makefile
-rwxrwxr-x 1 xrgeek xrgeek  8384 1月  18 05:15 sem
-rw-rw-r-- 1 xrgeek xrgeek   350 1月  18 05:14 sem.c
xrgeek@ubuntu:~/Desktop/pthread$ ./sem  junhao.txt

我们观察到-rwxrwxr-x 1 xrgeek xrgeek 0 1月 20 06:46 junhao.txt我们创建的文件执行权限是rwxrwxr-x->775而不是我们在代码所展现的那样是777,这是为什么呢?上网查阅了资料才知道,其实open函数创建的文件的权限其实并不是直接等于我们文件的权限,而是要和一个权限掩码进行相与后再取非才得到最后的文件执行权限,即mode & umask

(111111111) &~ (000000010) = 111111101 -> 775

1.2 wirte

ssize_t write(int fd, const void *buf, size_t count);

功能:

向文件写入内容

参数:

  • fd:文件描述符,open得到的,通过这个文件描述符操作某个文件
  • buf:要往磁盘写入的数据,数据
  • count:要写的数据的实际的大小

返回值

  • 成功:>0: 返回实际的读取到的字节数,=0:文件已经读取完了
  • 失败:-1 ,并且设置errno

使用用例

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

int main(int argc, char *argv[])
{
    char* buff = "junhaoshizhendeshuai!!!!!!!!!!!!";
    int fd;
    fd = open(argv[1], O_RDWR);
    if (fd < 0)
    {
        printf("open file %s 失败\n", argv[1]);
        return -1;
    }
    write(fd, buff, 30);
    close(fd);
    return 0;
}

1.3 read

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

功能:

read函数试图从文件描述符fd所指定的文件读取内容到buf所指定的内存当中。在支持读取的文件中,读操作从当前文件偏移开始,随着读取字节的增加,文件偏移也会增加。如果文件偏移达到了文件末尾,无字节可读,read函数会返回0

参数:

  • fd:文件描述符,open得到的,通过这个文件描述符操作某个文件
  • buf:需要读取数据存放的地方,数组的地址(传出参数)
  • count:指定的数组的大小

返回值:

  • 成功:如果读取成功,会返回读到内容的字节大小。
  • 失败:如果出现错误,函数返回-1,并且会将errno这个全局变量设置成合适的值。

1.4 lseek

#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);

功能:

调整读写文件的指针

参数:

  • fd:文件描述符
  • offset:文件的偏移量
  • whence:当前位置的基点,有三个标志位
    • SEEK_SET:当前位置为文件的开头,新位置为偏移量的大小
    • SEEK_CUR:当前位置为文件指针的位置,新位置为当前位置加上偏移量
    • SEEK_END:当前位置为文件的结尾,新位置为文件的大小加上偏移量的大小

返回值:

  • 成功:返回文件指针的位置

  • 失败:-1

例子

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

int main(int argc, char *argv[])
{
    char* buff = "junhaoshizhendeshuai";
    char buff1[20] = {0};
    int fd;
    fd = open(argv[1], O_RDWR);
    if (fd < 0)
    {
        printf("open file %s 失败\n", argv[1]);
        return -1;
    }
    write(fd, buff, 30);
    lseek(fd, -15, SEEK_CUR);
    read(fd, buff1, 20);
    printf("%s\n", buff1);
    close(fd);
    return 0;
}

解释一下这个例子:

我们接收了命令行传过来的文件名,用可读写模式打开,把一段字符串写入这个文件中,此时指针在字符串的最后,我们用lseek函数往前移动三个字符,再将往后的字符写入buff1中,最后关闭文件

1.5 close

功能:

可以关闭一个打开的文件

返回值

成功返回0,出错返回-1,并设置ERRNO

ps:当一个进程终止时,该进程打开的所有文件都由内核自动关闭

1.6 stat

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int stat(const char *pathname, struct stat *statbuf);

功能:

获取一个文件相关的一些信息

参数:

  • pathname:操作的文件的路径
  • statbuf:结构体变量,传出参数,用于保存获取到的文件的信息
struct stat {
               dev_t     st_dev;         /* ID of device containing file */
               ino_t     st_ino;         /* Inode number */
               mode_t    st_mode;        /* File type and mode */
               nlink_t   st_nlink;       /* Number of hard links */
               uid_t     st_uid;         /* User ID of owner */
               gid_t     st_gid;         /* Group ID of owner */
               dev_t     st_rdev;        /* Device ID (if special file) */
               off_t     st_size;        /* Total size, in bytes */
               blksize_t st_blksize;     /* Block size for filesystem I/O */
               blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

               /* Since Linux 2.6, the kernel supports nanosecond
                  precision for the following timestamp fields.
                  For the details before Linux 2.6, see NOTES. */

               struct timespec st_atim;  /* Time of last access */
               struct timespec st_mtim;  /* Time of last modification */
               struct timespec st_ctim;  /* Time of last status change */

           #define st_atime st_atim.tv_sec      /* Backward compatibility */
           #define st_mtime st_mtim.tv_sec
           #define st_ctime st_ctim.tv_sec
           };

返回值:

  • 成功:返回0
  • 失败:-1

例子

#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
    struct stat stat_buf;
    int ret = stat("english.txt", &stat_buf);
    if (ret == -1)
    {
        perror("stat");
        return -1;
    }
    printf("size of file is: %ld\n", stat_buf.st_size);
    return 0;
    
}

1.7 lstat

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int lstat(const char *pathname, struct stat *statbuf);

功能:

获取一个软链接文件相关的一些信息

参数:

  • pathname:操作的文件的路径
  • statbuf:结构体变量,传出参数,用于保存获取到的文件的信息

返回值:

  • 成功:返回0
  • 失败:-1

1.8 实现cp命令

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main()
{
    // 1. 打开文件
    int src_fd = open("./english.txt",  O_RDONLY);
    if (src_fd == -1)
    {
        perror("open");
        return -1;
    }
    // 2. 创建一个新的文件
    int dest_fd = open("_copy.txt", O_CREAT | O_WRONLY, 0664);
    // 3. 读写操作
    if (dest_fd == -1)
    {
        perror("open");
        return -1;
    }

    // 3. 频繁的读写操作
    char buf[1024] = {0};

    int len = 0;

    while ((len = read(src_fd, buf, sizeof(buf))) > 0)
    {
        write(dest_fd, buf, len);
    }
    // 4. 关闭文件
    close(src_fd);
    close(dest_fd);
    return 0;
}

1.9 实现ls -l命令功能

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <string.h>

// 模拟实现 ls -l 指令
// -rw-rw-r-- 1 nowcoder nowcoder 12 12月  3 15:48 a.txt
int main(int argc, char * argv[]) {

    // 判断输入的参数是否正确
    if(argc < 2) {
        printf("%s filename\n", argv[0]);
        return -1;
    }

    // 通过stat函数获取用户传入的文件的信息
    struct stat st;
    int ret = stat(argv[1], &st);
    if(ret == -1) {
        perror("stat");
        return -1;
    }

    // 获取文件类型和文件权限
    char perms[11] = {0};   // 用于保存文件类型和文件权限的字符串

    switch(st.st_mode & S_IFMT) {
        case S_IFLNK:
            perms[0] = 'l';
            break;
        case S_IFDIR:
            perms[0] = 'd';
            break;
        case S_IFREG:
            perms[0] = '-';
            break; 
        case S_IFBLK:
            perms[0] = 'b';
            break; 
        case S_IFCHR:
            perms[0] = 'c';
            break; 
        case S_IFSOCK:
            perms[0] = 's';
            break;
        case S_IFIFO:
            perms[0] = 'p';
            break;
        default:
            perms[0] = '?';
            break;
    }

    // 判断文件的访问权限

    // 文件所有者
    perms[1] = (st.st_mode & S_IRUSR) ? 'r' : '-';
    perms[2] = (st.st_mode & S_IWUSR) ? 'w' : '-';
    perms[3] = (st.st_mode & S_IXUSR) ? 'x' : '-';

    // 文件所在组
    perms[4] = (st.st_mode & S_IRGRP) ? 'r' : '-';
    perms[5] = (st.st_mode & S_IWGRP) ? 'w' : '-';
    perms[6] = (st.st_mode & S_IXGRP) ? 'x' : '-';

    // 其他人
    perms[7] = (st.st_mode & S_IROTH) ? 'r' : '-';
    perms[8] = (st.st_mode & S_IWOTH) ? 'w' : '-';
    perms[9] = (st.st_mode & S_IXOTH) ? 'x' : '-';

    // 硬连接数
    int linkNum = st.st_nlink;

    // 文件所有者
    char * fileUser = getpwuid(st.st_uid)->pw_name;

    // 文件所在组
    char * fileGrp = getgrgid(st.st_gid)->gr_name;

    // 文件大小
    long int fileSize = st.st_size;

    // 获取修改的时间
    char * time = ctime(&st.st_mtime);

    char mtime[512] = {0};
    strncpy(mtime, time, strlen(time) - 1);

    char buf[1024];
    sprintf(buf, "%s %d %s %s %ld %s %s", perms, linkNum, fileUser, fileGrp, fileSize, mtime, argv[1]);

    printf("%s\n", buf);

    return 0;
}

1.10 access

#include <unistd.h>
int access(const char *pathname, int mode);

功能:

判断某个文件是否有某个权限,或者判断文件是否存在

参数:

  • pathname:操作的文件的路径
  • mode:
    • R_OK: 判断是否有读权限
    • W_OK: 判断是否有写权限
    • X_OK: 判断是否有执行权限
    • F_OK: 判断文件是否存在

返回值:

  • 成功:返回0
  • 失败:-1

例子

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

int main() {

    int ret = access("a.txt", F_OK);
    if(ret == -1) {
        perror("access");
    }

    printf("文件存在!!!\n");

    return 0;
}

1.11 chmod

#include <sys/stat.h>
int chmod(const char *pathname, mode_t mode);

功能:

修改文件的权限

参数:

  • pathname:操作的文件的路径
  • mode: 需要修改的权限值,八进制的数

返回值:

  • 成功:返回0
  • 失败:-1

例子

#include <sys/stat.h>
#include <stdio.h>
int main() {
    int ret = chmod("a.txt", 0777);
    if(ret == -1) {
        perror("chmod");
        return -1;
    }
    return 0;
}

1.12 truncate

功能:

缩减或者扩展文件的尺寸至指定的大小

参数:

  • path:操作的文件的路径
  • length: 需需要最终文件变成的大小

返回值:

  • 成功:返回0
  • 失败:-1

例子

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>

int main() {

    int ret = truncate("b.txt", 5);

    if(ret == -1) {
        perror("truncate");
        return -1;
    }

    return 0;
}

1.13 mkdir

#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);

功能:

创建一个目录

参数:

  • path:创建的目录的路径
  • mode: 权限,八进制的数

返回值:

  • 成功:返回0
  • 失败:-1

例子

#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>

int main() {

    int ret = mkdir("aaa", 0777);

    if(ret == -1) {
        perror("mkdir");
        return -1;
    }

    return 0;
}

1.14 chdir

#include <unistd.h>
int chdir(const char *path);

功能:

修改进程的工作目录,比如在/home/nowcoder 启动了一个可执行程序a.out, 进程的工作目录 /home/nowcoder

参数:

  • path:需要修改的工作目录

返回值:

  • 成功:返回0
  • 失败:-1
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main() {

    // 获取当前的工作目录
    char buf[128];
    getcwd(buf, sizeof(buf));
    printf("当前的工作目录是:%s\n", buf);

    // 修改工作目录
    int ret = chdir("/home/nowcoder/Linux/lesson13");
    if(ret == -1) {
        perror("chdir");
        return -1;
    } 

    // 创建一个新的文件
    int fd = open("chdir.txt", O_CREAT | O_RDWR, 0664);
    if(fd == -1) {
        perror("open");
        return -1;
    }

    close(fd);

    // 获取当前的工作目录
    char buf1[128];
    getcwd(buf1, sizeof(buf1));
    printf("当前的工作目录是:%s\n", buf1);
    
    return 0;
}

1.15 getcwd

#include <unistd.h>
char *getcwd(char *buf, size_t size);

功能:

获取当前工作目录

参数:

  • buf:需要修改的工作目录
  • size:数组的大小

返回值:

返回的指针指向的一块内存,这个数据就是第一个参数

1.16 rename

#include <stdio.h>
int rename(const char *oldpath, const char *newpath);

功能:

修改文件的名称

参数:

  • oldpath:需要修改的工作目录
  • newpath:新的文件目录

返回值:

  • 成功:返回0
  • 失败:-1

1.17 opendir

#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);

功能:

打开一个文件目录

参数:

  • name:工作目录名

返回值:

  • 成功:DIR * 类型,理解为目录流
  • 失败:错误返回NULL

1.18 readdir

#include <dirent.h>
struct dirent *readdir(DIR *dirp);

功能:

读取文件目录

参数:

  • dirp:dirp是opendir返回的结果

返回值:

  • 成功:struct dirent,代表读取到的文件的信息
  • 失败:读取到了末尾或者失败了,返回NULL

1.19 closedir

#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);

功能:

关闭目录

参数:

  • dirp:dirp是opendir返回的结果

返回值:

返回值:

  • 成功:0
  • 失败:-1

例子:读取某个目录下所有的普通文件的个数

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int getFileNum(const char * path);

// 读取某个目录下所有的普通文件的个数
int main(int argc, char * argv[]) {

    if(argc < 2) {
        printf("%s path\n", argv[0]);
        return -1;
    }

    int num = getFileNum(argv[1]);

    printf("普通文件的个数为:%d\n", num);

    return 0;
}

// 用于获取目录下所有普通文件的个数
int getFileNum(const char * path) {

    // 1.打开目录
    DIR * dir = opendir(path);

    if(dir == NULL) {
        perror("opendir");
        exit(0);
    }

    struct dirent *ptr;

    // 记录普通文件的个数
    int total = 0;

    while((ptr = readdir(dir)) != NULL) {

        // 获取名称
        char * dname = ptr->d_name;

        // 忽略掉. 和..
        if(strcmp(dname, ".") == 0 || strcmp(dname, "..") == 0) {
            continue;
        }

        // 判断是否是普通文件还是目录
        if(ptr->d_type == DT_DIR) {
            // 目录,需要继续读取这个目录
            char newpath[256];
            sprintf(newpath, "%s/%s", path, dname);
            total += getFileNum(newpath);
        }

        if(ptr->d_type == DT_REG) {
            // 普通文件
            total++;
        }


    }

    // 关闭目录
    closedir(dir);

    return total;
}

1.20 dup

#include <unistd.h>
int dup(int oldfd);

功能:

复制一个新的文件描述符

fd=3, int fd1 = dup(fd),
fd指向的是a.txt, fd1也是指向a.txt
从空闲的文件描述符表中找一个最小的,作为新的拷贝的文件描述符

参数:

  • oldfd:旧的文件描述符

返回值:

  • 成功:0
  • 失败:-1

例子

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

int main() {

    int fd = open("a.txt", O_RDWR | O_CREAT, 0664);

    int fd1 = dup(fd);

    if(fd1 == -1) {
        perror("dup");
        return -1;
    }

    printf("fd : %d , fd1 : %d\n", fd, fd1);

    close(fd);

    char * str = "hello,world";
    int ret = write(fd1, str, strlen(str));
    if(ret == -1) {
        perror("write");
        return -1;
    }

    close(fd1);

    return 0;
}

1.21 dup2

#include <unistd.h>
int dup2(int oldfd, int newfd);

功能:

重定向文件描述符
oldfd 指向 a.txt, newfd 指向 b.txt
调用函数成功后:newfd 和 b.txt 做close, newfd 指向了 a.txt
oldfd 必须是一个有效的文件描述符
oldfdnewfd值相同,相当于什么都没有做

参数:

  • oldfd:旧的文件描述符

返回值:

  • 成功:0
  • 失败:-1
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main() {

    int fd = open("1.txt", O_RDWR | O_CREAT, 0664);
    if(fd == -1) {
        perror("open");
        return -1;
    }

    int fd1 = open("2.txt", O_RDWR | O_CREAT, 0664);
    if(fd1 == -1) {
        perror("open");
        return -1;
    }

    printf("fd : %d, fd1 : %d\n", fd, fd1);

    int fd2 = dup2(fd, fd1);
    if(fd2 == -1) {
        perror("dup2");
        return -1;
    }

    // 通过fd1去写数据,实际操作的是1.txt,而不是2.txt
    char * str = "hello, dup2";
    int len = write(fd1, str, strlen(str));

    if(len == -1) {
        perror("write");
        return -1;
    }

    printf("fd : %d, fd1 : %d, fd2 : %d\n", fd, fd1, fd2);

    close(fd);
    close(fd1);

    return 0;
}

1.22 fnctl

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

int fcntl(int fd, int cmd, ...);

功能:

对文件描述符做一些操作

参数

  • fd:表示需要操作的文件描述符
  • cmd:表示对文件描述符进行如何操作
    • F_DUPFD:复制文件描述符,复制的是第一个参数fd,得到一个新的文件描述符(返回值)
    • F_GETFL: 获取指定的文件描述符文件状态flag
    • F_SETFL:设置文件描述符文件状态flag
      • 必选项:O_RDONLY, O_WRONLY, O_RDWR 不可以被修改
      • 可选性:O_APPEND, NONBLOCK
        O_APPEND 表示追加数据
        NONBLOK 设置成非阻塞

返回值:

  • 成功:0
  • 失败:-1
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

int main() {

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

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

    // 获取文件描述符状态flag
    int flag = fcntl(fd, F_GETFL);
    if(flag == -1) {
        perror("fcntl");
        return -1;
    }
    flag |= O_APPEND;   // flag = flag | O_APPEND

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

    char * str = "nihao";
    write(fd, str, strlen(str));

    close(fd);

    return 0;
}

2. 标准c库IO函数和linux系统函数的区别和联系

2.1 区别

在这里插入图片描述

  • 标准c库IO函数是跨平台的,你在linux去写了一个程序,在window,mac也能够运行,qt也是这个原理。那么为什么它能够实现跨平台呢?java虚拟机是实现跨平台的一种方式,通过运行不同的虚拟机在不同的平台上。而标准c库IO函数是通过调用不同平台的系统io函数来实现的,例如如果它在window上运行就会调用window的系统io函数,而在linux上运行就调用linux的系统io函数
  • 标准c库IO函数封装后变得更高级了,它有一个IO缓存区,例如我们fwrite往文件里面去写数据,fwrite的声明为:
    size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);当我们调用这个函数往文件写入数据时不是一下子就把它写到磁盘上去而是先写到缓冲区,然后调用系统io函数write把它写到磁盘去,值得注意的是写入磁盘是和硬件打交道,那就需要从用户态转成内核态,这种状态的更换是非常消耗cpu的资源的,磁盘缓冲区的作用就在于提升执行的效率,之前我们是写入磁盘,现在是写入内存,cpu和内存交换数据的效率是远大于和磁盘交换数据的,只有当刷新缓冲区缓冲区已满正常关闭函数,这三种情况才会将数据写入到缓冲区。缓冲区的大小是默认为8k

2.2 关系

那么c文件库函数和linux系统io函数是什么关系呢?
很明显它们是调用和被调用的关系,例如我们调用了c语言的库函数fopen,那么它会调用linux系统底层的open函数,

2.3 使用场景

  • 当我们做网络通信的时候,就需要使用linux的系统io函数,我给你发了一段话总不能存到缓存区里面吧?
  • 而当我们去做磁盘的数据交换时就应该使用标准c库IO函数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值