Webserver(1.6)Linux系统IO函数

目录

open函数

man 2 open

打开已有文件

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

int main(){
    int fd = open("a.txt",O_RDONLY);

    if(fd==-1){
        perror("open");
    }

    //关闭
    close(fd);
    return 0;
}

创建新文件

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

int main(){
    //创建一个新文件
    int fd=open("create.txt",O_RDWR | O_CREAT,0777);
    if(fd==-1){
        perror("open");
    }

    //关闭
    close(fd);
    return 0;
}

read和write函数

把文件全部读取并全部写到另一个文件中,拷贝操作

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

int main(){
    //open打开english.txt文件
    int srcfd=open("english.txt",O_RDONLY);
    if(srcfd==-1){
        perror("open");
        return -1;
    }
    //创建一个新的文件(拷贝文件)
    int destfd = open("cpy.txt",O_WRONLY | O_CREAT,0664);
    if(destfd==-1){
        perror("open");
        return -1;
    }

    //频繁的读写操作
    char buf[1024]={0};
    int len=0;
    
    while((len=read(srcfd,buf,sizeof(buf)))>0){
        write(destfd,buf,len);
    }
    //关闭文件
    close(destfd);
    close(srcfd);

    return 0;
}

写的文件和读取的文件大小一样,在vscode中查看内容一样,拷贝成功

lseek函数

移动文件头

lseek(fd,0,SEEK_SET)

获取当前文件指针位置

lseek(fd,0,SEEK_CUR)

获取文件长度

lseek(fd,0,SEEK_END)

拓展文件长度

lseek(fd,100,SEEK_END)

下面介绍拓展文件长度的用法

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

int main(){
    int fd=open("hello.txt",O_RDWR);
    if(fd==-1){
        perror("open");
        return -1;
    }

    //拓展文件的长度
    int ret=lseek(fd,100,SEEK_END);
    if(ret==-1){
        perror("lseek");
        return -1;
    }

    write(fd,"",1);

    close(fd);

    return 0;
}

拓展文件长度的时候,需要写一次数据,可以加入一个空的字符串

stat和lstat函数

stat直接获取指向的文件的信息(哪怕前面有软链接,也会指向最终那个文件信息)

查看文件状态

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

int main(){
    struct stat statbuf;
    int ret=stat("a.txt",&statbuf);

    if(ret==-1){
        perror("stat");
        return -1;
    }
    printf("size:%ld\n",statbuf.st_size);


    return 0;
}

lstat用于获取指向该文件的软链接的信息

相关推荐
China_Yanhy15 小时前
金融级企业出口网关架构设计与实施指南Enterprise Egress Gateway Architecture & Implementation Guide
运维·金融·架构
Jacob程序员15 小时前
Linux scp命令:高效远程文件传输指南
linux·运维·服务器
cyzat32115 小时前
n8n 2.0 深度解析:从开发工具到企业级自动化平台的华丽
运维·自动化·n8n·企业级平台
奋斗者1号15 小时前
SSL/TLS 证书在客户端-服务器通信中的详解
服务器·网络协议·ssl
h7ml15 小时前
企业微信通讯录同步服务的增量更新算法与冲突解决策略
服务器·算法·企业微信
corpse201015 小时前
Transparent Huge Pages(透明大页)对redis的影响
linux·redis
Cx330❀15 小时前
Linux进程前言:从冯诺依曼体系到操作系统的技术演进
linux·运维·服务器
阿巴~阿巴~15 小时前
帧长、MAC与ARP:解密局域网通信的底层逻辑与工程权衡
linux·服务器·网络·网络协议·tcp/ip·架构·以太网帧
Maggie_ssss_supp15 小时前
Linux-计算机网络
服务器·网络·计算机网络
oMcLin15 小时前
如何在 Manjaro Linux 上实现高效的 Ceph 存储集群,提升大规模文件存储的冗余性与性能?
linux·运维·ceph