Search code examples
c++iobinaryofstream

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


I am trying to open a binary file, read from it and then open multiple files with std::ofstreamand write into seperate files randomly. However, i get some garbage values in the written binary file. Is it not possible to write into multiple files paralel? What could be the cause of this issue?

Because when i create one ofstream and write everything, it seems okay. Here is my code for writing to binary:

//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";
}

when i read the file i get garbage values like this: 979383418452721018666090051403776.000000 500207915157676809436722056201764864.000000 2.16899e+17


Solution

  • You're opening your files in text mode. You need to open them in binary mode.

    outfile[i].open(sstm.str(), ios_base::out | ios_base::binary);