#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2003
    Posts
    1
    Rep Power
    0

    Question Getting Line From File: fscanf() going nuts!


    I'm using an ANSI C program to read in data from a file that has, every few lines, a name on it. Sometimes the name is just a first name, as in "Dave", and sometimes it's two names, as in "Bob Jones". I need to store the name in a string, and I need all of it (not just the first name when two names are present).

    I took a hint from another DevShed Forum discussion and tried this for the line that reads in the name:

    Code:
    fscanf( ipf, "%[^\n]", struct.memberString );
    The idea is that the "%[^\n]" gets everything but newlines, so I get everything on the present line in the file buffer (ipf). But when I do this repeatedly with other names or multi-word values I get nothing. I've gone in with a debugger, and after those lines (that are, practically, identical to the above with the substitution of a different string the fscanf()'d data is being stored in) nothing is stored in them. It's like those subsequent fscanf()'s are reading in null terminators (\0's) from the file.

    Basically, my question is this: how the heck in ANSI C do I read in just a line from a file buffer, getting everything on the line including spaces but not newlines and stray null terminators? Is my fscanf() syntax wrong? Should I be using fgetc() and some sort of while loop? Please help!
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    Try using this format specifier:
    Code:
        fscanf(ipf, "%[^\n]%*c", struct.memberString);
    Basically, the %[^\n] should read everything upto the \n (which is left behind on the read buffer). To account for the \n, which is still left behind, the code uses %*c to read the \n character, but not assign it to any variable.

    Alternatively, you can also use fgets(). Hope this helps :)
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2002
    Posts
    421
    Rep Power
    12
    while(getline(files,x))

    where files is the name of the stream and x is the string to put it into. I think that getline function reads the whole file though..not sure.

    Then again..i might just be stupid and telling you the wrong thing.

    -andy
    hmmm...

IMN logo majestic logo threadwatch logo seochat tools logo