(Feb 12, 2016 11:41 AM)Ticoma Wrote: I've been looking at code for reading and writing binary files, and I've seen the code #define BLOCK 64; at the top of the file (is this the header?) This code is later followed by writer.write((char *) myarray, BLOCKS); so I assume BLOCKS is some sort of structure which is referring to 64, not 32bit binary code chunks?
fstream writer("copied2.pdf",std::ios::out | std::ios::binary); Then there is this, which declares the fstream variable as binary. Are there any books that include this sort of information about reading bianry file types and these std::io open mode flags, or is this stuff generally learned on your own in research?
#define is a macro which defines BLOCK 64. It's like declaring an int BLOCK=64 but not exactly. It's different in a lot of ways. Every time the compiler sees BLOCK in your program, it simply replaces it with 64. Read about macros in C/C++, you'll understand what they are.
Now let's talk about
writer.write((char *) myarray, BLOCKS); . writer is your object of class fstream which stands for file stream. The write member function of this class requires two parameters. The first parameter is the character pointer to the address of data that you want this function to write in your file. So
myarray, I assume is a pointer to your data or else you'd have written it as
writer.write((char *)&myarray, BLOCKS); if it was a variable. (*char) actually typecasts the address pointer to type character pointer as I already said that the functions requires a character pointer.
The second parameter id the size of data that you want to write. Usually it's a bad practice to define the size of data statically(as in your case). A good practice is to use
sizeof() operator. It makes your code more portable. But I could think of some situations where I'd use the you have chosen. Suppose the size of data varies for each call of write function but would not exceed 64 bytes. In this case, it's good to choose your style. Why? Well, it's because a file with data written in fixed size of block makes it easier to retrieve the data from it(Feel free to correct me on this one if I'm wrong because I've never been through such situation). Hope this answer helps.
Refer these links for further studies
http://www.cplusplus.com/doc/tutorial/preprocessor/
http://www.cplusplus.com/reference/ostre...eam/write/
and the one specified by AnnabelleLee.
Enjoy programming :)