linux 非缓冲io笔记

简介

在linux中,打开的的文件(可输入输出)标识就是一个int值,如下面的三个标准输入输出
STDIN_FILENO/STDOUT_FILENO/STDERR_FILENO这三个是标准输入输出,对应0,1,2

open(文件路径,读写标识,其它不定参数)
read(文件标识,缓冲区,要读的字节数):从文件中读取指定的字节数到缓冲区,返回值为实际读取的字节
write(文件标识,缓冲区,要写的字节数):将缓冲区中指定的字节数写入到文件中
close(文件标识):关闭文件
读写标识,常用的有O_RDONLY,O_WRONLY,O_RDWR,O_APPEND,O_TRUNC

lseek(文件标识,偏移量,偏移起始位置),其中偏移的起始位置有三个:
SEEK_SET:文件头
SEEK_CUR:当前位置
SEEK_END:文件尾

例1

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

struct people{
    const char name[10];
    int age;
};

int main(){
    int fd;
    if((fd=open("./test_file",O_RDWR|O_TRUNC|O_CREAT))<0){
        perror("open file error");
        return -1;
    }
    struct people a={"zhangsan",20},b={"lisi",40},
                  c={"wangwu",50},d={"zhaoliu",60};
    write(fd,&a,sizeof(a));
    write(fd,&b,sizeof(b));
    write(fd,&c,sizeof(c));
    write(fd,&d,sizeof(d));

    printf("input your choice:");
    int num;
    scanf("%d",&num);
    switch(num){
        case 1:
            lseek(fd,0,SEEK_SET);break;
        case 2:
            lseek(fd,sizeof(struct people),SEEK_SET);break;
        case 3:
            lseek(fd,sizeof(struct people)*2,SEEK_SET);break;
        default:
            lseek(fd,sizeof(struct people)*3,SEEK_SET);
    }

    struct people test;
    if(read(fd,&test,sizeof(struct people))<0){
        perror("read file error");
        return 1;        
    }
    printf("your choice is %s,%d
",test.name,test.age);
    close(fd);
    return 0;


例子2

dup函数用于将现在的文件标识复制一份给其它人, 以达到转接的作用
dup2函数与dup作用一样,但过程不一样,dup2会将第二个参数的文件描述符关闭, 然后再复制文件标识
下面的例子将STDOUT_FILENO转接到test.txt文件, 于是printf打印的字符串不会显示在终端窗口, 而是写入到文件中

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
 
void err_quit(const char *str){
    perror(str);
    exit(1);
}
 
int main(){
    int fd;
    if((fd=open("./test.txt",O_RDWR|O_CREAT|O_TRUNC))<0)
        err_quit("open error");
 
    char *str="this is a test
" ;
    if(dup2(fd,STDOUT_FILENO)<0)
        err_quit("dup2 error");
    printf("%s",str);
    return 0;
}
原文地址:https://www.cnblogs.com/cfans1993/p/5586726.html