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

相关推荐
Xの哲學5 小时前
Linux grep命令:文本搜索的艺术与科学
linux·服务器·算法·架构·边缘计算
夜月yeyue5 小时前
Linux 调度类(sched_class)
linux·运维·c语言·单片机·性能优化
林义满5 小时前
运维转型让产线 “少掉链”:上海义满汽车零部件借智能运维降本增效,年减损失超 200 万
运维·汽车
VekiSon6 小时前
Linux系统编程——IPC进程间通信:信号通信与共享内存
linux·运维·服务器
南山nash6 小时前
CentOs7 安装 Docker 详细步骤
linux·运维·docker·容器
徐先生 @_@|||6 小时前
Conda最基础使用命令
linux·windows·conda
ZHHHHHJ666 小时前
LL层-PAST
运维·服务器·网络
wdfk_prog7 小时前
[Linux]学习笔记系列 -- [fs][drop_caches]
linux·笔记·学习
咩咩大主教7 小时前
VSCode远程连接Linux部署的Docker
linux·vscode·docker
名誉寒冰7 小时前
GDB 调试与 Core Dump(段错误)排查指南(Linux/C/C++)
linux·c语言·c++