ra fik
ra fik

Reputation: 122

how to print the content of a text file in c

Iam trying to print the content of a text file called text.txt in the terminal in c I have the following code but it doesn't work:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
 char str[255];
 FILE *fp;
 fp = fopen("text.txt","r");
 while (fgets(str,255,fp)!=NULL){
    printf("%s",str);
    fclose(fp);
 };
}

I couldn't find a solution please help

Upvotes: 0

Views: 2680

Answers (1)

Moaz Fathy
Moaz Fathy

Reputation: 91

First of all, you are closing the file inside the loop. fclose should lie at the end of your program. Secondly, fopen() might fail (you don't have permission to read the file for example). So, don't forget to handle that too.


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

int main(){
    const int sz = 255;

    char str[sz];
    FILE *fp;
    fp = fopen("input.txt","r");
    if(fp == NULL){
        // opening the file failed ... handle it
    }
    while (fgets(str,sz,fp)!=NULL){
        printf("%s",str);
    };

    fclose(fp);
}

Here is another similar way

  if (fp!=NULL)
  {
    // file open succeded. do sth with it.
    fclose (fp);
  }

Hope this helps and keep coding!

Upvotes: 2

Related Questions