【C语言】【unix c】lseek(2)重新定位文件的读写位置的使用

来源:互联网 发布:广东毕业生就业数据 编辑:程序博客网 时间:2024/06/08 13:00
一、lseek(2)重新定位文件的读写位置的使用    #include <sys/types.h>    #include <unistd.h>    off_t lseek(int fd, off_t offset, int whence);        功能:重新定位文件读写位置距离文件起始的偏移        参数:            fd:指定了具体的文件            offset:偏移量            whence:                SEEK_SET:offset就是文件的偏移位置(以头为基准)                SEEK_CUR:当前位置加上offset(以当前位置为基准)                SEEK_END:文件的大小加上offset 文件的尾部(以尾部为基准)        返回值:            -1 错误 errno被设置            正确 返回的是距离文件开始的位置    ***************************************************************    举例:lseek.c        #include <stdio.h>        #include <p_file.h>    程序:        int main(int argc, char *argv[]) {            int fd;            char buf[24]; //读取到的需要先存在一个地方            fd = open(argv[1], O_RDONLY); //不用新建文件,所以不用写第三个参数            if(fd == -1) {            perror("open");            return -1;            }            lseek(fd, 3,SEEK_SET); //以头为基准,向后偏移3个字节            int r = read(fd, buf, 2);            write(1, buf, r);//            printf("\n");            close(fd);            return 0;        }    命令: tarena@ubuntu:~/day/day28$ a.out hello     结果: lo    补充:        tarena@ubuntu:~/day/day28$ od -tx1 -tc hello        (文件起始位置)0000000  68  65  6c  6c  6f  0a     //ASIIC码                      h   e   l   l   o  \n     //字符        (文件结束位置)0000006
阅读全文
0 0
原创粉丝点击