C++ Make a file of a specific size

前端 未结 3 1625
刺人心
刺人心 2021-01-02 09:03

Here is my current problem: I am trying to create a file of x MB in C++. The user will enter in the file name then enter in a number between 5 and 10 for the size of the fil

相关标签:
3条回答
  • 2021-01-02 09:12

    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!

    0 讨论(0)
  • 2021-01-02 09:16

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-02 09:21

    To make a 2MB file you have to seek to 2*1024*1024 and write 0 bytes. fput()ting empty string will do no good no matter how many time. And the string is empty, because strings a 0-terminated.

    0 讨论(0)
提交回复
热议问题