"Edwin Parker" <ep*****@mobilemate.com> wrote:
I'm fairly new to C, but have most of the basics covered. I have a file
that my program writes to, but I need a way to search for information
within that file and then edit that information or print it to the
screen. I would like to be able to input a string (for example) and have
it scan that file for the exact string. I'm just not too sure how to
approach this. Any help would be great. Thanks in advance!
If the file is a text file in lines of a limited length, and the search
term must be within one line, you could use fgets to read each line of the
file into a buffer and use strstr function to look for the search term:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char linebuf[200], *newl, *found;
FILE *fp;
if(argc != 3)
{
fprintf(stderr, "Usage requires two arguments: search term then filename\n");
exit(EXIT_FAILURE);
}
fp = fopen(argv[2], "r");
if(fp == NULL)
{
fprintf(stderr, "Error opening file %s for read as text\n", argv[2]);
exit(EXIT_FAILURE);
}
while(fgets(linebuf, sizeof linebuf, fp))
{
newl = strchr(linebuf, '\n');
if(!newl) fprintf(stderr, "Warning: long line split\n");
found = strstr(linebuf, argv[1]);
if(found) fputs(linebuf, stdout);
}
return 0;
}
--
Simon.