我有一个项目,我必须使用从用户那里获取的目标以二进制模式备份我的文本文件。 我正在考虑以二进制形式打开我的文本文件,然后在我从用户那里得到的地址中关闭它们。但我不知道该怎么做。
有没有办法关闭新地址中的文件(将它们保存在我想要的任何地方)而不是直接设置地址,因为它应该由用户设置
最佳答案
这是保存文件的示例代码:
#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;
}
复制文件的示例代码如下:
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();
关于c++ - 以二进制形式保存文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21072113/