1

The following small program is supposed to create a binary file, write 6 uint (typedef'ed as unsigned int) to it, and then read and print the data back from the same file.

#include <iostream>
#include <fstream>
#include <string>

typedef unsigned int uint;

using namespace std;

int main(int argc, char* argv[])
{
    string usr = [my username];
    string szFile = "C:/Users/" + usr + "/iotest.bin";
    cout << "File Streaming Test\n" << sizeof(uint) << "\n\n";

    ifstream inFile = ifstream(szFile, ios_base::in | ios_base::binary);

    if (inFile.fail()) {
        // file probably DNE, create it and write some data to it
        inFile.clear();

        // first, close the input stream
        // so the output stream can be opened
        inFile.close();

        // open the output stream
        ofstream outFile = ofstream(szFile, ios_base::out | ios_base::trunc | ios_base::binary);
        // make sure these are written as uint
        uint zero = 0;
        uint one = 1;
        uint two = 2;

        // write the data
        outFile << two << two << zero << one << one << zero;

        // flush and close the output stream
        outFile.flush();
        outFile.close();
    }

    // if we had to create the file,
    // then reopen the input stream
    if (!inFile.is_open())
        inFile.open(szFile, ios_base::in | ios_base::binary);

    // read 6 uint from the file
    uint arr[6];
    for (int i = 0; i < 6; i++) {
        inFile >> arr[i];
        cout << arr[i] << endl;
    }

    // pause
    while (cin.get() != '\n');

    // inFile auto-closes when it goes out of scope
    return 0;
}

When I run the program once, it generates the following output:

File Streaming Test
4

220110
3435973836
3435973836
3435973836
3435973836
3435973836

Running the program a second time (after checking the the file does exist in the file explorer) generates the same output. Windows (file explorer) says that the created file is only 6 bytes in size, when it should be 6 * 4 = 24 bytes in size. It's like outFile is only writing part of what I give it. The reading of 220110 in one uint is odd because it matches the six numbers I wrote, but binary representation wouldn't just concatenate the digits like that.

0 Answers0