write a C program to read a .c file and to give the total number of "if statements" in that file as an output
write a C
thanks a lot in advance:)
Program code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
/* Function declarations */
int countOccurrences(FILE *fptr, const char *word);
int main()
{
FILE *fptr;
char path[100];
char *word;
word = "if";
int wCount;
FILE *fp;
fp = fopen("a.c","r");
/* Exit if file not opened successfully */
if (fp == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write previleges.\n");
exit(EXIT_FAILURE);
}
// Call function to count all occurrence of word
wCount = countOccurrences(fp, word);
printf("'%s' is found %d times in file.", word, wCount);
// Close file
fclose(fp);
return 0;
}
/**
* Returns total occurrences of a word in given file.
*/
int countOccurrences(FILE *fp, const char *word)
{
char str[BUFFER_SIZE];
char *pos;
int index, count;
count = 0;
// Read line from file till end of file.
while ((fgets(str, BUFFER_SIZE, fp)) != NULL)
{
index = 0;
// Find next occurrence of word in str
while ((pos = strstr(str + index, word)) != NULL)
{
// Index of word in str is
// Memory address of pos - memory
// address of str.
index = (pos - str) + 1;
count++;
}
}
return count;
}
Program code #1:
Program code #2:
Step by step
Solved in 5 steps with 4 images