Read a text file using C
Open a text file using C program and read the content of the file.
Code
/*Write a program to read a file*/ #include <stdio.h> #include <stdlib.h> int main() { FILE *fp; //Taking a file pointer variable char fname[30],ch; //Taking a existing file name from the user to read printf("\nEnter a file name to read: "); gets(fname); //Open the file in read mode fp=fopen(fname,"r"); //Check the file is corrupted or not if(fp==NULL) { printf("\nFile cannot be access."); exit(0); } if(ferror(fp)!=0) { printf("\nFile is either corrupted or damaged"); exit(1); } //Print the content of the file while((ch=getc(fp))!=EOF) { printf("%c",ch); } //Close the file fclose(fp); return 0; }
Output>
Enter a file name to read: temp.txt This is a temporary file.