Re: binary file
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Tue, 19 Aug 2008 21:06:47 -0700
"Bill Cunningham" <nospam@xxxxxxxxx> writes:
I was wondering if someone could look this file over for me. It compiles
correctly and prints the number 2 so I know fscanf is working. I am reading
a text file and converting the text data obtained into a binary file. Now
here's my specific question. I have two doubles separated by a tab in the
text data. Are tabs preserved if you do what I have? My text file looks like
this
.26 0.00
and that's all and there's a tab there. Here's my source code.
Not bad, mostly.
Use "indent -kr --no-tabs". I've corrected the indentation
for this followup.
#include <stdio.h>
int main()
{
int rv;
double x, y;
FILE *fpr, *fpw;
if ((fpr = fopen("zo", "r")) == NULL) {
puts("open error");
return 1;
}
rv = fscanf(fpr, "%lf\t%lf", &x, &y);
printf("%i\n", rv);
fclose(fpr);
if ((fpw = fopen("z", "wb")) == NULL) {
puts("open write error");
return -1;
}
Ok so far. (There are a couple of things I could quibble about, but
I'll leave them aside for now.)
double a[1], b[1];
You've declared two arrays, each of which has only one element.
That's rarely a sensible thing to do.
x = a[1], y = b[1];
And here you go completely off the rails.
You've read values from your file into your variables "x" and "y", and
now you clobber those values by copying uninitialized array elements
over them. I think you've got the assignments backwards.
And why on Earth are you using a comma operator? Write the
assignments as two separate statements.
fwrite(a, sizeof(double), 1, fpw);
fwrite(b, sizeof(double), 1, fpw);
Ok, you used arrays so they'd be implicitly converted to pointers so
you can pass them to fwrite.
Get rid of the arrays and the assignments. If you want to write the
values of x and y to a binary file, just do it; it's completely
unnecessary to copy them to an array first. If you want to write the
value of x to a binary file using fwrite, the first argument to fwrite
should be the address of x.
fwrite returns a result that tells you whether it succeeded or not.
Look it up in K&R2 and check the result.
fclose(fpw);
fclose() can fail. If it does, its return value will tell you that.
Look it up in K&R2 and check the result.
return 0;[snip]
}
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- References:
- binary file
- From: Bill Cunningham
- binary file
- Prev by Date: Re: binary file
- Next by Date: Re: binary file
- Previous by thread: Re: binary file
- Next by thread: Re: binary file
- Index(es):
Relevant Pages
|