File Reading: Word By Word
Question:16
Write a C program to take input for the name of the file to read. Further, read the file word by word and display them.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char n[30],fname[20];
int i=1;
printf("Enter filename to read ");
scanf("%s",fname);
fp = fopen(fname, "r");
//fp = fopen("test10.txt", "r");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
//exit(1); //header file: stdlib.h
}
while(1)
{
fscanf(fp, "%s", n); //read word by word
if(feof(fp))
{
printf("end of file");
break;
}
printf("%d : %s\n", i++,n );//2
}
fclose(fp);
getch();
return(0);
}
Question:17
Write a C program to read a file word by word. Further, count and display words starting with either ‘a’ or ‘A’.
[Using the above program we can count and display words starting with any character.]
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char n[30],fname[20];
int i=0;
printf("Enter filename to read ");
scanf("%s",fname);
fp = fopen(fname, "r");
//fp = fopen("test10.txt", "r");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
//exit(1); //header file: stdlib.h
}
while(1)
{
fscanf(fp, "%s", n); //read word by word
if(feof(fp))
{
printf("end of file");
break;
}
if(n[0]=='a' || n[0]=='A')
{
printf("%s\n",n);
i++;
}
}
fclose(fp);
printf("\ntotal words = %d\n",i);
getch();
return(0);
}
Question:18
Write a C program to read a file word by word. Further count and display words starting with vowels(a,e,,I,o,u,A,E,I,O,U).
[Using the above program we can count and display words starting with any character.]
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char n[30],fname[20];
int i=0;
printf("Enter filename to read ");
scanf("%s",fname);
fp = fopen(fname, "r");
//fp = fopen("test10.txt", "r");
if(fp==NULL)
{
printf("Unable to open the file\n");
getch();
return(0);
//exit(1); //header file: stdlib.h
}
while(1)
{
fscanf(fp, "%s", n); //read word by word
if(feof(fp))
{
printf("end of file");
break;
}
if(n[0]=='a' || n[0]=='A' || n[0]=='e' || n[0]=='E' || n[0]=='I' || n[0]=='i' || n[0]=='O' || n[0]=='o' || n[i]=='U' || n[i]=='u')
{
printf("%s\n",n);
i++;
}
}
fclose(fp);
printf("total words = %d\n",i);
getch();
return(0);
}




