1

I need to copy a file that will be modified later on an iOS device. For performance reasons, it would be great if this would work copy-on-write, i.e. the file is not really duplicated, and only modified blocks of the copy are written later.

As pointed out in the comments, this probably has to be supported by the file system (HFS+?). A link is not sufficient, since both the old (A) and new (B) file name will point to the same file, and if I modify A, B will also change.

A "lazy" copy also would not help, since on first write the whole file would still need to be copied.

I was thinking more about a solution like the one described by @Hot Licks that would start with A and B using the same blocks on disk, and when I write to file B, only the modified blocks would be stored on disk, while identical parts in A and B go on using the same blocks on disk.

Is this possible on iOS?

Regards, Jochen

4

1 回答 1

0

没有内置机制可以有效地进行文件的部分复制,但是如果您要复制文件并对内容进行内部更改,那么最有效的机制就是 mmap。您将文件映射到内存并就地修改它。更改会自动写回文件,而无需分段重写文件。

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>

struct stat astat;
int fd = open("filename", O_RDWR);
if ((fd != -1) && (fstat(fd, &astat) != -1)) {
    char *data = mmap(0, astat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (data != MAP_FAILED) {
        self.data_ptr = data;
        self.data_size = astat.st_size;
    }
    close(fd);
}

完成文件后,使用 munmap 将映射释放回操作系统:

munmap(self.data_ptr, self.data_size);

通常的警告适用于修改共享资源。

于 2013-01-09T15:35:15.950 回答