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

标签 c++ io binary ofstream

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

关于c++ - 是否可以在循环中写入多个二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58770966/

相关文章:

erlang - 粘合二进制文件(list_to_binary)有多贵?

c++ - 错误 : no match for ‘operator<’ in ‘__x < __y’ when trying to insert in two map

c# - 从 BackgroundWorker C# 调用的 CoInitialize

java - 用户输入到java中的文本文件中

c - Windows中的 `fprintf()`和 `fscanf()`是否需要以文本模式打开文件

postgresql - 如何将字符串属性映射到数据库中的二进制列?

c++ - 为返回的 shared_ptr 赋值不符合预期

c# - 使用结构 union 将 C++ 编码到 C# 结构

perl - Perl 中的输出流 : STDERR, STDOUT,

C++ 文件 (exe) 读取自身