C++ Make a file of a specific size

Your code doesn't work because you are using fputs which writes a null-terminated string into the output buffer. But you are trying to write all nulls, so it stops right when it looks at the first byte of your string and ends up writing nothing.

Now, to create a file of a specific size, all you need to do is to call truncate function (or _chsiz for Windows) exactly once and set what size you want the file to be.

Good luck!


Potentially sparse file

This creates output.img of size 300 MB:

#include <fstream>

int main()
{
    std::ofstream ofs("ouput.img", std::ios::binary | std::ios::out);
    ofs.seekp((300<<20) - 1);
    ofs.write("", 1);
}

Note that technically, this will be a good way to trigger your filesystem's support for sparse files.

Dense file - filled with 0's

Functionally identical to the above, but filling the file with 0's:

#include <iostream>
#include <fstream>
#include <vector>

int main()
{
    std::vector<char> empty(1024, 0);
    std::ofstream ofs("ouput.img", std::ios::binary | std::ios::out);

    for(int i = 0; i < 1024*300; i++)
    {
        if (!ofs.write(&empty[0], empty.size()))
        {
            std::cerr << "problem writing to file" << std::endl;
            return 255;
        }
    }
}

Tags:

C++

Fopen

Fputs