Linux文件IO

标准IO

源于Unix。对与系统IO ,当我们调用read,write读写数据的时候,操作系统会进入到内核来去调用这些api,但是如果是多次循环读写的话频繁的进入内核是和消耗性能的。所以标准的IO(fopen、fread、fwrite)会有一个用户buffer来缓存文件的数据,当使用fread或者fwrite的时候会直接在这个buffer里面读取,而不需要去频繁的进入内核。当buffer被用满了之后,才会调用read或者write进入到内核读取数据放到buffer中。

一、打开文件

cpp 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <error.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

// 打开文件
int main(int argc, char** argv) {
    int fd;
    if (argc != 2) {
        printf("Usage: %s <file>\n", argv[0]);
        return -1;
    }
    fd = open(argv[1], O_RDWR);
    if (fd < 0) {
        printf("can not open file %s\n", argv[1]);
        printf("errno = %d\n", errno); // 打印错误信息
        printf("err: %s\n", strerror(errno));
        // 这里更加简单,效果等同于上面两个
        perror("open");
    }
    else {
        printf("fd: %d\n", fd);
    }
    while (1)
    {
        sleep(10);
    }
    close(fd);
    return 0;
}

二、创建文件

mode模式,权限。

左边是宏,右边是表示对应的八进制

umask指令,查看文件权限。

三、写入文件

cpp 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <error.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

// 打开文件
int main(int argc, char** argv) {
    int fd;
    if (argc < 3) {
        printf("Usage: %s <file> <string1> <string2> ......\n", argv[0]);
        return -1;
    }
    fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) {
        printf("can not open file %s\n", argv[1]);
        printf("errno = %d\n", errno); // 打印错误信息
        printf("err: %s\n", strerror(errno));
        // 这里更加简单,效果等同于上面两个
        perror("open");
    }
    else {
        printf("fd: %d\n", fd);
    }

    lseek(fd, 10, SEEK_SET);

    for (int i = 2;i < argc;i++) {
        int len = write(fd, argv[i], strlen(argv[i]));
            if (len != strlen(argv[i])) {
                perror("write");
                break;
            }
        write(fd, "\r\n", 2);
    }

    close(fd);
    return 0;
}

四、读取

文件IO内部机制

应用层触发异常,传递给内核,内核去处理异常。glibc

相关推荐
半方白22 分钟前
通过 ks.cfg 文件实现 openEuler 系统自动部署
运维·自动化运维
moppol25 分钟前
容器化 vs 虚拟机:什么时候该用 Docker?什么时候必须用 VM?
运维·docker·容器
ZPC821031 分钟前
ubuntu 6.8.0 安装xenomai3.3
linux·运维·ubuntu
一梦浮华1 小时前
自学嵌入式 day30 IPC:进程间通信
linux·运维·服务器
CH_Qing1 小时前
【udev】关于/dev 设备节点的生成 &udev
linux·前端·网络
电脑能手1 小时前
遇到该问题:kex_exchange_identification: read: Connection reset`的解决办法
linux·ubuntu·ssh
snoopyfly~2 小时前
Ubuntu 24.04 安装配置 Redis 7.0 开机自启
linux·redis·ubuntu
精英的英2 小时前
在Ubuntu 24.04主机上创建Ubuntu 14.04编译环境的完整指南
linux·运维·ubuntu
求索小沈2 小时前
ubuntu22.04安装anaconda
linux·运维·服务器
JAVA拾贝2 小时前
Prometheus+Grafana运维监控并实现钉钉告警
运维·钉钉·grafana·prometheus·运维监控