我添加一些功能到使用纯C的功能(一个现有的代码库fopen,fwrite,fclose)将数据写入到一个文件.不幸的是我无法改变文件i/o的实际机制,但我必须为文件预先分配空间以避免碎片(这会在读取过程中破坏我们的性能).有没有更好的方法来实际写入零或随机数据到文件?当我打开文件时,我知道文件的最终大小.
我知道我可以在linux上使用fallocate,但我不知道windows的等价物是什么.
谢谢!
我已经在一个相当大的C++项目上工作了几个星期了.我最初的目标是使用这个项目来学习C++ 11并仅使用纯C++代码并避免手动分配和C构造.但是,我认为这个问题会迫使我用C来做一个小函数,我想知道为什么.
基本上我有一个保存功能,它会在我更改其中的数据之前将一个稍大的二进制文件复制到一个单独的位置.文件本身是CD图像,最大大小约为700MB.这是我使用的原始C++代码:
std::ios::sync_with_stdio(false);
std::ifstream in(infile, std::ios::binary);
std::ofstream out(outfile, std::ios::binary);
std::copy(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(out));
out.close();
in.close();
Run Code Online (Sandbox Code Playgroud)
与690MB文件一起使用时,此代码只需不到4分钟即可完成.我用多个文件运行它,它总是相同的结果; 没有3分钟.但是,我还发现以下方式运行得更快一点,但仍然没有C那么快:
std::ios::sync_with_stdio(false);
std::ifstream in(infile, std::ios::binary);
std::ofstream out(outfile, std::ios::binary);
out << in.rdbuf();
out.close();
in.close();
Run Code Online (Sandbox Code Playgroud)
这个花了24秒,但它仍然比C慢约20倍.
环顾四周之后,我发现有人需要写一个80GB的文件并看到他可以使用C全速写入.我决定尝试使用这段代码:
FILE *in = fopen(infile, "rb");
FILE *out = fopen(outfile, "wb");
char buf[1024];
int read = 0;
// Read data in 1kb chunks and write to output file
while ((read = fread(buf, 1, 1024, in)) == 1024)
{
fwrite(buf, 1, 1024, out);
}
// If there is any data left …Run Code Online (Sandbox Code Playgroud)