使用C++创建一个大小约为50-100MB的纯文本文件,其中内容应插入4百万次“Added first line”。
使用C++创建一个大小约为50-100MB的纯文本文件,其中内容应插入4百万次“Added first line”。
使用老式文件IO
fopen 打开用于写入的文件。
fseek 定位到所需文件大小减1的位置。
fwrite 写入单个字节。
fclose 关闭文件。
创建特定大小的文件最快的方法是使用creat()
或open()
创建一个零长度的文件,然后使用chsize()
更改大小。这将简单地为文件分配磁盘上的块,内容将是那些块中存在的任何内容。由于不需要进行缓冲区写入,因此速度非常快。
我不确定我是否理解了这个问题。您是否想确保文件中的每个字符都是可打印的ASCII字符?如果是这样,那么这个方法可以实现:用“abcdefghabc....”填充文件。
#include <stdio.h>
int main ()
{
const int FILE_SiZE = 50000; //size in KB
const int BUFFER_SIZE = 1024;
char buffer [BUFFER_SIZE + 1];
int i;
for(i = 0; i < BUFFER_SIZE; i++)
buffer[i] = (char)(i%8 + 'a');
buffer[BUFFER_SIZE] = '\0';
FILE *pFile = fopen ("somefile.txt", "w");
for (i = 0; i < FILE_SIZE; i++)
fprintf(pFile, buffer);
fclose(pFile);
return 0;
}
你没有提到操作系统,但我假设creat/open/close/write是可用的。
为了真正高效地写入数据,假设有一个4k页面和磁盘块大小以及重复字符串:
这样可以绕过fopen()和其他函数的缓冲区,这既有好处也有坏处:它们的缓冲意味着它们很快,但它们仍然不会像这样高效,因为它没有使用缓冲区的开销。
这可以很容易地用C++或C编写,但假设您将出于效率考虑使用POSIX调用,而不是iostream或stdio,因此它不在核心库规范之内。
我遇到了同样的问题,在Windows上非常快地创建了一个大约500MB的文件。 你传递给fwrite()的缓冲区越大,速度就越快。
int i;
FILE *fp;
fp = fopen(fname,"wb");
if (fp != NULL) {
// create big block's data
uint8_t b[278528]; // some big chunk size
for( i = 0; i < sizeof(b); i++ ) // custom initialization if != 0x00
{
b[i] = 0xFF;
}
// write all blocks to file
for( i = 0; i < TOT_BLOCKS; i++ )
fwrite(&b, sizeof(b), 1, fp);
fclose (fp);
}
现在至少在我的Win7,MinGW几乎立即创建文件。 与每次写入1字节的fwrite()相比,它将在10秒内完成。 传递4k缓冲区将在2秒钟内完成。
在C++中创建大文件的最快方法是什么? 好的。我假设最快的方式意味着运行时间最短。
使用C ++创建一个大小约为50-100 MB的平面文本文件,其中内容“添加第一行”应插入到文件中4百万次。
使用旧式文件IO预分配文件。
fopen the file for write.
fseek to the desired file size - 1.
fwrite a single byte
fclose the file
create a string containing the "Added first line\n" a thousand times.
find it's length.
使用旧式文件IO预分配文件空间
fopen the file for write.
fseek to the the string length * 4000
fwrite a single byte
fclose the file
open the file for read/write
loop 4000 times,
writing the string to the file.
close the file.
那是我最好的猜测。我相信有很多方法可以做到。