Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

Thursday, January 19, 2017

Read A Text File Using C

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.
Note:
To read a file you have to create a file first by using any text editor(Notepad) or you can also use the C program to create a file.