user4336026
user4336026

Reputation:

Does std::ofstream write sequential data to disk or does it only use the disk's free space?

Lets say that I want to create a 1 GB binary file of all 1's for whatever reason using ofstream. And lets say for the sake of argument that the particular drive I'm going to be creating this file on is heavily fragmented and it only has 1 GB of free space left on the disk. Here's a basic example of what it would look like:

#include <fstream>
#include <cstdint>

int main (int argv, char *argc[])
{
    int length_of_file = 1073741823; // 1024^3 - 1 bytes
    uint8_t data_block = 0xff;

    std::ofstream os;
    os.open("C:\\foo.bin", std::ios::trunc | std::ios::binary);

    while (os.is_good()) {
        for (int i = 0; i < length_of_file; ++i) {
            os.write(data_block, sizeof(uint8_t));
        }
    }

    os.close();
    return 0;
}

This should write 1 GB worth of 1's to the file "foo.bin", but if ofstream writes sequential data to the drive then this would overwrite files on the disk with 1's.

So my question is: will this method overwrite any files in the hard drive?

Upvotes: 0

Views: 720

Answers (1)

jschultz410
jschultz410

Reputation: 2899

No, this method won't overwrite any files on your hard drive (other than C:\foo.bin). The OS ensures that your files are independent. Most likely you will get an error during your run where the disk drive complains about running out of space and your drive will be nearly completely full.

Note, the way you've structured your loops is a bit strange and probably not what you intended. You probably want to eliminate your outer loop and move the call to os.is_good() into the inner loop:

for (int i = 0; os.is_good() && i < length_of_file; ++i) {
  os.write(data_block, sizeof(uint8_t));
}

Upvotes: 2

Related Questions