Search code examples
cfilefgetsputs

Using fgets and puts to read and print a file not working


I wrote this piece if code below to read a text file that says: It was the best of times, it was the worst of times, it was the age of wisdom.

When I run my code nothing seems to happen. Is there anything you can spot in my code that may cause this issue? (Solution builds with no error or warnings too). Thanks :)

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
FILE * fPointer;
fPointer = fopen("exercise1.txt","r");
char singleline[150];

while (!feof(fPointer))
{
    fgets(singleline, 150, fPointer);
    puts(singleline);
}

fclose(fPointer);
return 0;

}

Solution

  • If I modify your program to take into account the remarks of Weather Vane, and I replace your puts by a fputs to not double the \n (fgets do not the remove the \n and puts add a \n) :

    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
      FILE * fPointer = fopen("exercise1.txt","r");
    
      if (fPointer == NULL)
        puts("cannot open exercise1.txt");
      else {
        char singleline[150];
    
        while (fgets(singleline, sizeof(singleline), fPointer))
          fputs(singleline, stdout);
    
        fclose(fPointer);
      }
    
      return 0;
    }
    

    Compilation and execution :

    /tmp % gcc -pedantic -Wextra c.c
    /tmp % cp c.c exercise1.txt
    /tmp % ./a.out
    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
      FILE * fPointer = fopen("exercise1.txt","r");
    
      if (fPointer == NULL)
        puts("cannot open exercise1.txt");
      else {
        char singleline[150];
    
        while (fgets(singleline, sizeof(singleline), fPointer))
          fputs(singleline, stdout);
    
        fclose(fPointer);
      }
    
      return 0;
    }
    /tmp % \rm exercise1.txt 
    /tmp % ./a.out
    cannot open exercise1.txt