The following code reads a text file one character at the time and print it to stdout:
#include <stdio.h>
int main()
{
char file_to_open[] = "text_file.txt", ch;
FILE *file_ptr;
if((file_ptr = fopen(file_to_open, "r")) != NULL)
{
while((ch = fgetc(file_ptr)) != EOF)
{
putchar(ch);
}
}
else
{
printf("Could not open %s\n", file_to_open);
return 1;
}
return(0);
}
But instead of printing to stdout [putchar(ch)] I want to search the file for specific strings provided in another textfile ie. strings.txt and output the line with the match to out.txt
text_file.txt
:
1993 - 1999 Pentium 1997 - 1999 Pentium II 1999 - 2003 Pentium III 1998 - 2009 Xeon 2006 - 2009 Intel Core 2
strings.txt
:
Nehalem AMD Athlon Pentium
In this case the three first lines of text_file.txt
would match. I have done some research on file operations in C, and it seems that I can read one character at the time with fgetc
[like I do in my code], one line with fgets
and one block with fread
, but no word as I guess would be perfect in my situation?