Reading Strings and individual Characters from a text file using File Handling in C.
Language : C
[sourcecode language='c']
//To read strings and individual characters from a file
#include
#include
void makefile();
void readch();
void readstr();
void main()
{ int n;
char ch;
do{
printf(“Read make file(1) string(2) or ch(3) ? :”);
scanf(“%d”, &n);
switch (n)
{ case 1:
makefile();
break;
case 2:
readch();
break;
case 3:
readstr();
break;
}
printf(“\n\nY/N”);
fflush(stdin);
scanf(“%c”, &ch);
}while(ch==’y’ || ch==’Y');
}
void makefile()
{
FILE *fp;
char str[80];
fp=fopen(“File.txt”, “w” );
printf(“Enter some text : “);
fflush(stdin);
gets(str);
fputs(str,fp);
fclose(fp);
}
void readstr()
{ FILE *fp;
char str[80];
fp=fopen(“File.txt”, “r”);
while(fgets(str,79,fp)!=NULL)
{
printf(“%s”, str);
}
fclose(fp);
}
void readch()
{
FILE *fp;
char ch;
fp=fopen(“File.txt”, “r”);
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
printf(“%c”, ch);
}
fclose(fp);
}
[/sourcecode]






