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用于获取指向该文件的软链接的信息

相关推荐
liebe1*114 分钟前
第七章 防火墙地址转换
运维·服务器·网络
好好学操作系统20 分钟前
autodl 保存 数据 跨区
linux·运维·服务器
dbitc22 分钟前
WIN11把WSL2移动安装目录
linux·运维·ubuntu·wsl
KingRumn22 分钟前
Linux同步机制之信号量
linux·服务器·网络
嵌入式学习菌22 分钟前
SPIFFS文件系统
服务器·物联网
旺仔Sec23 分钟前
2026年度河北省职业院校技能竞赛“Web技术”(高职组)赛项竞赛任务
运维·服务器·前端
BullSmall43 分钟前
linux 根据端口查看进程
linux·运维·服务器
herinspace1 小时前
管家婆软件年结存后快马商城操作注意事项
服务器·数据库·windows
_F_y1 小时前
Linux:进程间通信
linux
嘻哈baby1 小时前
Ansible自动化运维入门:从手工到批量部署
运维·自动化·ansible