Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

can't figure scanf operation...

Status
Not open for further replies.

msc0tt

IS-IT--Management
Jun 25, 2002
281
CA
My program writes, and reads a flatfile DB. Writing new lines is easy enough:
fprintf(fd, "%s/%s %02d-%02d-%04d %02d:%02d:%02d\n", var, var, ...")

Reading the lines back is the problem:

fscanf(fd, "%s/%s %02d-%02d-%04d %02d:%02d:%02d\n", &var, &var, ...")

I seldom use scanf, but in this case figured it would be a one-line no-brainer.... Wrong! ;-{)

Any experienced scanf'ers see the problem?
 
What happens if you drop the type formatting, like just %d instead of %02d? Shouldn't really be needed if all fields are otherwise delimited. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
One problem that may occur is that scanf considers spaces as variable delimiters, as a result if you have astring that contains the text "fred bloggs" then scanf will only grab the text fred from the file for the first variable, not fred bloggs as you probably intended.

Generally most C programmers steer well clear of scanf and its cousins for this reason.

Generally when I am faced with your problem I write the variables to the file interspersed with a character that I know will never occur in the text (say ^) using printf but when I read it back I read the whole record in using fgets() and then use strtok to break the buffer into variables.

Cheers - Gavin
 
Thanks for the tips. After reading the *long* description of scanf(), it turns out that it ALWAYS uses whitespace to delimit variables. My attempt to use "%s/%s" to scan in "Hi/There" would never work. So much for a 1-line solution - sigh....
I do like the strtok() however! (never used this guy before). I'll give this a go. -cheers
 
There is limited character class support in scanf. I think something like "%[^/]/%s" would scan "Hi/There" in two pieces. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top