您的位置:首页 > 运维架构 > Linux

Linux文件操作 -- lseek实践

2016-02-06 14:16 731 查看
注:学习资料来自邢文鹏老师


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$ ls
lseek.c

yu@ubuntu:~/Linux/206/llll$ touch x

yu@ubuntu:~/Linux/206/llll$ ls -l
total 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 x

yu@ubuntu:~/Linux/206/llll$ gcc -o lseek lseek.c

yu@ubuntu:~/Linux/206/llll$ ./lseek x
yu@ubuntu:~/Linux/206/llll$ ls -l
total 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 x

yu@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
00000058
0002001


x文件大小已经由0变为1025, 最后面为
X
字符
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: