Read only “N” bytes from a file in Cocoa

血红的双手。 提交于 2019-12-03 05:02:56

问题


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


回答1:


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];

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.




回答2:


-[NSFileHandle readDataOfLength:].

NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *fileData = [handle readDataOfLength:N];
[handle closeFile];



回答3:


If you want to avoid reading the entire file, you can just use the standard C I/O functions:

#include <stdio.h>
...
FILE *file = fopen("the-file.dat", "rb");
if(file == NULL)
    ; // handle error
char theBuffer[1000];  // make sure this is big enough!!
size_t bytesRead = fread(theBuffer, 1, 1000, file);
if(bytesRead < 1000)
    ; // handle error
fclose(file);



回答4:


Open the file:

NSData *fileData = [NSData dataWithContentsOfFile:fileName];

Read the bytes you want:

int bytes[1000];
[fileData getBytes:bytes length:sizeof(int) * 1000];


来源:https://stackoverflow.com/questions/936020/read-only-n-bytes-from-a-file-in-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!