Sorry for taking so long to post this!
Groovy hepcat (e-mail address removed) was jivin' in comp.lang.c on Thu,
14 Feb 2008 9:56 pm. It's a cool scene! Dig it.
how do i search for a particular string in a text file
Not really a C question, more of a general programming thing, but
certainly can be done in C.
There's not just one way to do it. The right way depends on the format
of the data in the file - eg., one record per line, comma separated,
tab separated, white space separated, etc. - and what you intend to do
with it and how fast the search must be. In either case, you're going
to have to read the file.
for example in the desired text file i have
time=1.24
value=306
Looks like one record per line, like the ubiquitous config file
format. Your best bet might be to simply read in a line at a time, from
the beginning of the file, using fgets(), and compare with the search
term using strncmp() or strstr(). Stop when you find the one you're
interested in.
i have to search the file for string 'time' and store its value of
1.24 in an array
Then maybe sscanf() would be better than strncmp() or strstr(). It
would extract the value as well as detect the correct line. Something
like so, for example:
#define MAX_LINE_LEN 100 /* or whatever value makes sense */
....
char buf[MAX_LINE_LEN];
char value[MAX_LINE_LEN];
....
while(fgets(buf, sizeof buf, the_file))
{
if(1 == sscanf(buf, "time=%s", value))
{
/* You have your value. Make some use of it. */
break;
}
}
Or perhaps you want the value stored as a floating point type. That's
easy enough. Just make value a double, and call sscanf() as sscanf(buf,
"time=%lf", &value).
similarly i have to search the file for string 'value'
If you have many of these entries to search for, it might be better to
read the whole file into memory before searching, then do the searches
in memory using strstr(). This will save time because you don't have to
read the file more than once. It'll also give you a null pointer when
the search term can't be found, which is useful for error detection.
You can still extract the value using sscanf() more or less as above.