简体   繁体   中英

saving text file in binary

I have a project witch I have to back up my text files in binary mode with the destination that is getting from the user. I was thinking to open my text files in binary and close them in the address that I have got from the user. but I don't know how to do that.

is there a way to close the files in a new address(saving them where ever I want) and not set an address directly because it's suppose to set by the user

Here is sample code to save the file:

#include <fstream>
int main () {
    std::ofstream ofs;
    ofs.open ("test.txt", std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);
    ofs << " data goes here";
    ofs.close();
    return 0;
}

The following is sample code to copy files:

ifstream source("from.txt", ios::binary);
ofstream dest("to.txt", ios::binary);

source.seekg(0, ios::end);
ifstream::pos_type size = source.tellg(); // file size
source.seekg(0);

char* buffer = new char[size]; // allocate memory for buffer

// copy file    
source.read(buffer, size);
dest.write(buffer, size);

// clean up
delete[] buffer;
source.close();
dest.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM