文件IO

1. OPEN

umask=2, 666&(~2)=664

 

 

 

 

 

 2. CLOSE

 

 

 

 

 

 

3. Read

 

 

 

4. write

模拟 cat:

 

 

 

需求:

写hello到一个文件,然后读取,输出到终端。

 

 若这样写,read不到,因为写hello后将到文件末尾。

需要lseek

 

 

 

 

lseek 计算文件大小

少了一句: close(fd)!!!!

 

lseek 拓展文件

 

 

阻塞与非阻塞

 

 通过 O_NONBLOCK实现非阻塞

 非阻塞的情况下read返回-1,但是需要判断errno的值来确定是否是非阻塞。

 

另一种方法设置非阻塞, 通过fcntl()函数

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
    int fd=open("/dev/tty",O_RDWR);
    //fcntl() function, set unblock
    int flags=fcntl(fd,F_GETFL);//get flags  
    flags|=O_NONBLOCK;// change flags  
    fcntl(fd,F_SETFL,flags);//set flags

    char buf[256];
    int ret=0;
    while(1){
        //not blocked
        ret=read(fd,buf,sizeof(buf));
        if(ret<0){
            perror("read err:");
            printf("ret is %d\n", ret);
        }
        if(ret){
            printf("buf is %s\n", buf);
        }
        printf("haha\n");
        sleep(2);
    }
    close(fd);
    return 0;
}

 

posted @ 2020-02-21 16:51  feibilun  阅读(130)  评论(0编辑  收藏  举报