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

相关推荐
ts码农10 分钟前
model层实现:
java·服务器·前端
哈基米喜欢哈哈哈1 小时前
进程和线程
java·linux·windows·笔记
cccc来财1 小时前
TCP的流量控制和拥塞控制
服务器·网络·tcp/ip
扶风呀1 小时前
负载均衡详解
运维·后端·微服务·面试·负载均衡
chengpei1472 小时前
Ubuntu Server系统安装磁盘分区方案
linux·运维·ubuntu
轻松Ai享生活2 小时前
SysRq详解
linux
现实与幻想~3 小时前
Linux:企业级WEB应用服务器TOMCAT
linux·前端·tomcat
网硕互联的小客服3 小时前
服务器如何应对SYN Flood攻击?
运维·服务器·网络
万花丛中一抹绿3 小时前
服务器硬件电路设计之 I2C 问答(五):I2C 总线数据传输方向如何确定、信号线上的串联电阻有什么作用?
服务器·i2c·服务器硬件研发
ZERO的秃头之路4 小时前
WMware的安装以及Ubuntu22的安装
linux·服务器·ubuntu