当我们对于文件进行操作时,不可避免的要和光标移动打交道。不像在图形化界面中使用键盘方向键甚至鼠标字节点击的操作,在Linux文件操作中,需要使用 lseek这个api进行光标偏移。
头文件:<sys/types.h>、<unistd.h>
函数原型:off_t lseek(int fd, off_t offset, int whence);
描述:将文件读写指针相对whence移动offset个字节;
fd:文件句柄;
offset: 偏移值(向后,单位byte)
whence:位置宏
返回值:如果函数调用成功,返回函数调用前后光标的偏移值
whence的位置宏:
SEEK_SET:文件头
SEEK_CUR:当前光标位置
SEEK_END:文件尾
demo:
int main()
{
int fd;
char *buf = "this is a message from linux c.";
fd = open("./file1", O_RDWR);
if(fd == -1)
{
printf("fail to open\n");
fd = open("./file1", O_RDWR | O_CREAT, 0600);
if(fd > 0)
{
printf("open succeddfully\n");
}
}
printf("fd = %d\n", fd);
int n_write = write(fd, buf, strlen(buf));
if( n_write != -1 )
{
printf("write %d byte to file\n", n_write);
}
char *readbuf;
readbuf = (char *)malloc(sizeof(char) * n_write + 1);
/*这时,光标在fd的尾部,如果直接进行读取操作会什么都读不到*/
lseek(fd, -n_write, SEEK_END);
/*从文件尾部向前偏移n_write个字节*/
int n_read = read(fd, readbuf, n_write);
printf("n_read = %d\n", n_read);
printf("form file1: %s\n", readbuf);
close(fd);
return 0;
}
运行结果:
fd = 3
write 31 byte to file
n_read = 31
form file1: this is a message from linux c.
此时的
lseek(fd, -n_write, SEEK_END);//文件尾向前偏移n_write个字节
也可以写成下面两种方法:
lseek(fd, 0, SEEK_SET);//直接偏移到文件头
lseek(fd, -n_write, SEEK_CUR);//当前光标位置向前偏移n_write个字节
利用返回值计算文件的大小(上面demo一样的file1,头文件和上面的demo相同):
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <unistd.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 int main()
10 {
11 int fd;
12 int filesize;
13
14 fd = open("./file1", O_RDWR);
15
16 filesize = lseek(fd, 0, SEEK_END);
17
18 printf("the size of file1 : %d\n", filesize);
19
20 close(fd);
21
22 return 0;
23 }
运行结果:
the size of file1 : 31