只读“N”字节从Cocoa中的文件 [英] Read only "N" bytes from a file in Cocoa

查看:107
本文介绍了只读“N”字节从Cocoa中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何读取指定文件中的N个字节?

How to read only "N" bytes from a specified file?

推荐答案

该文件的方式类似于通过NSData加载它,但没有实际读取的内容,你可以使用内存映射。这样做意味着磁盘上的文件将被视为虚拟内存的一部分,并像普通虚拟内存一样被分页和分页。

If you want random access to the contents of the file in a manner similar to having loaded it via NSData but without actually reading everything into memory, you can use memory mapping. Doing so means that the file on disk becomes treated as a section of virtual memory, and will be paged in and out just like regular virtual memory.

NSError * error = nil;
NSData * theData = [NSData dataWithContentsOfFile: thePath
                                          options: NSMappedRead
                                            error: &error];

如果您不关心获取文件系统错误详细信息,可以使用:

If you don't care about getting filesystem error details, you can just use:

NSData * theData = [NSData dataWithContentsOfMappedFile: thePath];

然后你只需要使用NSData的 -getBytes:range:方法拉出特定的数据,只有文件的相关部分才会从永久存储中读取;他们也将有资格被分页。

Then you would just use NSData's -getBytes:range: method to pull out specific pieces of data, and only the relevant parts of the file will actually be read from permanent storage; they'll also be eligible to be paged out too.

这篇关于只读“N”字节从Cocoa中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆