You are reading the lines, the problem is that you are overwriting them over and over again in your buffer, so only the last one stays.
A good way to do this is to use fscanf
in the while condition, this way you'll have a sound stop condition and you can verify the read results, which should allways be done.
You can do something like this:
Live demo
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINES 100 //nr of lines
int main() {
//array of 100 pointers to char, so 100 lines max, adapt it to you needs
//should be the equal or larger than the max number of lines to be read
char *buffer[LINES];
FILE *fp;
int i = 0;
//checking the opened file is also a good practice
if (!(fp = fopen("test.pas", "r"))) {
perror("Not able to open file!");
return 1;
}
do {
if (!(buffer[i] = malloc(100))) { //allocate memory for each line
perror("Memory allocation failed"); //checking memory allocation
return 1;
}
}while (fscanf(fp, "%99s", buffer[i]) == 1 && strcat(buffer[i], "$") && i++ < LINES - 1);
buffer[i] = NULL; // sentinel, marks the end of the array of strings
i = 0; //reset i
while (buffer[i]) {
puts(buffer[i]); //print each line
free(buffer[i]); //free memory
i++;
}
fclose(fp);
}
Note that fscanf()
reads until the next blank space, so for strings with more than 1 word you should use something like fgets
or you if you use UNIX, getline()
.
feof
is not the best option as you can see in
Why is “while ( !feof (file) )” always wrong?
The standard actually exemplifies the correct usage of feof
ISO/IEC9899:2017 N2176 § 7.21.6.2 - 19