I've been trying to fopen a file, fread it and fwrite it to another file
or stdout while having k&r2 at hand and having no luck. The appendix seems
to be very vague on the FILE struct components.
It *SHOULD* be vague on the FILE struct components. Hands off!
The stuff in there is system-specific and is likely to not be very
helpful unless you really know how it works, in which case you
probably wouldn't be having the above problem.
When you call fopen(), do you check for whether it returns NULL?
If fopen() returns NULL, do you call perror() or strerror() and
then print the resulting string in a nice error message for the
user/programmer? (Yes, I know fopen() is not guaranteed to set
errno, but as long as it's not guaranteed to *NOT* set errno,
printing the possibly irrelevant message is more useful for the
programmer, or for the user who can report it to the programmer,
to debugging than not printing it). You do need to realize that
some error messages are not applicable, for example, "output.txt:
not a typewriter" doesn't make a lot of sense, but "output.txt:
permission denied" suggests a reason why the file couldn't be
created.
Did you fopen() the file in binary mode? Do you WANT to open the
file in binary mode? If you are trying to fwrite() the contents
of C types such as int, long, float, double, or struct, chances are
you want to open an output file in binary mode, and when you try
to read it back in, you also want it opened in binary mode. On the
other hand, if you're just going to fwrite() blobs of text, maybe
you want the file open in text mode.
Do you check the return values from fread() and fwrite()? Have you
tried using a hex dump utility on the output file, and compared the
file contents with what you expect to be in there? Does your code
realize that fread() may well read in the data in chunks that don't
correspond with the chunks that you wrote in the first place?
Gordon L. Burditt