如何快速在iOS中创建大文件?

问题描述:

我需要能够快速创建一个大的虚拟文件(大约1 GB)。我目前正在循环一个字节数组并将其附加到文件,但这可能导致单独的磁盘命中:

I need to be able to create a large "dummy" file (around 1 GB) quickly. I am currently looping over a byte array and appending it to the file, but this results in may separate disk hits:

NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.path];
[handle seekToEndOfFile];

while (shouldContinue)
{
     NSData *dummyData = [self buildDummyData];
     [handle writeData:dummyData];
}

但这需要大约7秒才能完成。我希望它在不到1秒钟内完成。有没有办法创建文件并分配其大小而无需向其追加字节?

But this takes around 7 seconds to complete. I would like it to complete in less than 1 second. Is there a way to create a file and allocate its size without needing to append bytes to it?

您可以使用 truncate 直接设置文件的长度:

You can use truncate to set the length of a file directly:

int success = truncate("/path/to/file", 1024 * 1024 * 1024);
if (success != 0) {
    int error = errno;
    /* handle errors here. See 'man truncate' */
}