ftell fseek

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Thu Dec 13 13:36:46 AEST 1990


In article <kim.660990813 at kowari>, kim at bilby.cs.uwa.oz.au (Kim Shearer) writes:
--> while (fscanf (my_file_p, "%s", name) == 1) {
-->     marker = ftell (my_file_p);
>       fscanf (my_file_p, "%d", &old_hours);

There's at least one of your problems.  You're getting the position of
the file JUST AFTER a string.  What you want is the position BEFORE.
In short:

	while (marker = ftell(my_file_p),
	       2 == fscanf(my_file_p, "% s%d", name, &old_hours)
	      ) {
	    /* at this point, fseek()ing back to 'marker' will get
	       you to the point BEFORE the string, so that another
	       fscanf() like the one above will read the right stuff.
	    */
	}

A word of warning:  it would be as well to protect yourself against
overflow.

	char format[80];
	char check;

	sprintf(format, "%%%us%%c%%d", (sizeof name) - 1);

	... 3 == fscanf(my_file_p, format, name, &check, &old_hours)
	    && isspace(check) ...

to read no more characters into name[] than will fit, and check that
reading into name stopped because there was no more of the strig to
read, not because name[] ran out of space.  (The *scanf() functions
are enough to make a C programmer think about getting f2c ...)

-- 
The Marxists have merely _interpreted_ Marxism in various ways;
the point, however, is to _change_ it.		-- R. Hochhuth.



More information about the Comp.lang.c mailing list