Reputation: 53
I want to write a program in C which just reads a file, stores it into an array and then prints the array. Everything works fine but when the text file has more than one line, I always just get the last line printed out.
This is my Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
FILE * stream;
char dateiname[255];
stream = fopen("heute.txt", "r");
if(stream == NULL){
printf("Error");
}else {
while(!feof(stream)){
fgets(dateiname, 255, stream);
}
fclose(stream);
}
printf("%s\n", dateiname);
}
Thanks for help!
Upvotes: 0
Views: 772
Reputation: 821
If you want to just read and print the contents of the file you no need to worry about the size of the file and how many number of lines you have in file.
you can just run fgets()
in the while
and print each line until we reach NULL
But if you want to store them, we need to calculate the size of the file.
So we need to use functions like stat
or fstat
to get the size of the file and allocate memory dynamically then just read
that many bytes.
Upvotes: 0
Reputation: 2567
Everything works fine but when the text file has more than one line, I always just get the last line printed out
Reason: For every iteration, the data gets replaced with the next line data, and at the end dateiname
will read only the last line.
while(!feof(stream))
Usage of feof()
is not recommended. Please see this link for more information :https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284351&answer=1046476070
Please see the following code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *stream;
char dateiname[1024];
int i = 0;
stream = fopen("heute.txt", "r");
if (stream == NULL)
{
printf("Error");
}
else
{
while (fgets(dateiname, sizeof(dateiname), stream) != NULL)
{
printf("Line %4d: %s", i, dateiname);
i++;
}
}
return 0;
}
Upvotes: 1