Krishna Shanbhag
Krishna Shanbhag

Reputation: 1517

Reading a File Character by character in iOS

Basically i have a concern, which needs to be solved using Objective C alone. (i have tried with C)

if u feel my approach is not correct is there any other method to accomplish this task in an efficient way?

Upvotes: 3

Views: 923

Answers (2)

Basel
Basel

Reputation: 2368

Get all the lines from your file, make your changes such as replacing characters or adding more text, and then save the file.

NSString *objPath = [[NSBundle mainBundle] pathForResource:@"textfile" ofType:@"txt"];
NSData *objData = [[NSData alloc] initWithContentsOfFile:objPath];

NSString *objString = [[NSString alloc] initWithData:objData encoding:NSUTF8StringEncoding];
NSMutableArray *lines = [NSMutableArray arrayWithArray:[objString componentsSeparatedByString:@"\n"]];

for (int i = 0; i < lines.count; i++) {
    NSString *oneLine = [lines objectAtIndex:i];
    if (oneLine.length < 2) {
        continue;
    }
    oneLine = [NSString stringWithFormat:@"/%@", oneLine];
    oneLine = [oneLine stringByReplacingOccurrencesOfString:@"`" withString:@"\`"];

    [lines replaceObjectAtIndex:i withObject:oneLine];        
}
NSString *finalString = [lines componentsJoinedByString:@"\n"];
//save the file

Upvotes: 4

Stavash
Stavash

Reputation: 14304

You can use NSFileHandle and invoke readDataAtLength: with a value of 1.

Upvotes: 2

Related Questions