chrizzla
chrizzla

Reputation: 53

Why does the program print only the last line of the file, even after reading the entire file?

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

Answers (2)

csavvy
csavvy

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

Krishna Kanth Yenumula
Krishna Kanth Yenumula

Reputation: 2567

  1. 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.

  1. 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

  1. 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

Related Questions