By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,194 Members | 859 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,194 IT Pros & Developers. It's quick & easy.

need help with search code

P: n/a
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!
Nov 13 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"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.
Nov 13 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.