]> git.saurik.com Git - wxWidgets.git/blob - src/common/file.cpp
safeguards against crashes
[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
24 #ifdef __BORLANDC__
25 #pragma hdrstop
26 #endif
27
28 #if wxUSE_FILE
29
30 // standard
31 #if defined(__WXMSW__) && !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
32 #include <io.h>
33
34 #ifndef __SALFORDC__
35 #define WIN32_LEAN_AND_MEAN
36 #define NOSERVICE
37 #define NOIME
38 #define NOATOM
39 #define NOGDI
40 #define NOGDICAPMASKS
41 #define NOMETAFILE
42 #define NOMINMAX
43 #define NOMSG
44 #define NOOPENFILE
45 #define NORASTEROPS
46 #define NOSCROLL
47 #define NOSOUND
48 #define NOSYSMETRICS
49 #define NOTEXTMETRIC
50 #define NOWH
51 #define NOCOMM
52 #define NOKANJI
53 #define NOCRYPT
54 #define NOMCX
55 #endif
56
57 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
58 #include <unistd.h>
59 #ifdef __GNUWIN32__
60 #include <windows.h>
61 #endif
62 #elif defined(__DOS__)
63 #if defined(__WATCOMC__)
64 #include <io.h>
65 #elif defined(__DJGPP__)
66 #include <io.h>
67 #include <unistd.h>
68 #include <stdio.h>
69 #else
70 #error "Please specify the header with file functions declarations."
71 #endif
72 #elif (defined(__WXPM__))
73 #include <io.h>
74 #define W_OK 2
75 #define R_OK 4
76 #elif (defined(__WXSTUBS__))
77 // Have to ifdef this for different environments
78 #include <io.h>
79 #elif (defined(__WXMAC__))
80 #if __MSL__ < 0x6000
81 int access( const char *path, int mode ) { return 0 ; }
82 #else
83 int _access( const char *path, int mode ) { return 0 ; }
84 #endif
85 char* mktemp( char * path ) { return path ;}
86 #include <stat.h>
87 #define W_OK 2
88 #define R_OK 4
89 #include <unistd.h>
90 #else
91 #error "Please specify the header with file functions declarations."
92 #endif //Win/UNIX
93
94 #include <stdio.h> // SEEK_xxx constants
95 #include <fcntl.h> // O_RDONLY &c
96
97 #ifndef __MWERKS__
98 #include <sys/types.h> // needed for stat
99 #include <sys/stat.h> // stat
100 #elif ( defined(__MWERKS__) && defined(__WXMSW__) )
101 #include <sys/types.h> // needed for stat
102 #include <sys/stat.h> // stat
103 #endif
104
105 #if defined(__BORLANDC__) || defined(_MSC_VER)
106 #define W_OK 2
107 #define R_OK 4
108 #endif
109
110 // there is no distinction between text and binary files under Unix, so define
111 // O_BINARY as 0 if the system headers don't do it already
112 #if defined(__UNIX__) && !defined(O_BINARY)
113 #define O_BINARY (0)
114 #endif //__UNIX__
115
116 #ifdef __SALFORDC__
117 #include <unix.h>
118 #endif
119
120 #ifndef MAX_PATH
121 #define MAX_PATH 512
122 #endif
123
124 // some broken compilers don't have 3rd argument in open() and creat()
125 #ifdef __SALFORDC__
126 #define ACCESS(access)
127 #define stat _stat
128 #else // normal compiler
129 #define ACCESS(access) , (access)
130 #endif // Salford C
131
132 // wxWindows
133 #ifndef WX_PRECOMP
134 #include "wx/string.h"
135 #include "wx/intl.h"
136 #include "wx/log.h"
137 #endif // !WX_PRECOMP
138
139 #include "wx/filename.h"
140 #include "wx/file.h"
141
142 // ============================================================================
143 // implementation of wxFile
144 // ============================================================================
145
146 // ----------------------------------------------------------------------------
147 // static functions
148 // ----------------------------------------------------------------------------
149 bool wxFile::Exists(const wxChar *name)
150 {
151 wxStructStat st;
152 #if wxUSE_UNICODE && wxMBFILES
153 wxCharBuffer fname = wxConvFile.cWC2MB(name);
154
155 return !wxAccess(fname, 0) &&
156 !wxStat(wxMBSTRINGCAST fname, &st) &&
157 (st.st_mode & S_IFREG);
158
159 #else
160 return !wxAccess(name, 0) &&
161 !wxStat(name, &st) &&
162 (st.st_mode & S_IFREG);
163 #endif
164 }
165
166 bool wxFile::Access(const wxChar *name, OpenMode mode)
167 {
168 int how = 0;
169
170 switch ( mode ) {
171 case read:
172 how = R_OK;
173 break;
174
175 case write:
176 how = W_OK;
177 break;
178
179 default:
180 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
181 }
182
183 return wxAccess(wxFNCONV(name), how) == 0;
184 }
185
186 // ----------------------------------------------------------------------------
187 // opening/closing
188 // ----------------------------------------------------------------------------
189
190 // ctors
191 wxFile::wxFile(const wxChar *szFileName, OpenMode mode)
192 {
193 m_fd = fd_invalid;
194 m_error = FALSE;
195
196 Open(szFileName, mode);
197 }
198
199 // create the file, fail if it already exists and bOverwrite
200 bool wxFile::Create(const wxChar *szFileName, bool bOverwrite, int accessMode)
201 {
202 // if bOverwrite we create a new file or truncate the existing one,
203 // otherwise we only create the new file and fail if it already exists
204 #if defined(__WXMAC__) && !defined(__UNIX__)
205 // Dominic Mazzoni [dmazzoni+@cs.cmu.edu] reports that open is still broken on the mac, so we replace
206 // int fd = open(wxUnix2MacFilename( szFileName ), O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
207 int fd = creat( szFileName , accessMode);
208 #else
209 int fd = wxOpen(wxFNCONV(szFileName),
210 O_BINARY | O_WRONLY | O_CREAT |
211 (bOverwrite ? O_TRUNC : O_EXCL)
212 ACCESS(accessMode));
213 #endif
214 if ( fd == -1 ) {
215 wxLogSysError(_("can't create file '%s'"), szFileName);
216 return FALSE;
217 }
218 else {
219 Attach(fd);
220 return TRUE;
221 }
222 }
223
224 // open the file
225 bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
226 {
227 int flags = O_BINARY;
228
229 switch ( mode ) {
230 case read:
231 flags |= O_RDONLY;
232 break;
233
234 case write_append:
235 if ( wxFile::Exists(szFileName) )
236 {
237 flags |= O_WRONLY | O_APPEND;
238 break;
239 }
240 //else: fall through as write_append is the same as write if the
241 // file doesn't exist
242
243 case write:
244 flags |= O_WRONLY | O_CREAT | O_TRUNC;
245 break;
246
247 case write_excl:
248 flags |= O_WRONLY | O_CREAT | O_EXCL;
249 break;
250
251 case read_write:
252 flags |= O_RDWR;
253 break;
254 }
255
256 int fd = wxOpen(wxFNCONV(szFileName), flags ACCESS(accessMode));
257 if ( fd == -1 ) {
258 wxLogSysError(_("can't open file '%s'"), szFileName);
259 return FALSE;
260 }
261 else {
262 Attach(fd);
263 return TRUE;
264 }
265 }
266
267 // close
268 bool wxFile::Close()
269 {
270 if ( IsOpened() ) {
271 if ( close(m_fd) == -1 ) {
272 wxLogSysError(_("can't close file descriptor %d"), m_fd);
273 m_fd = fd_invalid;
274 return FALSE;
275 }
276 else
277 m_fd = fd_invalid;
278 }
279
280 return TRUE;
281 }
282
283 // ----------------------------------------------------------------------------
284 // read/write
285 // ----------------------------------------------------------------------------
286
287 // read
288 off_t wxFile::Read(void *pBuf, off_t nCount)
289 {
290 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
291
292 #ifdef __MWERKS__
293 int iRc = ::read(m_fd, (char*) pBuf, nCount);
294 #else
295 int iRc = ::read(m_fd, pBuf, nCount);
296 #endif
297 if ( iRc == -1 ) {
298 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
299 return wxInvalidOffset;
300 }
301 else
302 return (size_t)iRc;
303 }
304
305 // write
306 size_t wxFile::Write(const void *pBuf, size_t nCount)
307 {
308 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
309
310 #ifdef __MWERKS__
311 #if __MSL__ >= 0x6000
312 int iRc = ::write(m_fd, (void*) pBuf, nCount);
313 #else
314 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
315 #endif
316 #else
317 int iRc = ::write(m_fd, pBuf, nCount);
318 #endif
319 if ( iRc == -1 ) {
320 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
321 m_error = TRUE;
322 return 0;
323 }
324 else
325 return iRc;
326 }
327
328 // flush
329 bool wxFile::Flush()
330 {
331 if ( IsOpened() ) {
332 #if defined(__VISUALC__) || wxHAVE_FSYNC
333 if ( wxFsync(m_fd) == -1 )
334 {
335 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
336 return FALSE;
337 }
338 #else // no fsync
339 // just do nothing
340 #endif // fsync
341 }
342
343 return TRUE;
344 }
345
346 // ----------------------------------------------------------------------------
347 // seek
348 // ----------------------------------------------------------------------------
349
350 // seek
351 off_t wxFile::Seek(off_t ofs, wxSeekMode mode)
352 {
353 wxASSERT( IsOpened() );
354
355 int origin;
356 switch ( mode ) {
357 default:
358 wxFAIL_MSG(_("unknown seek origin"));
359
360 case wxFromStart:
361 origin = SEEK_SET;
362 break;
363
364 case wxFromCurrent:
365 origin = SEEK_CUR;
366 break;
367
368 case wxFromEnd:
369 origin = SEEK_END;
370 break;
371 }
372
373 int iRc = lseek(m_fd, ofs, origin);
374 if ( iRc == -1 ) {
375 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
376 return wxInvalidOffset;
377 }
378 else
379 return (off_t)iRc;
380 }
381
382 // get current off_t
383 off_t wxFile::Tell() const
384 {
385 wxASSERT( IsOpened() );
386
387 int iRc = wxTell(m_fd);
388 if ( iRc == -1 ) {
389 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
390 return wxInvalidOffset;
391 }
392 else
393 return (off_t)iRc;
394 }
395
396 // get current file length
397 off_t wxFile::Length() const
398 {
399 wxASSERT( IsOpened() );
400
401 #ifdef __VISUALC__
402 int iRc = _filelength(m_fd);
403 #else // !VC++
404 int iRc = wxTell(m_fd);
405 if ( iRc != -1 ) {
406 // @ have to use const_cast :-(
407 int iLen = ((wxFile *)this)->SeekEnd();
408 if ( iLen != -1 ) {
409 // restore old position
410 if ( ((wxFile *)this)->Seek(iRc) == -1 ) {
411 // error
412 iLen = -1;
413 }
414 }
415
416 iRc = iLen;
417 }
418 #endif // VC++
419
420 if ( iRc == -1 ) {
421 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
422 return wxInvalidOffset;
423 }
424 else
425 return (off_t)iRc;
426 }
427
428 // is end of file reached?
429 bool wxFile::Eof() const
430 {
431 wxASSERT( IsOpened() );
432
433 int iRc;
434
435 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
436 // @@ this doesn't work, of course, on unseekable file descriptors
437 off_t ofsCur = Tell(),
438 ofsMax = Length();
439 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
440 iRc = -1;
441 else
442 iRc = ofsCur == ofsMax;
443 #else // Windows and "native" compiler
444 iRc = eof(m_fd);
445 #endif // Windows/Unix
446
447 switch ( iRc ) {
448 case 1:
449 break;
450
451 case 0:
452 return FALSE;
453
454 case -1:
455 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
456 break;
457
458 default:
459 wxFAIL_MSG(_("invalid eof() return value."));
460 }
461
462 return TRUE;
463 }
464
465 // ============================================================================
466 // implementation of wxTempFile
467 // ============================================================================
468
469 // ----------------------------------------------------------------------------
470 // construction
471 // ----------------------------------------------------------------------------
472
473 wxTempFile::wxTempFile(const wxString& strName)
474 {
475 Open(strName);
476 }
477
478 bool wxTempFile::Open(const wxString& strName)
479 {
480 // we must have an absolute filename because otherwise CreateTempFileName()
481 // would create the temp file in $TMP (i.e. the system standard location
482 // for the temp files) which might be on another volume/drive/mount and
483 // wxRename()ing it later to m_strName from Commit() would then fail
484 //
485 // with the absolute filename, the temp file is created in the same
486 // directory as this one which ensures that wxRename() may work later
487 wxFileName fn(strName);
488 if ( !fn.IsAbsolute() )
489 {
490 fn.Normalize(wxPATH_NORM_ABSOLUTE);
491 }
492
493 m_strName = fn.GetFullPath();
494
495 m_strTemp = wxFileName::CreateTempFileName(m_strName, &m_file);
496
497 if ( m_strTemp.empty() )
498 {
499 // CreateTempFileName() failed
500 return FALSE;
501 }
502
503 #ifdef __UNIX__
504 // the temp file should have the same permissions as the original one
505 mode_t mode;
506
507 wxStructStat st;
508 if ( stat(m_strName.fn_str(), &st) == 0 )
509 {
510 mode = st.st_mode;
511 }
512 else
513 {
514 // file probably didn't exist, just give it the default mode _using_
515 // user's umask (new files creation should respect umask)
516 mode_t mask = umask(0777);
517 mode = 0666 & ~mask;
518 umask(mask);
519 }
520
521 if ( chmod(m_strTemp.mb_str(), mode) == -1 )
522 {
523 wxLogSysError(_("Failed to set temporary file permissions"));
524 }
525 #endif // Unix
526
527 return TRUE;
528 }
529
530 // ----------------------------------------------------------------------------
531 // destruction
532 // ----------------------------------------------------------------------------
533
534 wxTempFile::~wxTempFile()
535 {
536 if ( IsOpened() )
537 Discard();
538 }
539
540 bool wxTempFile::Commit()
541 {
542 m_file.Close();
543
544 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
545 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
546 return FALSE;
547 }
548
549 if ( wxRename(m_strTemp, m_strName) != 0 ) {
550 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
551 return FALSE;
552 }
553
554 return TRUE;
555 }
556
557 void wxTempFile::Discard()
558 {
559 m_file.Close();
560 if ( wxRemove(m_strTemp) != 0 )
561 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
562 }
563
564 #endif // wxUSE_FILE
565