Re: question
- From: "Bill Cunningham" <nospam@xxxxxxxxx>
- Date: Sun, 13 Jan 2008 17:05:53 GMT
"Keith Thompson" <kst-u@xxxxxxx> wrote in message
news:87fxx2s8al.fsf@xxxxxxxxxxxxxxxxxx
"Bill Cunningham" <nospam@xxxxxxxxx> writes:
I wrote this small program to read a 512 block of binary data and
write
the same to a file. My code compiled well. The only thing is when I ran
the
compilers binary instead of a data file of 512 bytes I got one of 2048
bytes.
#include <stdio.h>
main(){
"int main(void) {"
int buf[512];
FILE *fp;
fp=fopen("r.dsk","rb");
if (fp==NULL) {printf("Error"); exit(0);}
You need "#include <stdlib.h>" for exit.
fread(buf,sizeof(int),512,fp);
No error checking.
fclose(fp);
No error checking (yes, fclose can fail).
I don't remember reading that in my lliterature. Thanks for the tip.
fp=fopen("dat","wb");
if (fp==NULL) {printf("Error");}
Above, you printed an error message and terminated the program. Here
you print an error message and continue.
fwrite(buf,sizeof(int),512,fp);
No error checking.
fclose(fp);}
No error checking (yes, fclose can fail).
Add "return 0;".
*Please* put the closing "}" on a line by itself. It's very difficult
to see.
Is it the code or some overhead from the compiler or linker?
And finally, the answer to your question:
The program is doing exactly what it's supposed to do. Read the
documentation for fread() and fwrite(). They both take two size_t
arguments, the size in bytes of each element and the number of
elements. You're asking fread() to read 512 element, each of which is
sizeof(int) bytes (in other words, 512 ints, not 512 bytes). If int
is 4 bytes on your system, you'll read and write 2048 bytes (assuming
there are no errors).
One more thing: it's conventional to print error messages to stderr,
and to use the argument to exit() to indicate success or failure.
Rather than
if (fp==NULL) {printf("Error"); exit(0);}
I'd write:
if (fp == NULL) {
fprintf(stderr, "Error\n");
exit(EXIT_FAILURE);
}
Okay. stderr. I skipped ahead in the tutorial to write this. But I'm
actually learning C! If I could get as good at as I am Basic I'll be like
Richard Heathfield or Ben Pfaff. Maybe even dmr. It's great to have a
community.
Yes, I also changed the code layout. Whitespace is not in short
supply; use as much as you need to make the code clear and readable.
This is a question of style. That I'll have to learn. All my code so far
is snippets. I'll have to catch up on that :)
Bill
.
- Follow-Ups:
- Re: question
- From: Serve Lau
- Re: question
- References:
- question
- From: Bill Cunningham
- Re: question
- From: Keith Thompson
- question
- Prev by Date: Re: question
- Next by Date: Re: Pointer conversions
- Previous by thread: Re: question
- Next by thread: Re: question
- Index(es):
Relevant Pages
|