gpt4 book ai didi

c - 如何从文件中读取最后一行?

转载 作者:行者123 更新时间:2023-11-30 14:29:00 25 4
gpt4 key购买 nike

我正在创建一个应用程序,它必须从文本文件中获取一些数据。问题是,我需要的数据位于文本文件的最后一行。有没有办法以某种方式读取最后一行?我只需要最后一行内容。有人可以帮助我吗?

谢谢

最佳答案

读取整个文件,保留两行,然后丢弃最后一行,例如:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int secondtolast(char *dst, size_t maxlen, FILE *h) {
char *line[2];
int i = 0;

line[0] = malloc(maxlen);
if (!line[0]) return 1;
*line[0] = 0;
line[1] = malloc(maxlen);
if (!line[1]) {
free(line[0]); /* return memory to the OS */
return 1;
}
*line[1] = 0;

while (fgets(line[i], maxlen, h)) i = !i;
strcpy(dst, line[i]);

free(line[0]);
free(line[1]);

return 0;
}

int main(void) {
char l2[8192];
if (secondtolast(l2, sizeof l2, stdin)) {
fprintf(stderr, "no memory");
}
printf("second to last line: %s", l2);
return 0;
}

关于c - 如何从文件中读取最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5303535/

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