gpt4 book ai didi

c - 如何查看是否已到达文件开头?

转载 作者:行者123 更新时间:2023-12-04 08:30:17 24 4
gpt4 key购买 nike

我有一个任务要重写Unix系统函数tail .我的算法按以下方式工作:
lseek到文件末尾,进入一个循环,将文件描述符向后移动一点,读取几个字节,如果找到任何新行,我会增加计数器。有一次,我得到了 10 行新行(我认为应该是 11 行,但事情还没有完成,现在这对我有用),我离开了循环。

如果文件的新行少于 10 行,由于我编写它的方式,我会进入无限循环。
有没有办法查看我是否已经到达文件的开头,然后我可以离开循环?
代码 :

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main (int argc, char *argv[])
{

int fd;
off_t offset = 10;
size_t size = 10;
unsigned char buff[10];
int new_line_counter = 0;
off_t total_offset = 0;//dont mind this
fd = open("a.txt", O_RDONLY);
if (fd == -1)
{
perror("open");
return 1;
}
lseek(fd,0,SEEK_END);
while (new_line_counter < 10)
{
lseek(fd,-offset,SEEK_CUR);
total_offset+=10;//dont mind this
for(int i = 0; i<10;i++)
{
if(buff[i]=='\n')
{
if(new_line_counter==10)break;
new_line_counter++;
//printf("%d",new_line_counter);

}
}
read(fd,buff,size);
lseek(fd,-offset,SEEK_CUR);
}
}

最佳答案

使用 lseek 的返回值.它将返回当前文件位置,或者在出错时返回 -1。
你先lseek(fd,0,SEEK_END)会给你文件大小。
使用它来跟踪当前文件位置(并确保调整“偏移量”,以便 lseek(fd,-offset,SEEK_CUR); 在文件开始之前永远不会搜索。
这是必要的,否则你可能会错过第一行。

关于c - 如何查看是否已到达文件开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65061305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com