我試圖讓這段代碼從文件中讀取一行,但它不起作用。我想知道你們中的一個人是否可以幫助我。它將讀取我可以稍後配置的最後5行,但現在我只是想讓它讀取最後一行。從文件中讀取最後N行
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
FILE *myfile = fopen("X:\\test.txt", "r");
int x, number_of_lines = 0, count = 0, bytes = 512, end;
char str[256];
do {
x = fgetc(myfile);
if (x == '\n')
number_of_lines++;
} while (x != EOF); //EOF is 'end of file'
if (x != '\n' && number_of_lines != 0)
number_of_lines++;
printf("number of lines in test.txt = %d\n\n", number_of_lines);
for (end = count = 0; count < number_of_lines; ++count) {
if (0 == fgets(str, sizeof(str), myfile)) {
end = 1;
break;
}
}
if (!end)
printf("\nLine-%d: %s\n", number_of_lines, str);
fclose(myfile);
system("pause");
return 0;
}
剛剛看過用'與fgets線()'。當你得到EOF指示時,最後一行在緩衝區中。當你需要最後N行時,保持一個N行數組並旋轉列表直到你到達EOF。 –