Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS101 / KCS201 Programming for Problem Solving - Using C Language
Lab Exercises
32. Write a program to check whether a given word exists in a file or not. If yes then find the number of times it occurs.
/*
File: Prgrm32.c
Author: Aditya Saini
Date: Sept 30, 2019
Description: Program to find the number of occurrences of the given word in a file.
*/
#include <stdio.h>
#include <string.h>
int main (void)
{
FILE *f_ptr;
char path [256];
char word [20];
char string [20];
int count;
//Input file path.
printf ("Input path: ");
scanf ("%s", path);
//Try to open file
f_ptr = fopen (path, "r");
if (f_ptr == NULL)
{
printf ("Error! Unable to open the file.");
return -1;
}
char path [256];
char word [20];
char string [20];
int count;
//Input file path.
printf ("Input path: ");
scanf ("%s", path);
//Try to open file
f_ptr = fopen (path, "r");
if (f_ptr == NULL)
{
printf ("Error! Unable to open the file.");
return -1;
}
//Input word
printf ("Input word to find: ");
scanf ("%s", word );
//Finding the number of occurrences of the given word
while (! feof (f_ptr))
{
fscanf (f_ptr, "%s", string);
if (strcmp (string, word ) == 0)
{
count++;
}
}
//Output the result.
printf ("Word \"%s\" is occurs %d times in the file.", word , count);
fclose (f_ptr);
};
Output
Input path: Prgrm32.c
Input word to find: word
Word "word" occurs 8 times in the file.
Input word to find: word
Word "word" occurs 8 times in the file.
No comments:
Post a Comment
Please do not post spam links.