我有一个任务是用C向后写入文件中的第n行。各行的顺序相反(最后一行是1,然后是2,...,然后第一行是n)。我需要找到第k行并将其写回。行由字符0x0D和0x0A分隔。
通过每两个字符向后读取,我设法以一种笨拙,缓慢的方式进行操作。该代码的测试之一失败,因为它太慢了。这是更好的方法吗?任何代码都将非常受欢迎。 (我仅限于使用lseek,阅读...-我不能使用getline()或类似的东西。)
int get_line(int fd, int lineNr, int begin, int size, int end)
{
char newC = 0;
char oldC = 0;
int linieCurenta = 1; //currentLine
int oldPos = end;
int newPos = end;
int linieGasita = FALSE; //check if the line was found
char line[PATHSIZE];
lseek(fd, end, SEEK_SET);
for(int i = end; i > begin; i--)
{
lseek(fd, -1, SEEK_CUR);
oldC = newC;
if(read(fd, &newC, 1) != 1)
{
perror("Reading error");
break;
}
lseek(fd, -1, SEEK_CUR);
if((newC == 0x0D && oldC == 0x0A) || i == begin + 1)
{
oldPos = newPos;
newPos = i - 2;
if(linieCurenta == lineNr) //If currentLine = lineNr
{
linieGasita = TRUE; //found
break;
}
linieCurenta++;
}
}
if(linieGasita == 0)
{
printf("ERROR\ninvalid line\n");
return -3;
}
lseek(fd, oldPos + 1, SEEK_SET);
printf("SUCCESS\n");
int start = 0; int limit = 0;
int cnt = 0;
//A way of writing longer than 2048 characters lines.
while(limit < oldPos - newPos) {
if(limit + PATHSIZE < oldPos - newPos) {
start = limit;
limit += PATHSIZE;
} else {
start = limit;
limit = oldPos - newPos;
}
cnt = 0;
for(int i = start; i < limit; i++) //Linie prea mare
{
lseek(fd, -1, SEEK_CUR);
if(read(fd, &line[cnt++], 1) != 1)
{
perror("Reading error...");
return -5;
}
lseek(fd, -1, SEEK_CUR);
}
cnt = 0;
//I have to print the line here, like this.
for(int i = start; i < limit; i++)
{
printf("%c", line[cnt++]);
}
}
return 0;
}
PATHSIZE定义为2048
结果还可以,但是过程很慢。