Linux文件操作 -- lseek实践
来源:互联网 发布:写作神器软件下载 编辑:程序博客网 时间:2024/05/21 14:57
注:学习资料来自邢文鹏老师
lseek
每个打开的文件都记录着当前读写位置,打开文件时读写位置是0,表示文件开头,通常读写多少个字节就会将读写位置往后移多少个字节。
但是有一个例外,如果以O_APPEND
方式打开,每次写操作都会在文件末尾追加数据,然后将读写位置移到新的文件末尾。 lseek
和标准I/O库的fseek
函数类似,可以移动当前读写位置(或者叫偏移量)。
#include <sys/types.h>#include <unistd.h>off_t lseek(int fd, off_t offset, int whence);
参数offset
和whence
的含义和fseek
函数完全相同。只不过第一个参数换成了文件描述符。
和fseek
一样,偏移量允许超过文件末尾,这种情况下对该文件的下一次写操作将延长文件,中间空洞的部分读出来都是0。
若lseek
成功执行,则返回新的偏移量,因此可用以下方法确定一个打开文件的当前偏移量:
off_t currpos;currpos = lseek(fd, 0, SEEK_CUR);
这种方法也可用来确定文件或设备是否可以设置偏移量,常规文件都可以设置偏移量,而设备一般是不可以设置偏移量的。
如果设备不支持lseek
,则lseek
返回-1,并将errno
设置为ESPIPE
。
注意fseek和lseek在返回值上有细微的差别,fseek
成功时返回0失败时返回-1,要返回当前偏移量需调用ftell
,而lseek
成功时返回当前偏移量失败时返回-1。
lseek程序实例:
#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h> #include <fcntl.h>int main(int argc, char *argv[]){ if(argc<2){ printf("args error\n"); } int fd = open(argv[1], O_RDWR); if(fd<0){ perror("fd<0"); return 0; } lseek(fd, 1024, SEEK_SET); write(fd, "X", 1); close(fd); return 0; }
程序执行及运行结果:
yu@ubuntu:~/Linux/206/llll$ lslseek.cyu@ubuntu:~/Linux/206/llll$ touch xyu@ubuntu:~/Linux/206/llll$ ls -ltotal 4-rw-rw-r-- 1 yu yu 348 Feb 6 14:01 lseek.c-rw-rw-r-- 1 yu yu 0 Feb 6 14:02 xyu@ubuntu:~/Linux/206/llll$ gcc -o lseek lseek.c yu@ubuntu:~/Linux/206/llll$ ./lseek xyu@ubuntu:~/Linux/206/llll$ ls -ltotal 16-rwxrwxr-x 1 yu yu 7516 Feb 6 14:02 lseek-rw-rw-r-- 1 yu yu 348 Feb 6 14:01 lseek.c-rw-rw-r-- 1 yu yu 1025 Feb 6 14:03 xyu@ubuntu:~/Linux/206/llll$ od -tcx x 0000000 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 00000000 00000000 00000000 00000000*0002000 X 000000580002001
x文件大小已经由0变为1025, 最后面为X
字符
0 0
- Linux文件操作 -- lseek实践
- linux文件函数-lseek
- Linux基础编程-文件操作open,lseek,read,write,close
- Linux基础编程-文件操作open,lseek,read,write,close
- Linux基础编程-文件操作open,lseek,read,write,close
- linux文件操作open close read write lseek
- Linux 文件操作 open,lseek,read,write,close
- 【Linux】使用read、write、lseek函数实现文件读写操作
- 系统函数-文件操作-lseek()
- C语言文件操作lseek
- 文件操作中的lseek函数详解
- linux C: lseek 获取文件长度
- linux lseek
- 在linux中使用open函数对文件进行操作后如何读取文件中的内容 lseek fcntl ioctl
- 文件lseek操作产生空洞文件的方法
- Linux C编程学习笔记(3):read、write、lseek函数及文件读写和文件读写指针的移动操作
- 【文件】Linux文件函数——read、write、lseek
- 文件操作的系统调用之write ,close, lseek
- Linux 常见命令小技巧集锦
- hdu 1241 Oil Deposits
- HDOJ 3339 In Action (Dijstra + 01 背包)
- poj1273 Drainage Ditches(最大流入门)
- 淫欲的真相是什么呢?可能很多英雄豪杰都没有想到过
- Linux文件操作 -- lseek实践
- git:branch is published (but not merged) and is now commits behind
- hdoj--1258--Sum It Up(dfs)
- java学习心得——添加列表查询功能
- 【MinaFile】【十三】【2.0】关于粘包的处理
- 论__HashCode和内容Length做快速去重有多不靠谱
- POJ3641 快速幂
- 7216:Minecraft题解
- hdoj 2680 Choose the best route【最短路 dijkstra && SPFA】