#include<fcntl.h> main(){ int fd, nread; char buf[1024]; /*open file “data” for reading */ fd = open(“data”, O_RDONLY); /* read in the data */ nread = read(fd, buf, 1024); /* close the file */ close(fd); }
5.2. opne/creat function
1 2 3 4 5 6 7
#include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> intopen(constchar *pathname, int flags); intopen(constchar *pathname, int flags, mode_t mode); //可变参数,不是函数重载 intcreat(constchar *pathname, mode_t mode); //Return: a new file descriptor if success; -1 if failure
while ((n = read(STDIN_FILENO, buf, BUFSIZE)) > 0) if (write(STDOUT_FILENO, buf, n) != n) err_sys(“write error”); if (n<0) err_sys(“read error”);
5.5. seek
设置read/write的偏移量
1 2 3 4
#include<sys/types.h> #include<unistd.h> off_tlseek(int fildes, off_t offset, int whence); //Return: the resulting offset location if success; -1 if failure)
whence: seek从哪里开始加偏移量
SEEK_SET: the offset is set to “offset” bytes
SEEK_CUR: the offset is set to its current location plus “offset” bytes
SEEK_END: the offset if set to the size of the file plus “offset“ bytes
5.6. dup/dup2 Function
复制文件描述符
1 2 3 4
#include<unistd.h> intdup(int oldfd); intdup2(int oldfd, int newfd); //Return: the new file descriptor if success; -1 if failure)
e.g.重定向的实现
1 2
int fd = open(...) dup2(fd,1)
5.7. fcntl Function
控制文件描述符
1 2 3 4 5 6
#include<unistd.h> #include<fcntl.h> intfcntl(int fd, int cmd); intfcntl(int fd, int cmd, long arg); intfcntl(int fd, int cmd, struct flock *lock); //返回值: 若成功则返回值依赖于cmd,若出错为-1
cmd取值
F_DUPFD: Duplicate a file descriptor
F_GETFD/F_SETFD: Get/set the file descriptor’s close-on-exec flag
#include<sys/types.h> #include<sys/stat.h> #include<unistd.h> intstat(constchar *filename, struct stat *buf); intfstat(int filedes, struct stat *buf); intlstat(constchar *file_name, struct stat *buf); //Return: 0 if success; -1 if failure
structstat { mode_t st_mode; /*file type & mode*/ ino_t st_ino; /*inode number (serial number)*/ dev_t st_rdev; /*device number (file system)*/ nlink_t st_nlink; /*link count*/ uid_t st_uid; /*user ID of owner*/ gid_t st_gid; /*group ID of owner*/ off_t st_size; /*size of file, in bytes*/ time_t st_atime; /*time of last access*/ time_t st_mtime; /*time of last modification*/ time_t st_ctime; /*time of last file status change*/ long st_blksize; /*Optimal block size for I/O*/ long st_blocks; /*number 512-byte blocks allocated*/ };
structflock{ ... short l_type; /* Type of lock: F_RDLCK, F_WRLCK, F_UNLCK */ short l_whence; /* How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_END */ off_t l_start; /* Starting offset for lock */ off_t l_len; /* Number of bytes to lock */ pid_t l_pid; /* PID of process blocking our lock (F_GETLK only) */ ... }