need help with search code

E

Edwin Parker

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!
 
S

Simon Biber

Edwin Parker said:
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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,781
Messages
2,569,619
Members
45,314
Latest member
HugoKeogh

Latest Threads

Top