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

相关推荐
liuyao_xianhui20 小时前
Linux_基本指令1
linux·运维·服务器
守望时空3321 小时前
Linux挂载NTFS分区指南
linux
shan~~21 小时前
linux达梦数据库操作
linux·数据库·chrome
liliangcsdn1 天前
LLM时代基于unstructured解析非结构化pdf
linux·服务器·数据分析
Codigger官方1 天前
Linux 基金会牵头成立 React 基金会:前端开源生态迎来里程碑式变革
linux·前端·react.js
武文斌771 天前
项目学习总结:LVGL图形参数动态变化、开发板的GDB调试、sqlite3移植、MQTT协议、心跳包
linux·开发语言·网络·arm开发·数据库·嵌入式硬件·学习
爱吃喵的鲤鱼1 天前
仿mudou——Connection模块(连接管理)
linux·运维·服务器·开发语言·网络·c++
让子弹飞021 天前
永久解决ubuntu网络连接问题
linux·运维·ubuntu
郝学胜-神的一滴1 天前
使用Linux的read和write系统函数操作文件
linux·服务器·开发语言·数据库·c++·程序人生·软件工程
pu_taoc1 天前
深入剖析:基于epoll与主从Reactor模型的高性能服务器设计与实现
服务器·c语言·c++·vscode