iPhone 文件损坏

发布于 2024-08-25 13:46:59 字数 271 浏览 5 评论 0原文

是否有可能(在 iPhone/iPod Touch 上)像这样编写的文件:


if (FILE* file = fopen(filename, "wb")) {
    fwrite(buf, buf_size, 1, file);
    fclose(file);
}

被损坏,例如当应用程序被迫终止时?

据我所知, fwrite 应该是一个原子操作,因此当我用一条指令写入整个文件时,不应发生损坏。我在网上找不到任何可以说明这一点的信息。

Is it possible (on iPhone/iPod Touch) for a file written like this:


if (FILE* file = fopen(filename, "wb")) {
    fwrite(buf, buf_size, 1, file);
    fclose(file);
}

to get corrupted, e.g. when app is forced to terminate?

From what I know fwrite should be an atomic operation, so when I write whole file with one instruction no corruption should occure. I could not find any information on the net that would say otherwise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

朦胧时间 2024-09-01 13:46:59

从什么时候 fwrite 成为原子的?我找不到任何参考资料。无论如何,即使 fwrite 可以是原子的,fopenfwrite 之间的时间不是,所以如果您的应用在这些时间之间被迫终止,您将得到一个空文件。

当您为 iPhoneOS 编写时,您可以使用 -[NSData writeToFile:atomically:] 来确保整个打开-写入-关闭过程是原子的(它的工作原理是写入临时文件,然后替换原来的那个。)

Since when fwrite is atomic? I can't find any references. Anyway, even if fwrite can be atomic, the time between fopen and fwrite is not, so if your app is forced to terminate between those times, you'll get an empty file.

As you're writing for iPhoneOS, you can use -[NSData writeToFile:atomically:] to ensure the whole open-write-close procedure is atomic (it works by writing to a temporary file, then replace the original one.)

夏末染殇 2024-09-01 13:46:59

您可以让事情变得更容易,并使用 NSData 类,有一个 writeToFile:atomically: 方法等待您。用 NSData 包装原始缓冲区并不难,有 dataWithBytes:length 或 dataWithBytesNoCopy:length:freeWhenDone: 初始化器。

You could make things easier for yourself and write the data using the NSData class that has a writeToFile:atomically: method waiting for you. Wrapping the raw buffer with NSData is not hard, there are the dataWithBytes:length or dataWithBytesNoCopy:length:freeWhenDone: initializers.

半山落雨半山空 2024-09-01 13:46:59

使用fwrite写入的数据被缓冲。因此突然终止可能不会刷新缓冲区。 fclose 将刷新缓冲区,但这并不意味着字节也被写入磁盘(由于操作系统级缓存)AFAIK。

Data written with fwrite is buffered. So a sudden termination might not flush the buffers. fclose will flush the buffer but this does not implicate that the bytes are also written to the disk (due to OS level caches) AFAIK.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文