//* Reading and writing data in binary mode - copy file exmaple *

#include <iostream> #include <fstream> #include <string> using namespace std; int main() { // can be used both with char[] and string, it does not matter string inName; string outName; // prompting user for filenames cout << "Read text from: "; getline(cin,inName); cout << "Write text to: "; getline(cin,outName); ifstream inFile; ofstream outFile; inFile.open(inName, ios::in|ios::binary); if (!inFile.is_open()) { cout << "ERROR: Cannot open " << inName << " file for reading." << endl; return(1); } outFile.open(outName, ios::out|ios::binary); if (!outFile.is_open()) { cout << "ERROR: Cannot open " << inName << " file for writing." << endl; inFile.close(); return(1); } // reading-writing loop for (;;) { char buffer[256]; // this is the largest chunk of data we can read at a time // read UP TO 256 bytes, the actual number of bytes read is returned inFile.read(buffer, sizeof(buffer)); unsigned long bytes_read = inFile.gcount(); // you must not assume that always requested number of bytes is read // because of last reminder of bytes at the end of the file // DO NOT use inFile.readsome(,) instead the code used above // - unlike the textbook says IT IS NOT equivalent to the two liens above if (bytes_read==0) break; // cout << " " << bytes_read; outFile.write(buffer, bytes_read); if (outFile.fail()) { outFile.clear(); cerr << "ERROR: writing to file failed!" << endl; break; } } inFile.clear(); inFile.close(); outFile.close(); return(0); }