是否可以在一个循环中写入多个二进制文件

Is it possible to write to multiple binary files in a loop

本文关键字:循环 二进制文件 一个 是否      更新时间:2023-10-16

我正在尝试打开一个二进制文件,从中读取,然后用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);