📁📚Intermediate

Print Patterns Matching From a File

Pattern search in file

Search for patterns in a file and print matching lines.

Program Code

pattern_match_file.c
C
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5 FILE *file;
6 char line[256];
7 char pattern[50];
8 int lineNum = 0, matches = 0;
9
10 printf("Enter pattern to search: ");
11 scanf("%49s", pattern);
12
13 file = fopen("data.txt", "r");
14 if (file == NULL) {
15 printf("Cannot open file!\n");
16 return 1;
17 }
18
19 printf("\nMatching lines:\n");
20 printf("===============\n");
21
22 while (fgets(line, sizeof(line), file)) {
23 lineNum++;
24 if (strstr(line, pattern) != NULL) {
25 printf("Line %d: %s", lineNum, line);
26 matches++;
27 }
28 }
29
30 printf("\nTotal matches: %d\n", matches);
31
32 fclose(file);
33 return 0;
34}
Output

Enter pattern to search: error

 

Matching lines:

===============

Line 5: Error: File not found

Line 12: Warning: error in line 10

Line 23: error handler activated

 

Total matches: 3

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples