-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLBLReader.m
91 lines (66 loc) · 1.78 KB
/
LBLReader.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#import "LBLReader.h"
static const NSUInteger defaultBufferSize = 8*1024;
@interface LBLReader ()
@property (nonatomic, readwrite) BOOL canRead;
@property (nonatomic, readwrite) NSUInteger lineNumber;
@property (nonatomic) FILE *file;
@end
@implementation LBLReader
- (instancetype)init {
return [self initWithPath:@""];
}
- (instancetype)initWithPath:(NSString *)path {
return [self initWithPath:path bufferSize:defaultBufferSize];
}
- (instancetype)initWithPath:(NSString *)path bufferSize:(NSUInteger)bufferSize {
self = [super init];
if (self) {
_bufferSize = bufferSize;
// No initial file
_file = NULL;
// Does much more than just sets a path.
self.path = path;
}
return self;
}
- (void)setPath:(NSString *)path {
[self closeFile];
_path = path;
_lineNumber = 0;
_canRead = NO;
if (![[NSFileManager defaultManager] isReadableFileAtPath:path])
return;
_file = fopen([path UTF8String], "r");
if (_file != NULL)
_canRead = YES;
}
- (void)closeFile {
if (self.file != NULL)
fclose(self.file);
}
- (void)dealloc {
[self closeFile];
}
- (NSString *)readLine {
// Nothing to read? No line to return.
if (!self.canRead)
return nil;
NSUInteger bufferIndex = 0;
const NSUInteger bufferSize = self.bufferSize;
char buffer[bufferSize];
char ch;
while (YES) {
ch = fgetc(self.file);
// This line is the last.
if (ch == EOF)
self.canRead = NO;
if (ch == EOF || ch == '\n' || bufferIndex == bufferSize-1)
break;
buffer[bufferIndex] = ch;
bufferIndex += 1;
}
buffer[bufferIndex] = '\0';
self.lineNumber += 1;
return [NSString stringWithUTF8String:buffer];
}
@end