Reputation: 25
I am trying to get this piece of code to read a line from a file but it's not working. I was wondering if one of you could help me. It was going to read the last 5 lines which I can configure later, but right now I am just trying to get it to read the last line.
#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;
}
Upvotes: 0
Views: 1990
Reputation: 145307
Here is a simple solution where you read all lines into a circular line buffer and print the last 5 lines when the end of file has been reached:
#include <stdio.h>
int main(void) {
char lines[6][256];
size_t i = 0;
FILE *myfile = fopen("X:\\test.txt", "r");
if (myfile != NULL) {
while (fgets(lines[i % 6], sizeof(lines[i % 6]), myfile) != NULL) {
i++;
}
fclose(myfile);
for (size_t j = i < 5 ? 0 : i - 5; j < i; j++) {
fputs(lines[j % 6], stdout);
}
}
return 0;
}
Upvotes: 1
Reputation: 11
Just make a for or while cycle that reads all the file(use fscanf) and when the reading gets to your desired line you save it to a var.
Upvotes: 1