Reading File Character By Character
Question: 1
Write a C program to create a file, store text into it and further read the contents character by character and display the contents?
Note: File named “hello” is created
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("hello","w");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
}
printf("Enter text to store in the file,to end press ^z\n");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
printf("The contents of the file are \n");
fp=fopen("hello","r");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
}
while((ch=getc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
getch();
return(0);
}
2nd methods
Note: this program is same as above. The only difference is we are taking for the file name to create from the user.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("hello","w");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
}
printf("Enter text to store in the file,to end press ^z\n");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
printf("The contents of the file are \n");
fp=fopen("hello","r");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
}
while((ch=getc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
getch();
return(0);
}
Question: 2
Write a C program to take input for a filename to create and store text into it?
Note: In this program, we are only creating a file and storing data into it?
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch,fname[15];
clrscr();
printf("Enter name of the file to create ");
scanf("%s",fname);
fp=fopen(fname,"w");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
}
printf("Enter text to store in the file,to end press ^z\n");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
getch();
return(0);
}
Question: 3
Write a C program to take input for a filename to read. Further, read the contents of the file character by character and them?
Note: Contents of any text file can be displayed.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch,fname[15];
clrscr();
printf("Enter name of the file to read ");
scanf("%s",fname);
fp=fopen(fname,"r");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
}
while((ch=getc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
getch();
return(0);
}




