Making a copy of a file is a simple but essential file operation supported by most systems. Furthermore, the copy operation should support both text and binary files. (Text files are a special subclass of binary files, so the copy operation will work with text files even when opened in binary mode.) Three of the four I/O operations described previously support binary I/O, but line-oriented I/O operations only make sense with character-oriented I/O. Therefore, the following program demonstrates how to copy a file using character, block, and buffer I/O operations, but not line operations.
int c; // (d)
while ((c = in.get()) != EOF) // (e)
out.put(c); // (f)
mycopy.cpp: character copy. C++ has many character I/O functions. The following code fragments illustrate just three of the available functions. The next section will provide greater detail explaining why these functions work with binary data.
The function reads data one character or one byte at a time
The full prototype for the get function is istream& get(char& c);. So, we can see that the parameter is passed by reference, which is how the character read from the file is returned. The stream classes define a conversion or casting operator, operator bool(), that converts the returned istream& into a Boolean value that can control the loop.
The character is simply copied to the output file.
This overloaded version of the get function returns each character as an integer, which is necessary for the next step.
The get function returns all characters as non-negative (i.e., ≥ 0) integers. The character is first stored in the variable c and then compared to the symbolic constant EOF, which is typically -1. The get function returns EOF when it reaches the end of the file.
C++ converts back and forth between characters and integers without an explicit type cast, which allows the put function, whose parameter type is char, to copy the character to the output file.