根据这个问题(部分截断流),您应该能够在符合 POSIX 的系统上使用调用int ftruncate(int fildes, off_t length)
来调整现有文件的大小。
现代实现可能会“就地”调整文件的大小(尽管在文档中未指定)。唯一的问题是您可能需要做一些额外的工作来确保它off_t
是 64 位类型(POSIX 标准中存在 32 位off_t
类型的规定)。
您应该采取措施处理错误情况,以防万一它由于某种原因失败,因为显然,任何严重的失败都可能导致您的 100GB 文件丢失。
伪代码(假设并采取措施确保所有数据类型都足够大以避免溢出):
open (string filename) // opens a file, returns a file descriptor
file_size (descriptor file) // returns the absolute size of the specified file
seek (descriptor file, position p) // moves the caret to specified absolute point
copy_to_new_file (descriptor file, string newname)
// creates file specified by newname, copies data from specified file descriptor
// into newfile until EOF is reached
set descriptor = open ("MyHugeFile")
set gigabyte = 2^30 // 1024 * 1024 * 1024 bytes
set filesize = file_size(descriptor)
set blocks = (filesize + gigabyte - 1) / gigabyte
loop (i = blocks; i > 0; --i)
set truncpos = gigabyte * (i - 1)
seek (descriptor, truncpos)
copy_to_new_file (descriptor, "MyHugeFile" + i))
ftruncate (descriptor, truncpos)
显然,其中一些伪代码类似于标准库中的函数。在其他情况下,您将不得不自己编写。