2 // This file is (C) 2002-2003 Royce Mitchell III and released under the BSD license
5 #pragma warning ( disable : 4786 )
10 bool File::open ( const char* filename
, const char* mode
)
13 _f
= fopen ( filename
, mode
);
17 std::string
File::getline ( bool strip_crlf
/*= false*/ )
24 fgets ( buf
, sizeof(buf
)-1, _f
);
28 if ( strchr ( "\r\n", buf
[strlen(buf
)-1] ) )
33 char* p
= strpbrk ( &s
[0], "\r\n" );
43 // this function searches for the next end-of-line and puts all data it
44 // finds until then in the 'line' parameter.
46 // call continuously until the function returns false ( no more data )
47 bool File::next_line ( std::string
& line
, bool strip_crlf
)
49 line
= getline(strip_crlf
);
50 // indicate that we're done *if*:
51 // 1) there's no more data, *and*
52 // 2) we're at the end of the file
53 return line
.size()>0 || !eof();
59 bool mycallback ( const std::string& line, int line_number, long lparam )
61 std::cout << line << std::endl;
62 return true; // continue enumeration
65 File f ( "file.txt", "rb" ); // open file for binary read-only ( i.e. "rb" )
66 f.enum_lines ( mycallback, 0, true );
69 bool File::enum_lines ( bool (*callback
)(const std::string
& line
, int line_number
, long lparam
), long lparam
, bool strip_crlf
)
74 std::string s
= getline(strip_crlf
);
83 if ( !(*callback
) ( s
, line_number
, lparam
) )
91 return _filelength ( _fileno(_f
) );
93 struct stat file_stat
;
94 verify(fstat(fileno(_f
), &file_stat
) == 0);
95 return file_stat
.st_size
;
108 /*static*/ bool File::LoadIntoString ( std::string
& s
, const char* filename
)
110 File
in ( filename
, "rb" );
111 if ( !in
.isopened() )
113 size_t len
= in
.length();
114 s
.resize ( len
+ 1 );
115 if ( !in
.read ( &s
[0], len
) )
122 /*static*/ bool File::SaveFromString ( const char* filename
, const std::string
& s
, bool binary
)
124 File
out ( filename
, binary
? "wb" : "w" );
125 if ( !out
.isopened() )
127 out
.write ( s
.c_str(), s
.size() );