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