我正在使用 cstdio
函数创建一个空的二进制文件,并需要将其初始化为特定字节值(可以为零,但不一定为零)。
FILE* file = std::fopen("path/to/file", "wb+");
有没有办法用一个值填充整个文件,或者创建并填充缓冲区然后使用 std::fwrite
连续填充文件我唯一的选择?有点像
std::ffill(byteValue, sizeof(byteValue), fileSize, file);
拥有特定于平台的解决方案是可以的(我的目标是 windows 和 linux)。
最佳答案
使用 C++ iostreams,这很简单:
std::ofstream out("path/to/file", std::ios::binary);
char byteValue = '\0'; // or whatever
std::fill_n(std::ostreambuf_iterator<char>(out), fileSize, byteValue);
但是,如果 fileSize
确实很大,您可能更愿意使用 std::ofstream::write
来代替——它会快得多。
关于c++ - 如何创建一个新的二进制文件并用常量值填充它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50702666/