是否可以在循环中写入多个二进制文件
Is it possible to write to multiple binary files in a loop
我正在尝试打开一个二进制文件,从中读取,然后使用 std::ofstream
打开多个文件并随机写入单独的文件。但是,我在写入的二进制文件中得到了一些垃圾值。不能并行写入多个文件吗?这个问题的原因可能是什么?
因为当我创建一个 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 file\n";
}
当我读取文件时,我得到如下垃圾值:
979383418452721018666090051403776.000000 500207915157676809436722056201764864.000000 2.16899e+17
您正在以文本模式打开文件。您需要以二进制模式打开它们。
outfile[i].open(sstm.str(), ios_base::out | ios_base::binary);
我正在尝试打开一个二进制文件,从中读取,然后使用 std::ofstream
打开多个文件并随机写入单独的文件。但是,我在写入的二进制文件中得到了一些垃圾值。不能并行写入多个文件吗?这个问题的原因可能是什么?
因为当我创建一个 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 file\n";
}
当我读取文件时,我得到如下垃圾值:
979383418452721018666090051403776.000000 500207915157676809436722056201764864.000000 2.16899e+17
您正在以文本模式打开文件。您需要以二进制模式打开它们。
outfile[i].open(sstm.str(), ios_base::out | ios_base::binary);