search a string in file handling in c

N

neha_chhatre

how do i search for a particular string in a text file
for example in the desired text file i have
time=1.24
value=306

i have to search the file for string 'time' and store its value of
1.24 in an array
similarly i have to search the file for string 'value'

please help me with this urgently
 
M

Malcolm McLean

how do i search for a particular string in a text file
for example in the desired text file i have
time=1.24
value=306

i have to search the file for string 'time' and store its value of
1.24 in an array
similarly i have to search the file for string 'value'

please help me with this urgently
Either

float ticktock;
int val;
sscanf(str, "time=%f value=%d", &ticktock, &va);

or build a custom scanner on top of strstr if you can't be sure of the
format.
(You might to take a look at the first chapter of my book, which is free, to
see how to do string functions to turn whitespace into single spaces and so
forth).
 
F

Friedrich Dominicus

how do i search for a particular string in a text file
for example in the desired text file i have
time=1.24
value=306
i have to search the file for string 'time' and store its value of
1.24 in an array
similarly i have to search the file for string 'value'
Opening a file is done with fopen
reading can be done by fread or probably better in this case fgets
finding a token in a string can be done with strtok, if you need
a bit more then that you may consider using a library for matching
regular expressions.

storing away things for time could be done in a hash table e.g

Regards
Friedrich
 
C

CBFalconer

how do i search for a particular string in a text file
for example in the desired text file i have
time=1.24
value=306

i have to search the file for string 'time' and store its value
of 1.24 in an array
similarly i have to search the file for string 'value'

Try this:

/*
Leor said:
I think so. Here's a version I just threw together:
*/

/* And heres another throw -- binfsrch.c by CBF */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>

/* The difference between a binary and a text file, on read,
is the conversion of end-of-line delimiters. What those
delimiters are does not affect the action. In some cases
the presence of 0x1a EOF markers (MsDos) does.

This is a version of Knuth-Morris-Pratt algorithm. The
point of using this is to avoid any backtracking in file
reading, and thus avoiding any use of buffer arrays.
*/

size_t chrcount; /* debuggery, count of input chars, zeroed */

/* --------------------- */

/* Almost straight out of Sedgewick */
/* The next array indicates what index in id should next be
compared to the current char. Once the (lgh - 1)th char
has been successfully compared, the id has been found.
The array is formed by comparing id to itself. */
void initnext(int *next, const char *id, int lgh)
{
int i, j;

assert(lgh > 0);
next[0] = -1; i = 0; j = -1;
while (i < lgh) {
while ((j >= 0) && (id != id[j])) j = next[j];
i++; j++;
next = j;
}
#ifdef DEBUG
for (i = 0; i <= lgh; i++)
printf("id[%d] = '%c' next[%d] = %d\n",
i, id, i, next);
#endif
} /* initnext */

/* --------------------- */

/* reads f without rewinding until either EOF or *marker
has been found. Returns EOF if not found. At exit the
last matching char has been read, and no further. */
int kmpffind(const char *marker, int lgh, int *next, FILE *f)
{
int j; /* char position in marker to check */
int ch; /* current char */

assert(lgh > 0);
j = 0;
while ((j < lgh) && (EOF != (ch = getc(f)))) {
chrcount++;
while ((j >= 0) && (ch != marker[j])) j = next[j];
j++;
}
return ch;
} /* kmpffind */

/* --------------------- */

/* Find marker in f, display following printing chars
up to some non printing character or EOF */
int binfsrch(const char *marker, FILE *f)
{
int *next;
int lgh;
int ch;
int items; /* count of markers found */

lgh = strlen(marker);
if (!(next = malloc(1 + lgh * sizeof *next))) {
puts("No memory");
exit(EXIT_FAILURE);
}
else {
initnext(next, marker, lgh);
items = 0;
while (EOF != kmpffind(marker, lgh, next, f)) {
/* found, take appropriate action */
items++;
printf("%d %s : \"", items, marker);
while (isprint(ch = getc(f))) {
chrcount++;
putchar(ch);
}
puts("\"");
if (EOF == ch) break;
else chrcount++;
}
free(next);
return items;
}
} /* binfsrch */

/* --------------------- */

int main(int argc, char **argv)
{
FILE *f;

f = stdin;
if (3 == argc) {
if (!(f = fopen(argv[2], "rb"))) {
printf("Can't open %s\n", argv[2]);
exit(EXIT_FAILURE);
}
argc--;
}
if (2 != argc) {
puts("Usage: binfsrch name [binaryfile]");
puts(" (file defaults to stdin text mode)");
}
else if (binfsrch(argv[1], f)) {
printf("\"%s\" : found\n", argv[1]);
}
else printf("\"%s\" : not found\n", argv[1]);
printf("%lu chars\n", (unsigned long)chrcount);
return 0;
} /* main binfsrch */
 
S

srimks11

how do i search for a particular string in a text file
for example in the desired text file i have
time=1.24
value=306

i have to search the file for string 'time' and store its value of
1.24 in an array
similarly i have to search the file for string 'value'

please help me with this urgently

Hi

Do following steps -
(i) Open a file using fopen API.
(ii) Use strstr() to match the pattern of strings "time" & "value".
(iii) There may be situation where particular numeric values of "time"
& "value"
is needed, perform linear-search.
(iv) Close the file.

Though above operation seems to be costly as you will be using library
calls.

Try performing search of strings "time" & "value" using pointer calls.

Note: Never use strtok() or Isspace() API's library calls, though they
can serve the purpose
but their purpose are totally different.

HIH.

BR
Mukesh K Srivastava
-------------------
 
P

Peter 'Shaggy' Haywood

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.
 
C

CBFalconer

Peter said:
.... snip ...
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.

True. However, all those possibilities are catered to in the
program I published here a week ago. Or caterable to, with minor
modifications.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top