Objective-C:逐行讀取文件在Objective-C中處理大型文本文件的適當(dāng)方法是什么?假設(shè)我需要分別讀取每一行,并希望將每一行視為NSString。這樣做最有效的方法是什么?一種解決方案是使用NSString方法:+ (id)stringWithContentsOfFile:(NSString *)path
encoding:(NSStringEncoding)enc
error:(NSError **)error然后使用換行符分隔符拆分行,然后遍歷數(shù)組中的元素。但是,這似乎效率很低。有沒(méi)有簡(jiǎn)單的方法將文件視為一個(gè)流,枚舉每一行,而不是一次只讀取它?有點(diǎn)像Java的java.io.BufferedReader。
3 回答

MMMHUHU
TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
這將一般閱讀一個(gè)工作String
的Text
。如果你想閱讀更長(zhǎng)的文本(大文本),那么使用其他人提到的方法,如緩沖(保留內(nèi)存空間中文本的大?。?/em>。
假設(shè)你讀了一個(gè)文本文件。
NSString* filePath = @""//file path...NSString* fileRoot = [[NSBundle mainBundle] pathForResource:filePath ofType:@"txt"];
你想擺脫新的路線。
// read everything from textNSString* fileContents = [NSString stringWithContentsOfFile:fileRoot encoding:NSUTF8StringEncoding error:nil];// first, separate by new lineNSArray* allLinedStrings = [fileContents componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];// then break down even further NSString* strsInOneLine = [allLinedStrings objectAtIndex:0];// choose whatever input identity you have decided. in this case ;NSArray* singleStrs = [currentPointString componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@";"]];
你有它。

慕桂英546537
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
這應(yīng)該做的伎倆:
#include <stdio.h>NSString *readLineAsNSString(FILE *file){ char buffer[4096]; // tune this capacity to your liking -- larger buffer sizes will be faster, but // use more memory NSMutableString *result = [NSMutableString stringWithCapacity:256]; // Read up to 4095 non-newline characters, then read and discard the newline int charsRead; do { if(fscanf(file, "%4095[^\n]%n%*c", buffer, &charsRead) == 1) [result appendFormat:@"%s", buffer]; else break; } while(charsRead == 4095); return result;}
使用方法如下:
FILE *file = fopen("myfile", "r");// check for NULLwhile(!feof(file)){ NSString *line = readLineAsNSString(file); // do stuff with line; line is autoreleased, so you should NOT release it (unless you also retain it beforehand)}fclose(file);
此代碼從文件中讀取非換行符,一次最多4095個(gè)。如果您的行長(zhǎng)度超過(guò)4095個(gè)字符,則會(huì)一直讀取,直到它到達(dá)換行符或文件結(jié)尾。
注意:我沒(méi)有測(cè)試過(guò)這段代碼。請(qǐng)?jiān)谑褂们斑M(jìn)行測(cè)試。
- 3 回答
- 0 關(guān)注
- 1684 瀏覽
添加回答
舉報(bào)
0/150
提交
取消