栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

学习Linux下的文件I/O

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

学习Linux下的文件I/O

区别:标准c库的io函数是可以跨平台的原因是调用不同平台的系统api

标准c库文件i/o是有缓冲区的对磁盘读写可以提高效率

网络环境要求速度高不能用缓冲区要用linux读写文件

下图显示了c库io和linux系统io的关系

虚拟地址空间:并不存在是一种设想 解释编程中的模型

文件描述符

 文件描述表是一个数组大小默认是1024

5.linux系统io函数

open:

1.打开一个已经存在的文件

#include
#include
#include
#include
#include
int main()
{
    int fd=open("a.txt",O_RDONLY);
    if(fd==-1)//由于不存在a.txt所以会报错
    {
        perror("open");//输出错误信息
    }
    //关闭文件描述符
    close(fd);
    return 0;
}

 2.创建一个文件

 
#include 
#include 
#include 
#include
#include
int main()
{
    int fd=open("create.txt",O_RDWR|O_CREAT,0777);
    if(fd==-1)
    {
        perror("open");
    }
    //关闭
    close(fd);
}

read:从文件读取数据到内存当中

#include 
#include
#include
#include
#include

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;
}

lseek:操作文件指针

#include 
#include
#include
#include 
#include
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:查看文件信息

#include
#include
#include
#include
int main(){
    struct stat statbuf;
    int ret=stat("a.txt",&statbuf);
    if(ret==-1)
    {
        perror("stat");
        return -1;
    }
    printf("size:%ldn",statbuf.st_size);
    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/831501.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号