Creating big file on Windows

后端 未结 6 643
情歌与酒
情歌与酒 2020-12-17 10:03

I need to create big relatively big (1-8 GB) files. What is the fastest way to do so on Windows using C or C++ ? I need to create them on the fly and the speed is really a

6条回答
  •  被撕碎了的回忆
    2020-12-17 10:37

    I am aware that your question is tagged with Windows, and Brian R. Bondy gave you the best answer to your question if you know for certain you will not have to port your application to other platforms. However, if you might have to port your application to other platforms, you might want to do something more like what Adrian Cornish proposed as the answer for the question "How to create file of “x” size?" found at How to create file of "x" size?.

    FILE *fp=fopen("myfile", "w");
    fseek(fp, 1024*1024, SEEK_SET);
    fputc('\n', fp);
    fclose(fp);
    

    Of course, there is an added twist. The answer proposed by Adrian Cornish makes use of the fseek function which has the following signature.

    int fseek ( FILE * stream, long int offset, int origin );
    

    The problem is that you want to create a very large file with a file size that is beyond the range of a 32-bit integer. You need to use the 64-bit equivalent of fseek. Unfortunately, on different platforms it has different names.

    The header file LargeFileSupport.h found at http://mosaik-aligner.googlecode.com/svn-history/r2/trunk/src/CommonSource/Utilities/LargeFileSupport.h offers a solution to this problem.

    This would allow you to write the following function.

    #include "LargeFileSupport.h"
    /* Include other headers. */
    
    bool createLargeFile(const char * filename, off_type size)
    {
        FILE *fp = fopen(filename, "w");
        if (!fp)
        {
            return false;
        }
        fseek64(fp, size, SEEK_SET);
        fputc('\n', fp);
        fclose(fp);
    }
    

    I thought I would add this just in case the information would be of use to you.

提交回复
热议问题