C++ Make a file of a specific size

心已入冬 提交于 2019-12-18 16:46:40

问题


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 file they want created. Later on in this project i'm gonna do other things with it but I'm stuck on the first step of creating the darn thing.

My problem code (so far):

        char empty[1024];
        for(int i = 0; i < 1024; i++)
        {
            empty[i] = 0;
        }

        fileSystem = fopen(argv[1], "w+");


        for(int i = 0; i < 1024*fileSize; i++){
            int temp = fputs(empty, fileSystem);
            if(temp > -1){
                //Sucess!
            }
            else{
                cout<<"error"<<endl;
            }
        }

Now if i'm doing my math correctly 1 char is 1byte. There are 1024 bytes in 1KB and 1024KB in a MB. So if I wanted a 2 MB file, i'd have to write 1024*1024*2 bytes to this file. Yes?

I don't encounter any errors but I end up with an file of 0 bytes... I'm not sure what I'm doing wrong here so any help would be greatly appreciated!

Thanks!


回答1:


Here is what things would look like in actual c++

Edit Here is a way shorter variant that does functionally the same (sample creates output.img of 300Mb):

#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.


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



回答2:


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!




回答3:


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.



来源:https://stackoverflow.com/questions/7896035/c-make-a-file-of-a-specific-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!