Interview Questions

I want to read and write numbers between files and memory ...

C Interview Questions and Answers


(Continued from previous question...)

I want to read and write numbers between files and memory ...

Q:I want to read and write numbers between files and memory in a byte-at-a-time way, not as formatted characters the way fprintf and fscanf do. How can I do this?

A: What you're trying to do is usually called ``binary'' I/O. First, make sure that you are calling fopen with the "b" modifier ("rb", "wb", etc.; Then, use the & and sizeof operators to get a handle on the sequences of bytes you are trying to transfer. Usually, the fread and fwrite functions are what you want to use;Note, though, that fread and fwrite do not necessarily imply binary I/O. If you've opened a file in binary mode, you can use any I/O calls on it if you've opened it in text mode, you can use fread or fwrite if they're convenient.
Finally, note that binary data files are not very portable;

(Continued on next question...)

Other Interview Questions