Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty file of the specified size in Windows by C++ or C or C#? [closed]

Tags:

c++

c

c#

windows

How to create an empty file of the specified size in Windows by C++ or C or C# ?

This file does not take up disk space, Open the file, there isn't anything. But file has number of bytes in the file properties.

For example--

enter image description here

like image 837
J.Hero Avatar asked Dec 20 '25 11:12

J.Hero


1 Answers

You can do in c++ like this:

#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;
        }
    }
}


In c#: to make 2GB of file: Simply create the file, seek to a suitably large offset, and write a single byte:

FileStream fs = new FileStream(@"c:\tmp\huge_dummy_file", FileMode.CreateNew);
fs.Seek(2048L * 1024 * 1024, SeekOrigin.Begin);
fs.WriteByte(0);
fs.Close();
like image 152
Sorangwala Abbasali Avatar answered Dec 22 '25 23:12

Sorangwala Abbasali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!