iPhone 文件损坏
是否有可能(在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从什么时候
fwrite
成为原子的?我找不到任何参考资料。无论如何,即使fwrite
可以是原子的,fopen
和fwrite
之间的时间不是,所以如果您的应用在这些时间之间被迫终止,您将得到一个空文件。当您为 iPhoneOS 编写时,您可以使用
-[NSData writeToFile:atomically:]
来确保整个打开-写入-关闭过程是原子的(它的工作原理是写入临时文件,然后替换原来的那个。)Since when
fwrite
is atomic? I can't find any references. Anyway, even iffwrite
can be atomic, the time betweenfopen
andfwrite
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.)您可以让事情变得更容易,并使用 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 withNSData
is not hard, there are thedataWithBytes:length
ordataWithBytesNoCopy:length:freeWhenDone:
initializers.使用
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.