c++ - 以二进制形式保存文本文件

标签 c++ file binary save

我有一个项目,我必须使用从用户那里获取的目标以二进制模式备份我的文本文件。 我正在考虑以二进制形式打开我的文本文件,然后在我从用户那里得到的地址中关闭它们。但我不知道该怎么做。

有没有办法关闭新地址中的文件(将它们保存在我想要的任何地方)而不是直接设置地址,因为它应该由用户设置

最佳答案

这是保存文件的示例代码:

#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/

相关文章:

Android:将字符串写入文件

python - 从特定字符串开始读取python中的文件

c - 在给定的二进制数据中找到最大面积

c++ - 不使用 reinterpret_cast 读取二进制数据

c++ - std::unique_ptr 和 std::ostringstream (SIGSEGV) 的奇怪行为

c++ - 使用 krb5 API 查找领域的 KDC

c++ - 我如何把它变成一个循环?

c++ - 为什么添加 `const` 会使通用引用成为右值

c++ - 拦截 Windows 文件系统,编辑数据?

Python在二进制中找到最大组合数