#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    245
    Rep Power
    11

    using fscanf function


    ==============================
    Is there a method of using fscanf to where it will read in a value
    after an equal sign ? For example in the file network-config
    below when using the code
    fscanf(file_pointer, "%s", &var1);

    the var1 variable will contain 10.4.0.1 and not
    ETH1=10.4.0.1.

    I could of course, read a file character by character, but I thought
    fscanf would be quicker in this case.

    ==============================
    root:~# ./test_putenv2
    var1 = ETH1=10.4.0.1

    ==============================

    root:~# cat /etc/yellowbox/network-config
    ETH1=10.4.0.1
    ETH0=216.143.22.145
    NETMASK=255.255.255.0
    GATEWAY=216.143.22.1
    FIREWALLGROUP=0
    HOSTNAME=printer

    ==============================

    #include <stdio.h>
    #include <stdlib.h>

    main()

    {
    FILE *f, *file_pointer, *fopen();
    char var1[21];

    file_pointer = fopen ("/etc/yellowbox/network-config", "r");
    fscanf(file_pointer, "%s", &var1);
    printf("var1 = %s\n", var1);

    fclose(file_pointer);
    }
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,091
    Rep Power
    2222
    I am admittedly not an expert on the scanf family, but this might get you started.

    From the fscanf man page:
    * Suppresses assignment. The conversion that follows
    occurs as usual, but no pointer is used; the result
    of the conversion is simply discarded.
    So my understanding is that something like this should work:
    fscanf(fp,"%*s=%s", var1);

    Operating on the string, "ETH1=10.4.0.1", var1 should end up containing "10.4.0.1". var1 should not need the address operator (&) because it is already a pointer. And you might need to put a '\n' in that format string, too.

    See if that works (sorry, I haven't tested it). If not, then it hopefully shouldn't take much tweaking. Or one of the resident scanf residents might step in and offer the correction.
    Last edited by dwise1_aol; July 14th, 2003 at 12:01 PM.
  4. #3
  5. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,594
    Rep Power
    4207
    Use this:
    Code:
    fscanf(fp, "%*[^=] %*c %s", var1);
    Please see URGENT Quickie: fscanf a line from a file? Please help me, deadline in a few hours! for an explanation of why this works :)
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    245
    Rep Power
    11

    Thank you all


    Thank you dwise1_aol.
    Thank you Scorpions4ever. It works.

IMN logo majestic logo threadwatch logo seochat tools logo