引言
文件光标类似于鼠标,在写完文件之后,光标会来到文件的结尾,需要手动去调整光标的位置,在先前的博客中,创建完文件,写入数据后,需要先关闭文件重新打开文件,这样才能将光标刷新到文件的开头以读取文件大小。在本章节中可以直接使用移动光标的函数,来减少代码冗余。
光标的移动函数
off_t lseek(int fd, off_t offset, int whence);在该函数中,返回值是光标偏移的数量,可以使用这个机制来获取文件的大小,第一个参数是文件描述符,第二个参数是偏移量,第三个参数是基准位置,基准位置有以下几个参数:
- SEEK_SET:值为 0,从文件开头开始偏移
- SEEK_CUR:值为 1,从当前位置开始偏移
- SEEK_END:值为 2,从文件末尾开始偏移
使用该函数代替关闭和打开文件函数,如下面所示:
#include <fcntl.h> //调用光标移动的函数
#include <stdio.h>
#include <unistd.h> //调用光标移动的函数
#include <string.h>
#include <stdlib.h> //调用malloc函数
int main()
{
int fd, n_write, n_read;
char *buf = "Hello Linux!";
char *readBuf;
readBuf = (char *)malloc(sizeof(char) * n_write); //为该指针申请n_write个char的大小内存
fd = open("new3",O_RDWR);
if(fd > 0)
{
printf("file open success\n");
}
else
{
open("new3",O_RDWR|O_CREAT,0600);
printf("file has been created!\n");
}
n_write = write(fd, buf, strlen(buf));
lseek(fd, 0, SEEK_SET); //让光标指向文件开始
n_read = read(fd, readBuf, n_write);
printf("This file have %d byte\n", n_read);
return 0;
}
利用它的返回值可以得到文件的大小:
int main()
{
int fd, filesize;
char *buf = "Hello Linux!,stay hurrgy stay foolish";
fd = open("new1", O_RDWR|O_CREAT, 0600);
write(fd, buf, strlen(buf));
filesize = lseek(fd, 0, SEEK_END);
printf("This file have %d byte\n", filesize);
return 0;
}
4882

被折叠的 条评论
为什么被折叠?



