是否可以在一个循环中写入多个二进制文件
Is it possible to write to multiple binary files in a loop
我正在尝试打开一个二进制文件,从中读取,然后用std::ofstream
打开多个文件,并随机写入不同的文件。但是,我在编写的二进制文件中得到了一些垃圾值。不可能并行写入多个文件吗?这个问题的原因可能是什么?
因为当我创建一个流并编写所有内容时,它看起来还可以。这是我的二进制代码:
//For reading from a binary file
std::ifstream fileInput;
fileInput.exceptions(std::ifstream::failbit | std::ifstream::badbit);
const int numberOfFiles = 5;
std::ofstream outfile[numberOfFiles];
std::stringstream sstm;
for (int i = 0; i < numberOfFiles; i++)
{
sstm.str("");
sstm << "test" << i;
outfile[i].open(sstm.str());
}
try
{
fileInput.open("TestBinary.dat", std::ios::binary);
float f;
int newLineCounter = 0;
int index = 0;
while (fileInput.read(reinterpret_cast<char*>(&f), sizeof(float)))
{
outfile[index].write(reinterpret_cast<const char*>(&f), sizeof(float));
newLineCounter++;
// Since i am reading 3D points
if (newLineCounter == 3)
{
index = rand() % numberOfFiles;
newLineCounter = 0;
}
}
for (int i = 0; i < numberOfFiles; i++)
{
outfile[i].close();
}
fileInput.close();
}
catch (std::ifstream::failure e) {
std::cerr << "Exception opening/reading/closing filen";
}
当我读取该文件时,我会得到如下垃圾值:979383418452721018666090051403776.000000 500207915157676809436722056201764864.000000 2.16899e+17
您正在以文本模式打开文件。您需要以二进制模式打开它们。
outfile[i].open(sstm.str(), ios_base::out | ios_base::binary);
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 是否可以在一个循环中写入多个二进制文件
- 从二进制文件加载列表后,我的代码似乎进入了无限循环
- 将结构从二进制文件读取到链表,导致无限循环