/* Program to perform I/O in a given file using Character I/O */
#include<stdio.h>
main()
{
//declaring pointer to file
FILE *fp;
char chr;
printf("------------Writing in file:-----------------\n");
/* Writing in File*/
//Opening file for writing
fp=fopen("thought.txt","w");
//Checking file exists or not
if(fp==NULL)
{
printf("Error in opening file:\n");
return 0;
}
else
//If the file exists then writing into it character by character
{
printf("Enter text to be written in file:\n");
while((chr=getchar())!= EOF)
fputc(chr,fp);
}
//Closing the file
fclose(fp);
/* Reading in File*/
//Opening file for reading
printf("\n\n------------Reading from file:-----------------\n");
fp=fopen("thought.txt","r");
if(fp==NULL)
{
printf("Error in opening file:\n");
return 0;
}
//If the file exists then reading through it character by character
else
{
printf("Text found in the file is:\n");
while((chr=fgetc(fp))!= EOF)
printf("%c",chr);
}
//closing the file
fclose(fp);
}
0 comments: