blob: e45810c5b39540f1ef7ffbc7df7163cd978c3a0c [file] [log] [blame]
Benny Prijonof010e692005-11-11 19:01:31 +00001/* $Id$
2 */
3#ifndef __PJPP_FILE_HPP__
4#define __PJPP_FILE_HPP__
5
6#include <pj/file_io.h>
7#include <pj/file_access.h>
8#include <pj++/types.hpp>
9#include <pj++/pool.hpp>
10
11//
12// File API.
13//
14class Pj_File_API
15{
16public:
17 //
18 // Check file existance.
19 //
20 static bool file_exists(const char *filename)
21 {
22 return pj_file_exists(filename) != 0;
23 }
24
25 //
26 // Get file size.
27 //
28 static pj_off_t file_size(const char *filename)
29 {
30 return pj_file_size(filename);
31 }
32
33 //
34 // Delete file.
35 //
36 static pj_status_t file_delete(const char *filename)
37 {
38 return pj_file_delete(filename);
39 }
40
41 //
42 // Move/rename file.
43 //
44 static pj_status_t file_move(const char *oldname, const char *newname)
45 {
46 return pj_file_move(oldname, newname);
47 }
48
49 //
50 // Get stat.
51 //
52 static pj_status_t file_stat(const char *filename, pj_file_stat *buf)
53 {
54 return pj_file_getstat(filename, buf);
55 }
56};
57
58
59//
60// File.
61//
62class Pj_File : public Pj_Object
63{
64public:
65 //
66 // Offset type to be used in setpos.
67 //
68 enum Offset_Type
69 {
70 SEEK_SET = PJ_SEEK_SET,
71 SEEK_CUR = PJ_SEEK_CUR,
72 SEEK_END = PJ_SEEK_END,
73 };
74
75 //
76 // Default constructor.
77 //
78 Pj_File()
79 : hnd_(0)
80 {
81 }
82
83 //
84 // Construct and open a file.
85 //
86 Pj_File(Pj_Pool *pool, const char *filename,
87 unsigned access = PJ_O_RDONLY)
88 : hnd_(NULL)
89 {
90 open(pool, filename, access);
91 }
92
93 //
94 // Destructor closes the file.
95 //
96 ~Pj_File()
97 {
98 close();
99 }
100
101 //
102 // Open a file.
103 //
104 pj_status_t open(Pj_Pool *pool, const char *filename,
105 unsigned access = PJ_O_RDONLY )
106 {
107 close();
108 return pj_file_open(pool->pool_(), filename, access, &hnd_);
109 }
110
111 //
112 // Close a file.
113 //
114 void close()
115 {
116 if (hnd_ != 0) {
117 pj_file_close(hnd_);
118 hnd_ = 0;
119 }
120 }
121
122 //
123 // Write data.
124 //
125 pj_ssize_t write(const void *buff, pj_size_t size)
126 {
127 pj_ssize_t bytes = size;
128 if (pj_file_write(hnd_, buff, &bytes) != PJ_SUCCESS)
129 return -1;
130 return bytes;
131 }
132
133 //
134 // Read data.
135 //
136 pj_ssize_t read(void *buf, pj_size_t size)
137 {
138 pj_ssize_t bytes = size;
139 if (pj_file_read(hnd_, buf, &bytes) != PJ_SUCCESS)
140 return -1;
141 return bytes;
142 }
143
144 //
145 // Set file position.
146 //
147 pj_status_t setpos(pj_off_t offset, Offset_Type whence)
148 {
149 return pj_file_setpos(hnd_, offset,
150 (enum pj_file_seek_type)whence);
151 }
152
153 //
154 // Get file position.
155 //
156 pj_off_t getpos()
157 {
158 pj_off_t pos;
159 if (pj_file_getpos(hnd_, &pos) != PJ_SUCCESS)
160 return -1;
161 return pos;
162 }
163
164private:
165 pj_oshandle_t hnd_;
166};
167
168
169
170#endif /* __PJPP_FILE_HPP__ */
171