-
Notifications
You must be signed in to change notification settings - Fork 49
/
FileLineReader.hpp
97 lines (86 loc) · 1.38 KB
/
FileLineReader.hpp
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
92
93
94
95
96
97
// The class that read a line froma file
// Does not store the change line symbol
//
#ifndef _MOURISL_FILELINEREADER
#define _MOURISL_FILELINEREADER
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class FileLineReader
{
private:
FILE *fp ;
char c ;
char *buffer ;
int bufferSize ;
char delimit ;
public:
FileLineReader()
{
fp = NULL ;
bufferSize = 1000 ;
buffer = (char *)malloc(sizeof(char) * bufferSize) ;
buffer[0] = '\0' ;
delimit = '\n' ;
}
~FileLineReader()
{
if (fp != NULL)
fclose(fp) ;
if (buffer != NULL)
free(buffer) ;
}
int Open(const char *filename)
{
fp = fopen(filename, "r") ;
if (fp == NULL)
return 0 ;
return 1 ;
}
int IsOpen()
{
if (fp == NULL)
return 0 ;
return 1 ;
}
void Close()
{
if (fp != NULL)
fclose(fp) ;
fp = NULL ;
}
const char *ReadLine()
{
if (feof(fp))
return NULL ;
int len = 0 ;
while ((c = fgetc(fp)) != (char)EOF)
{
buffer[len] = c ;
++len ;
if (len >= bufferSize - 1) // not place to hold \0
{
bufferSize *= 2 ;
buffer = (char *)realloc(buffer, sizeof(char) * bufferSize) ;
}
if (c == delimit)
{
--len ;
break ;
}
}
buffer[len] = '\0' ;
if (len == 0 && feof(fp))
return NULL ;
return GetLinePtr() ;
}
const char *GetLinePtr()
{
return (const char*)buffer ;
}
FILE *GetFP()
{
return (FILE*)fp ;
}
} ;
#endif