I am trying to read some input numbers from the file in objective C using NSInputStream. But unable to do so, I don't want to use readContentsFromFile api, but NSInputStream instead. Please suggest on how to do so.
Important things I am looking at :
1. How to read integers from the file.
2. How to convert the data from uint_8 [] to integer.
3. What size of data should be read at once in NSInputStream?
Example.txt file :
20 30 40 50 60 70 80 90 100 120 140 160 180 190 20 30 40 50 60 70 80 90 100 120 140 160 180 190 20 30 40 50 60 70 80 90 100 120 140 160 180 190 20 30 40 50 60 70 80 90 100 120 140 160 180 190 20 30 40 50 60 70 80 90 100 120 140 160 180 190
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Example" ofType:@"txt"];
NSInputStream *stream = [NSInputStream inputStreamWithFileAtPath:filePath];
[stream open];
for(int i = 0; i < 20; i ++)
{
if(stream && [stream hasBytesAvailable])
{
uint8_t buffer[1024];
NSUInteger len = [stream read:buffer maxLength:32];
if(len>0)
{
NSLog(@"%ld",buffer[0]);
}
else
{
....
}
}
}
You should implement NSStreamDelegate
methods to read file with NSInputStream
. This is how you should initialise your NSInputStream
instance in such case:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Example" ofType:@"txt"];
NSInputStream *stream = [NSInputStream inputStreamWithFileAtPath:filePath];
[stream setDelegate:self]; // or any other object conforming to NSStreamDelegate
[stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[stream open];
Declare the following properties in the class that you use to read file:
@interface MyClassToReadFile: NSObject<NSStreamDelegate>
@property (strong, nonatomic) NSMutableData* data;
@property (nonatomic) NSInteger bytesRead;
@end
This is how you can implement stream:handleEvent:
:
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch (eventCode) {
case NSStreamEventHasBytesAvailable: {
if(!_data) {
_data = [NSMutableData data];
}
uint8_t buf[1024]; // or any other size
NSInteger len = [(NSInputStream *)stream read:buf maxLength:sizeof(buf)/sizeof(buf[0])];
if(len) {
[_data appendBytes:(const void *)buf length:len];
_bytesRead += len;
}
break;
}
case NSStreamEventEndEncountered: {
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
NSString* fileData = [[NSString alloc] initWithData:_data encoding:NSASCIIStringEncoding];
NSArray<NSString*>* numbersAsStrings = [fileData componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
NSMutableArray<NSNumber*>* numbers = [NSMutableArray array];
for (NSString* numberAsString in numbersAsStrings) {
[numbers addObject:[NSNumber numberWithLongLong:numberAsString.longLongValue]];
}
for (NSString* numberAsString in numbersAsStrings) {
NSLog(@"%lld", numberAsString.longLongValue);
}
break;
}
default:
break;
}
}