Reputation: 1654
I have a file with a header of two lines, and the rest contains two columns of double data like
0.0030556304 -0.0078125
The first column is 16 characters long, and the second column is 17 characters long, after there is a space and the '\n'.
My code to read this file is
nscan = fscanf(sound_file, "%lf %lf %c", &value1,
&value2,
&termch);
I use termch
to test further for newline character.
I've tried with
nscan = fscanf(sound_file, "%16lf %16lf %c", &value1,
&value2,
&termch);
too.
But when I printf the with
printf("%f %f\n", value1, value2);
the result is
-0.000000 -0.000000
Am I missing something?
Upvotes: 0
Views: 230
Reputation: 153582
fscanf(sound_file, "%lf %lf %c"...
is not doing what you think.
The space before "%c"
consumes all white-space including ' '
and '\n'
. The following "%c"
will consume the next char
(which must be non-white-space at this point), if any.
Better to read all files lines using fgets()
and then scan the buffer with sscanf()
char buf[100];
// Read 2 header lines and toss
if (fgets(buf, sizeof buf, sound_file) == NULL) Handle_EOForIOError();
if (fgets(buf, sizeof buf, sound_file) == NULL) Handle_EOForIOError();
// Insure code is using a type the match format specifiers
// Could be a problem in OP's unposted code.
double value1, value2;
while (fgets(buf, sizeof buf, sound_file) != NULL) [
int cnt = sscanf(buf, "%lf%lf", &value1, &value2);
if (cnt != 2) Handle_MissingData();
else Use(value1, value2);
}
fscanf("%lf",...
scans for optional leading white-space and then for a double. A leading " "
before the "%lf"
is not needed.
fscanf("%16lf",...
will limit the total number of non-white-space char
scanned to 16.
Upvotes: 1