]> git.saurik.com Git - wxWidgets.git/blob - src/common/file.cpp
-somewhat more elegant method, supporting the src subdir (-Markus)
[wxWidgets.git] / src / common / file.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: file.cpp
3 // Purpose: wxFile - encapsulates low-level "file descriptor"
4 // wxTempFile
5 // Author: Vadim Zeitlin
6 // Modified by:
7 // Created: 29/01/98
8 // RCS-ID: $Id$
9 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
12
13 // ----------------------------------------------------------------------------
14 // headers
15 // ----------------------------------------------------------------------------
16
17 #ifdef __GNUG__
18 #pragma implementation "file.h"
19 #endif
20
21 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
23 #include "wx/defs.h"
24
25 #ifdef __BORLANDC__
26 #pragma hdrstop
27 #endif
28
29 // standard
30 #if defined(__WXMSW__) && !defined(__GNUWIN32__)
31 #include <io.h>
32
33 #define WIN32_LEAN_AND_MEAN
34 #define NOSERVICE
35 #define NOIME
36 #define NOATOM
37 #define NOGDI
38 #define NOGDICAPMASKS
39 #define NOMETAFILE
40 #define NOMINMAX
41 #define NOMSG
42 #define NOOPENFILE
43 #define NORASTEROPS
44 #define NOSCROLL
45 #define NOSOUND
46 #define NOSYSMETRICS
47 #define NOTEXTMETRIC
48 #define NOWH
49 #define NOCOMM
50 #define NOKANJI
51 #define NOCRYPT
52 #define NOMCX
53 #include <windows.h> // for GetTempFileName
54 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
55 #include <unistd.h>
56 #else
57 #error "Please specify the header with file functions declarations."
58 #endif //Win/UNIX
59
60 #include <stdio.h> // SEEK_xxx constants
61 #include <fcntl.h> // O_RDONLY &c
62 #include <sys/types.h> // needed for stat
63 #include <sys/stat.h> // stat
64
65 // Microsoft compiler loves underscores, feed them to it
66 #ifdef _MSC_VER
67 // functions
68 #define open _open
69 #define close _close
70 #define read _read
71 #define write _write
72 #define lseek _lseek
73 #define fsync _commit
74 #define access _access
75 #define eof _eof
76
77 // types
78 #define stat _stat
79
80 // constants
81 #define O_RDONLY _O_RDONLY
82 #define O_WRONLY _O_WRONLY
83 #define O_RDWR _O_RDWR
84 #define O_EXCL _O_EXCL
85 #define O_CREAT _O_CREAT
86 #define O_BINARY _O_BINARY
87
88 #define S_IFDIR _S_IFDIR
89 #define S_IFREG _S_IFREG
90
91 #define W_OK 2
92 #define R_OK 4
93 #else
94 #define tell(fd) lseek(fd, 0, SEEK_CUR)
95 #endif //_MSC_VER
96
97 // there is no distinction between text and binary files under Unix
98 #ifdef __UNIX__
99 #define O_BINARY (0)
100 #endif //__UNIX__
101
102 // wxWindows
103 #include <wx/string.h>
104 #include <wx/intl.h>
105 #include <wx/file.h>
106 #include <wx/log.h>
107
108 #ifndef MAX_PATH
109 #define MAX_PATH 512
110 #endif
111
112 // ============================================================================
113 // implementation of wxFile
114 // ============================================================================
115
116 // ----------------------------------------------------------------------------
117 // static functions
118 // ----------------------------------------------------------------------------
119 bool wxFile::Exists(const char *name)
120 {
121 struct stat st;
122 return !access(name, 0) && !stat(name, &st) && (st.st_mode & S_IFREG);
123 }
124
125 bool wxFile::Access(const char *name, OpenMode mode)
126 {
127 int how;
128
129 switch ( mode ) {
130 case read:
131 how = R_OK;
132 break;
133
134 case write:
135 how = W_OK;
136 break;
137
138 default:
139 wxFAIL_MSG("bad wxFile::Access mode parameter.");
140 }
141
142 return access(name, how) == 0;
143 }
144
145 // ----------------------------------------------------------------------------
146 // opening/closing
147 // ----------------------------------------------------------------------------
148
149 // ctors
150 wxFile::wxFile(const char *szFileName, OpenMode mode)
151 {
152 m_fd = fd_invalid;
153 m_error = FALSE;
154
155 Open(szFileName, mode);
156 }
157
158 // dtor
159 wxFile::~wxFile()
160 {
161 Close();
162 }
163
164 // create the file, fail if it already exists and bOverwrite
165 bool wxFile::Create(const char *szFileName, bool bOverwrite, int access)
166 {
167 // if bOverwrite we create a new file or truncate the existing one,
168 // otherwise we only create the new file and fail if it already exists
169 int fd = open(szFileName, O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
170
171 if ( fd == -1 ) {
172 wxLogSysError(_("can't create file '%s'"), szFileName);
173 return FALSE;
174 }
175 else {
176 Attach(fd);
177 return TRUE;
178 }
179 }
180
181 // open the file
182 bool wxFile::Open(const char *szFileName, OpenMode mode, int access)
183 {
184 int flags = O_BINARY;
185
186 switch ( mode ) {
187 case read:
188 flags |= O_RDONLY;
189 break;
190
191 case write:
192 flags |= O_WRONLY | O_CREAT | O_TRUNC;
193 break;
194
195 case write_append:
196 flags |= O_WRONLY | O_APPEND;
197 break;
198
199 case read_write:
200 flags |= O_RDWR;
201 break;
202 }
203
204 int fd = open(szFileName, flags, access);
205
206 if ( fd == -1 ) {
207 wxLogSysError(_("can't open file '%s'"), szFileName);
208 return FALSE;
209 }
210 else {
211 Attach(fd);
212 return TRUE;
213 }
214 }
215
216 // close
217 bool wxFile::Close()
218 {
219 if ( IsOpened() ) {
220 if ( close(m_fd) == -1 ) {
221 wxLogSysError(_("can't close file descriptor %d"), m_fd);
222 m_fd = fd_invalid;
223 return FALSE;
224 }
225 else
226 m_fd = fd_invalid;
227 }
228
229 return TRUE;
230 }
231
232 // ----------------------------------------------------------------------------
233 // read/write
234 // ----------------------------------------------------------------------------
235
236 // read
237 off_t wxFile::Read(void *pBuf, off_t nCount)
238 {
239 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
240
241 int iRc = ::read(m_fd, pBuf, nCount);
242 if ( iRc == -1 ) {
243 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
244 return wxInvalidOffset;
245 }
246 else
247 return (uint)iRc;
248 }
249
250 // write
251 uint wxFile::Write(const void *pBuf, uint nCount)
252 {
253 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
254
255 int iRc = ::write(m_fd, pBuf, nCount);
256 if ( iRc == -1 ) {
257 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
258 m_error = TRUE;
259 return 0;
260 }
261 else
262 return iRc;
263 }
264
265 // flush
266 bool wxFile::Flush()
267 {
268 if ( IsOpened() ) {
269 // @@@ fsync() is not ANSI (BSDish)
270 // if ( fsync(m_fd) == -1 ) { // TODO
271 if (TRUE) {
272 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
273 return FALSE;
274 }
275 }
276
277 return TRUE;
278 }
279
280 // ----------------------------------------------------------------------------
281 // seek
282 // ----------------------------------------------------------------------------
283
284 // seek
285 off_t wxFile::Seek(off_t ofs, wxSeekMode mode)
286 {
287 wxASSERT( IsOpened() );
288
289 int flag = -1;
290 switch ( mode ) {
291 case wxFromStart:
292 flag = SEEK_SET;
293 break;
294
295 case wxFromCurrent:
296 flag = SEEK_CUR;
297 break;
298
299 case wxFromEnd:
300 flag = SEEK_END;
301 break;
302
303 default:
304 wxFAIL_MSG(_("unknown seek origin"));
305 }
306
307 int iRc = lseek(m_fd, ofs, flag);
308 if ( iRc == -1 ) {
309 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
310 return wxInvalidOffset;
311 }
312 else
313 return (off_t)iRc;
314 }
315
316 // get current off_t
317 off_t wxFile::Tell() const
318 {
319 wxASSERT( IsOpened() );
320
321 int iRc = tell(m_fd);
322 if ( iRc == -1 ) {
323 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
324 return wxInvalidOffset;
325 }
326 else
327 return (off_t)iRc;
328 }
329
330 // get current file length
331 off_t wxFile::Length() const
332 {
333 wxASSERT( IsOpened() );
334
335 #ifdef _MSC_VER
336 int iRc = _filelength(m_fd);
337 #else
338 int iRc = tell(m_fd);
339 if ( iRc != -1 ) {
340 // @ have to use const_cast :-(
341 int iLen = ((wxFile *)this)->SeekEnd();
342 if ( iLen != -1 ) {
343 // restore old position
344 if ( ((wxFile *)this)->Seek(iRc) == -1 ) {
345 // error
346 iLen = -1;
347 }
348 }
349
350 iRc = iLen;
351 }
352
353 #endif //_MSC_VER
354
355 if ( iRc == -1 ) {
356 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
357 return wxInvalidOffset;
358 }
359 else
360 return (off_t)iRc;
361 }
362
363 // is end of file reached?
364 bool wxFile::Eof() const
365 {
366 wxASSERT( IsOpened() );
367
368 int iRc;
369
370 #if defined(__UNIX__) || defined(__GNUWIN32__)
371 // @@ this doesn't work, of course, on unseekable file descriptors
372 off_t ofsCur = Tell(),
373 ofsMax = Length();
374 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
375 iRc = -1;
376 else
377 iRc = ofsCur == ofsMax;
378 #else // Windows and "native" compiler
379 iRc = eof(m_fd);
380 #endif // Windows/Unix
381
382 switch ( iRc ) {
383 case 1:
384 break;
385
386 case 0:
387 return FALSE;
388
389 case -1:
390 wxLogSysError(_("can't determine if the end of file is reached on \
391 descriptor %d"), m_fd);
392 break;
393
394 default:
395 wxFAIL_MSG(_("invalid eof() return value."));
396 }
397
398 return TRUE;
399 }
400
401 // ============================================================================
402 // implementation of wxTempFile
403 // ============================================================================
404
405 // ----------------------------------------------------------------------------
406 // construction
407 // ----------------------------------------------------------------------------
408 wxTempFile::wxTempFile(const wxString& strName)
409 {
410 Open(strName);
411 }
412
413 bool wxTempFile::Open(const wxString& strName)
414 {
415 m_strName = strName;
416
417 // we want to create the file in the same directory as strName because
418 // otherwise rename() in Commit() might not work (if the files are on
419 // different partitions for example). Unfortunately, the only standard
420 // (POSIX) temp file creation function tmpnam() can't do it.
421 #ifdef __UNIX__
422 static const char *szMktempSuffix = "XXXXXX";
423 m_strTemp << strName << szMktempSuffix;
424 mktemp((char *)m_strTemp.c_str()); // will do because length doesn't change
425 #else // Windows
426 wxString strPath;
427 wxSplitPath(strName, &strPath, NULL, NULL);
428 if ( strPath.IsEmpty() )
429 strPath = '.'; // GetTempFileName will fail if we give it empty string
430 #ifdef __WIN32__
431 if ( !GetTempFileName(strPath, "wx_",0, m_strTemp.GetWriteBuf(MAX_PATH)) )
432 #else
433 // Not sure why MSVC++ 1.5 header defines first param as BYTE - bug?
434 if ( !GetTempFileName((BYTE) (const char*) strPath, "wx_",0, m_strTemp.GetWriteBuf(MAX_PATH)) )
435 #endif
436 wxLogLastError("GetTempFileName");
437 m_strTemp.UngetWriteBuf();
438 #endif // Windows/Unix
439
440 return m_file.Open(m_strTemp, wxFile::write);
441 }
442
443 // ----------------------------------------------------------------------------
444 // destruction
445 // ----------------------------------------------------------------------------
446
447 wxTempFile::~wxTempFile()
448 {
449 if ( IsOpened() )
450 Discard();
451 }
452
453 bool wxTempFile::Commit()
454 {
455 m_file.Close();
456
457 if ( wxFile::Exists(m_strName) && remove(m_strName) != 0 ) {
458 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
459 return FALSE;
460 }
461
462 if ( rename(m_strTemp, m_strName) != 0 ) {
463 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
464 return FALSE;
465 }
466
467 return TRUE;
468 }
469
470 void wxTempFile::Discard()
471 {
472 m_file.Close();
473 if ( remove(m_strTemp) != 0 )
474 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
475 }