search a string in file handling in c

Discussion in 'C Programming' started by neha_chhatre@yahoo.co.in, Feb 14, 2008.

  1. Guest

    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
    , Feb 14, 2008
    #1
    1. Advertising

  2. <> wrote in message news:
    > 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).

    --
    Free games and programming goodies.
    http://www.personal.leeds.ac.uk/~bgy1mm
    Malcolm McLean, Feb 14, 2008
    #2
    1. Advertising

  3. writes:

    > 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

    --
    Please remove just-for-news- to reply via e-mail.
    Friedrich Dominicus, Feb 14, 2008
    #3
  4. CBFalconer Guest

    wrote:
    >
    > 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 Zolman wrote:
    > On 25 Feb 2004 07:34:40 -0800, (spike) wrote:
    >
    >> Im trying to write a program that should read through a binary
    >> file searching for the character sequence "\name\"
    >>
    >> Then it should read the characters following the "\name\"
    >> sequence until a NULL character is encountered.
    >>
    >> But when my program runs it gets a SIGSEGV (Segmentation
    >> vioalation) signal.
    >>
    >> Whats wrong? And is there a better way than mine to solve
    >>this task (most likely)

    >
    > 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 */

    --
    [mail]: Chuck F (cbfalconer at maineline dot net)
    [page]: <http://cbfalconer.home.att.net>
    Try the download section.



    --
    Posted via a free Usenet account from http://www.teranews.com
    CBFalconer, Feb 14, 2008
    #4
  5. Guest

    On Feb 14, 3:56 pm, wrote:
    > 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
    -------------------
    , Feb 18, 2008
    #5
  6. Sorry for taking so long to post this!

    Groovy hepcat 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.

    --
    Dig the sig!

    ----------- Peter 'Shaggy' Haywood ------------
    Ain't I'm a dawg!!
    Peter 'Shaggy' Haywood, Feb 18, 2008
    #6
  7. CBFalconer Guest

    Peter 'Shaggy' Haywood wrote:
    > wrote:
    >
    >> how do i search for a particular string in a text file

    >

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

    --
    [mail]: Chuck F (cbfalconer at maineline dot net)
    [page]: <http://cbfalconer.home.att.net>
    Try the download section.



    --
    Posted via a free Usenet account from http://www.teranews.com
    CBFalconer, Feb 20, 2008
    #7
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Anand Pillai

    String search vs regexp search

    Anand Pillai, Oct 12, 2003, in forum: Python
    Replies:
    10
    Views:
    578
    Anand Pillai
    Oct 15, 2003
  2. Mark Tarver
    Replies:
    22
    Views:
    1,280
    J Kenneth King
    Apr 26, 2009
  3. Peter
    Replies:
    34
    Views:
    1,918
    James Kanze
    Oct 17, 2009
  4. Abby Lee
    Replies:
    5
    Views:
    380
    Abby Lee
    Aug 2, 2004
  5. Replies:
    1
    Views:
    187
    Dr.Ruud
    Jul 29, 2006
Loading...

Share This Page