我需要创建相对较大的 (1-8 GB) 文件。使用 C 或 C++ 在 Windows 上执行此操作的最快方法是什么?我需要即时创建它们,速度确实是个问题。文件将用于存储模拟,即以不同的偏移量随机访问,我需要所有存储都将被预分配但不被初始化,目前我们正在用虚拟数据写入所有存储,这花费的时间太长了。
谢谢。
最佳答案
使用 Win32 API,CreateFile , SetFilePointerEx , SetEndOfFile , 和 CloseHandle .按照同样的顺序。
诀窍在于 SetFilePointerEx 函数。来自 MSDN:
Note that it is not an error to set the file pointer to a position beyond the end of the file. The size of the file does not increase until you call the SetEndOfFile, WriteFile, or WriteFileEx function.
当将文件从一个位置复制到另一个位置时,Windows 资源管理器实际上会做同样的事情。它这样做是为了使磁盘不需要为碎片化的磁盘重新分配文件。
关于在 Windows 上创建大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/455297/