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

相关推荐
冰橙子id1 小时前
linux-远程访问管理(sshd,scp,sftp)
linux·网络·ssh
光电的一只菜鸡2 小时前
ubuntu之坑(十五)——设备树
linux·数据库·ubuntu
saynaihe4 小时前
ubuntu 22.04 anaconda comfyui安装
linux·运维·服务器·ubuntu
企鹅与蟒蛇4 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
小蜜蜂爱编程4 小时前
ubuntu透网方案
运维·服务器·ubuntu
程序设计实验室4 小时前
小心误关了NAS服务器!修改Linux的电源键功能
linux·nas
AI视觉网奇5 小时前
git 访问 github
运维·开发语言·docker
头发那是一根不剩了5 小时前
nginx:SSL_CTX_use_PrivateKey failed
运维·服务器
七夜zippoe6 小时前
破解 VMware 迁移难题:跨平台迁移常见问题及自动化解决方案
运维·自动化·vmware
hweiyu007 小时前
docker简介
运维·docker·容器