Reading and Writing Binary Files
Reading and writing binary files involves working with raw data, often consisting of binary codes representing various types of data. One common task is to read data from a binary file into a buffer and then write it to another file.
Problem:
When attempting to read and write a binary file using the following code, only a few ASCII characters from the first line of the file are stored in the buffer:
int length; char * buffer; ifstream is; is.open ("C:\Final.gif", ios::binary ); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg); // allocate memory: buffer = new char [length]; // read data as a block: is.read (buffer,length); is.close(); FILE *pFile; pFile = fopen ("C:\myfile.gif", "w"); fwrite (buffer , 1 , sizeof(buffer) , pFile );
Solution:
There are two possible ways to solve this issue:
Using C streams:
This method involves using the ifstream and ofstream classes provided by the C standard library. It allows for efficient and portable file handling.
#include <fstream> #include <iterator> #include <algorithm> int main() { std::ifstream input( "C:\Final.gif", std::ios::binary ); std::ofstream output( "C:\myfile.gif", std::ios::binary ); std::copy( std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>( ), std::ostreambuf_iterator<char>(output)); }
Using a buffer for modification:
If the data needs to be manipulated or modified before writing it to a file, a buffer can be used to store it.
#include <fstream> #include <iterator> #include <vector> int main() { std::ifstream input( "C:\Final.gif", std::ios::binary ); // copies all data into buffer std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {}); }
The above is the detailed content of Why Does My Binary File Copy Only Partially, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!