加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux文件IO操作篇 (一) 非缓冲文件

发布时间:2020-12-14 02:07:50 所属栏目:Linux 来源:网络整理
导读:文件IO操作分为 2 种 非缓冲文件IO 和 缓冲文件IO 它们的接口区别是 非缓冲 open() close() read() write()缓冲 fopen() fclose() fread() fwrite() ? 1. 非缓冲文件操作 // 规模较小 实时性高 的文件 // 例如串口等高速实时通信 // 0 标准输入,通过终端输

文件IO操作分为 2 种 非缓冲文件IO 和 缓冲文件IO

它们的接口区别是

非缓冲   open() close() read() write()
缓冲    fopen() fclose() fread() fwrite()

?

1. 非缓冲文件操作

//规模较小 实时性高 的文件 // 例如串口等高速实时通信 // 0 标准输入,通过终端输入 // 1 标准输出,通过终端输出 // 2 标准错误,系统中存放错误的堆栈
//非缓冲文件操作函数只有2个
#include <sys/types.h> #include <sys/uio.h> #include <unistd.h> ssize_t read(int fildes,void *buf,size_t nbyte); ssize_t write(int fildes,const void *buf,size_t nbyte);

?

1.1 read()

//read()用于从文件中将信息读取到指定的内存区域,
//read(文件表示符,内存块指针,内存块大小)文件标识符由open获得。
#include <stdio.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>


#define LENGTH 1024

int main(int argc,char const *argv[])
{
    char buf[LENGTH] = {0};
    int fd;
    int len;
    
    fd = open("./read.c",O_RDONLY);    
    if(fd < 0){
        puts("file open fail .");
        return -1;
    }
    puts("open success .");

    len = read(fd,buf,LENGTH);
    if(len != -1){
        puts("read ok");
        if(len == 0 ){
            puts("read no.");
        }else{
            printf("%sn",buf);}
    }
    close(fd);

    return 0;
}

?

1.2 write()

//write()用于将缓存内容写入到文件中。
//ssize_t write(int fildes,const void *buf,size_t nbyte); fildes由open获得

例子:从键盘输入一个字符串,再将该字符串保存到文件中。

#include <stdio.h>
#include <string.h>
#include <unistd.h>


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define LENGTH 10240

int main(int argc,char const *argv[])
{
    int fd;
    int ret;
    char buf[LENGTH] = {0};
    puts("请输入要保存的信息:");

    if((ret = read(0,LENGTH)) < 0)    //从非缓冲标准输入0(键盘)获取数据,read到buf中,
    {
        perror("读取失败");
        return -1;
    }


    fd = open("./copy1",O_WRONLY|O_CREAT,0775); //以创造的方式打开copy1文件
    if(fd < 0)
    {
        puts("file open faile");
        return -1;
    }

    if((ret = write(fd,ret)) < 0)    //将buf中的内容写到文件中。
    {
        puts("写入失败");
        return -1;
    }
    close(fd);    //最后关闭文件id。

    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读