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

相关推荐
LH_R1 天前
OneTerm开源堡垒机实战(四):访问授权与安全管控
运维·后端·安全
用户31187945592181 天前
Kylin Linux 10 安装 glib2-devel-2.62.5-7.ky10.x86_64.rpm 方法(附安装包)
linux
Raymond运维1 天前
MariaDB源码编译安装(二)
运维·数据库·mariadb
涛啊涛1 天前
Centos7非LVM根分区容量不足后扩容,对调硬盘挂载/
linux·磁盘管理
JuiceFS2 天前
从 MLPerf Storage v2.0 看 AI 训练中的存储性能与扩展能力
运维·后端
CYRUS_STUDIO2 天前
用 Frida 控制 Android 线程:kill 命令、挂起与恢复全解析
android·linux·逆向
熊猫李2 天前
rootfs-根文件系统详解
linux
chen9452 天前
mysql 3节点mgr集群部署
运维·后端
LH_R2 天前
OneTerm开源堡垒机实战(三):功能扩展与效率提升
运维·后端·安全
dessler2 天前
Hadoop HDFS-高可用集群部署
linux·运维·hdfs