UNIX 文件I/O

2020-06-02  本文已影响0人  yuq329

UNIX 文件I/O

引言

文件描述符

函数open和openat

函数create

    open(path,O_RDWR|O_CREAT|O_TRUNC,mode);

函数close

函数lseek

    #include<apue.h>
    #include<error.h>
    #include<fcntl.h>
    
    char buf1[] = "abcdefghij";
    char buf2[] = "ABCDEFGHIJ";
    
    int main() {
        int fd;
    
        if ((fd = creat("file.hole", FILE_MODE)) < 0)
            err_sys("create error");
    
        if (write(fd, buf1, 10) != 10)
            err_sys("buf1 write error");
    
        if (lseek(fd, 16384, SEEK_SET) == -1)
            err_sys("lseek error");
    
        if (write(fd, buf2, 10) != 10)
            err_sys("buf2 write error");
    
        exit(0);
    }
```shell
(base) yuqdeiMac:3_fileio yuq$ ls -l file.hole
-rw-r--r--  1 yuq  staff  16394 Jun  1 21:30 file.hole
(base) yuqdeiMac:3_fileio yuq$ od -c file.hole
0000000    a   b   c   d   e   f   g   h   i   j  \0  \0  \0  \0  \0  \0
0000020   \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
*
0040000    A   B   C   D   E   F   G   H   I   J                        
0040012
```

函数read

#include<unistd.h>
ssize_t read(int fd, void *buf, size_t nbytes);

函数write

I/O的效率

#include<apue.h>
#include<error.h>

#define BUFFSIZE 4096

int main(){
    int n;
    char buf[BUFFSIZE];

    while((n=read(STDIN_FILENO,buf,BUFFSIZE))>0)
        if(write(STDOUT_FILENO,buf,n)!=n)
            err_sys("write error");

    if(n<0)
        err_sys("read error");
    exit(0);
}

文件共享

原子操作

函数dup和dup2

函数sync、fsync和fdatasync

   #include<unistd.h>
   int fsync(int fd);
   int fdatasync(int fd);
   
   void sync(void);

函数fcntl

函数ioctl

#include<unistd.h>
#include<sys/ioctl.h>
int ioctl(int fd, int request, ...);

/dev/fd

习题

Reference

上一篇 下一篇

猜你喜欢

热点阅读