1 // File.h
2 // This file is (C) 2002-2003 Royce Mitchell III and released under the BSD license
3 
4 #ifndef FILE_H
5 #define FILE_H
6 
7 #ifdef WIN32
8 #  include <io.h>
9 #elif defined(UNIX)
10 #  include <sys/stat.h>
11 #  include <unistd.h>
12 #endif
13 #include <string>
14 
15 class File
16 {
17 public:
File()18 	File() : _f(0)
19 	{
20 	}
21 
File(const char * filename,const char * mode)22 	File ( const char* filename, const char* mode ) : _f(0)
23 	{
24 		open ( filename, mode );
25 	}
26 
~File()27 	~File()
28 	{
29 		close();
30 	}
31 
32 	bool open ( const char* filename, const char* mode );
33 
seek(long offset)34 	bool seek ( long offset )
35 	{
36 		return !fseek ( _f, offset, SEEK_SET );
37 	}
38 
get()39 	int get()
40 	{
41 		return fgetc ( _f );
42 	}
43 
put(int c)44 	bool put ( int c )
45 	{
46 		return fputc ( c, _f ) != EOF;
47 	}
48 
49 	std::string getline ( bool strip_crlf = false );
50 
51 	// this function searches for the next end-of-line and puts all data it
52 	// finds until then in the 'line' parameter.
53 	//
54 	// call continuously until the function returns false ( no more data )
55 	bool next_line ( std::string& line, bool strip_crlf );
56 
57 	/*
58 	example usage:
59 
60 	bool mycallback ( const std::string& line, int line_number, long lparam )
61 	{
62 		std::cout << line << std::endl;
63 		return true; // continue enumeration
64 	}
65 
66 	File f ( "file.txt", "rb" ); // open file for binary read-only ( i.e. "rb" )
67 	f.enum_lines ( mycallback, 0, true );
68 	*/
69 
70 	bool enum_lines ( bool (*callback)(const std::string& line, int line_number, long lparam), long lparam, bool strip_crlf );
71 
read(void * data,unsigned len)72 	bool read ( void* data, unsigned len )
73 	{
74 		return len == fread ( data, 1, len, _f );
75 	}
76 
write(const void * data,unsigned len)77 	bool write ( const void* data, unsigned len )
78 	{
79 		return len == fwrite ( data, 1, len, _f );
80 	}
81 
82 	size_t length();
83 
84 	void close();
85 
isopened()86 	bool isopened()
87 	{
88 		return _f != 0;
89 	}
90 
eof()91 	bool eof()
92 	{
93 		return feof(_f) ? true : false;
94 	}
95 
96 	FILE* operator * ()
97 	{
98 		return _f;
99 	}
100 
101 	static bool LoadIntoString ( std::string& s, const char* filename );
102 	static bool SaveFromString ( const char* filename, const std::string& s, bool binary );
103 
104 private:
File(const File &)105 	File(const File&) {}
106 	const File& operator = ( const File& ) { return *this; }
107 
108 	FILE * _f;
109 };
110 
111 #endif//FILE_H
112