APUE 函数详解系列(一) lseek/stat/poll

本文介绍了lseek函数用于重新定位文件读写偏移量的方法,包括如何将读写位置移动到文件开头或末尾及获取当前文件位置;详细解释了stat函数用于获取文件状态信息的结构体内容;同时对比了poll函数与select函数的功能差异,并列举了poll函数的事件类型。

1. lseek - reposition read/write file offset

  • SYSNOPSIS
      #include<sys/types.h> and <unistd.h>
      off_t lseek(int fd, off_t offset,int whence);

  • DESCRIPTION
      The lseek() function repositions the offset of the open file associated descriptor fd to the argument offset according to the directive whence as follows:
      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 is set to the size of file plus offset bytes.

  • RETURE VALUE
      Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the begining of the file. On error, the value (off_t) -1 is returned and errno is set to indicate the error.

  • 特别使用方式:
      1) 将读写位置移到文件开头:lseek(int fd, 0, SEEK_SET);
      2) 将读写位置一道文件末尾:lseek(int fd, 0, SEEK_END);
      3) 取得目前文件位置:lseek(int fd, 0 , SEEK_CUR);


2. stat - display file or file system status

  • SYSNOPSIS
#include<sys/stat.h> . <unistd.h> . <sys/types.h>
int stat(const char *path, struct stat *buf)
  • DESCRIPTION
    This function return information about a file.
struct stat{
    dev_t    st_dev;
    ino_t    st_ino;
    mode_t   st_mode;    //文件类型和许可权限
    nlink_t  st_nlink;   //文件连接数
    uid_t    st_uid;     //用户所有者ID
    gid_t    st_gid;     //所属组ID
    time_t   st_mtime;   //文件最后修改时间
    time_t   st_atime;   //文件最后访问时间
    time_t   st_ctime;   //文件属性最后修改时间
}

3.Poll

类似select,接口不同

#include<poll.h>
int poll(struct pollfd fdarray[], nfds_t nfds, int timeout);

struct pollfd{
    int fd;
    short events;   //events of interest on fd 请求事件
    short revents;  //events that occurred on fd 返回事件
}
nfds指定fdarray数组中元素,events告诉内核我们关心的是每个描述符哪些事件,返回时,revents成员由内核设置,用于说明每个描述符发生了哪些事件。
                                poll中events和revents标志
标志名说明
以下四个测试可读性
POLLIN可以不阻塞读取普通数据和优先级数据(等效下两个
POLLRDNORM可以不阻塞读取普通数据
POLLRDBAND可以不阻塞读取优先级数据
POLLPRI可以不阻塞读取高优先级数据
以下三个测试可写性
POLLOUT可以不阻塞写普通数据
POLLWRNORM与POLLOUT相同
POLLWRBAND可以不阻塞写优先级数据
以下三个测试异常条件
POLLERR已出错
POLLHUP已挂断
POLLNVAL描述符没有引用一个打开文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值