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

文件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("%s
", 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,buf,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,buf,ret)) < 0)    //将buf中的内容写到文件中。
    {
        puts("写入失败");
        return -1;
    }
    close(fd);    //最后关闭文件id。

    return 0;
}
原文地址:https://www.cnblogs.com/kmist/p/10632838.html