]> git.saurik.com Git - wxWidgets.git/blob - src/common/file.cpp
Fix some leaks cause by removing list.DeleteContents calls.
[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 licence
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(__WXMICROWIN__) && !defined(__WXWINCE__)
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(__WXMSW__) && defined(__WXWINCE__)
58 // TODO: what to include?
59 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
60 #include <unistd.h>
61 #include <sys/stat.h>
62 #ifdef __GNUWIN32__
63 #include <windows.h>
64 #endif
65 #elif defined(__DOS__)
66 #if defined(__WATCOMC__)
67 #include <io.h>
68 #elif defined(__DJGPP__)
69 #include <io.h>
70 #include <unistd.h>
71 #include <stdio.h>
72 #else
73 #error "Please specify the header with file functions declarations."
74 #endif
75 #elif (defined(__WXPM__))
76 #include <io.h>
77 #elif (defined(__WXSTUBS__))
78 // Have to ifdef this for different environments
79 #include <io.h>
80 #elif (defined(__WXMAC__))
81 #if __MSL__ < 0x6000
82 int access( const char *path, int mode ) { return 0 ; }
83 #else
84 int _access( const char *path, int mode ) { return 0 ; }
85 #endif
86 char* mktemp( char * path ) { return path ;}
87 #include <stat.h>
88 #include <unistd.h>
89 #else
90 #error "Please specify the header with file functions declarations."
91 #endif //Win/UNIX
92
93 #include <stdio.h> // SEEK_xxx constants
94
95 #ifndef __WXWINCE__
96 #include <fcntl.h> // O_RDONLY &c
97 #endif
98
99 #ifdef __WXWINCE__
100 // Nothing
101 #elif !defined(__MWERKS__)
102 #include <sys/types.h> // needed for stat
103 #include <sys/stat.h> // stat
104 #elif defined(__MWERKS__) && ( defined(__WXMSW__) || defined(__MACH__) )
105 #include <sys/types.h> // needed for stat
106 #include <sys/stat.h> // stat
107 #endif
108
109 // Windows compilers don't have these constants
110 #ifndef W_OK
111 enum
112 {
113 F_OK = 0, // test for existence
114 X_OK = 1, // execute permission
115 W_OK = 2, // write
116 R_OK = 4 // read
117 };
118 #endif // W_OK
119
120 // there is no distinction between text and binary files under Unix, so define
121 // O_BINARY as 0 if the system headers don't do it already
122 #if defined(__UNIX__) && !defined(O_BINARY)
123 #define O_BINARY (0)
124 #endif //__UNIX__
125
126 #ifdef __SALFORDC__
127 #include <unix.h>
128 #endif
129
130 #ifndef MAX_PATH
131 #define MAX_PATH 512
132 #endif
133
134 // some broken compilers don't have 3rd argument in open() and creat()
135 #ifdef __SALFORDC__
136 #define ACCESS(access)
137 #define stat _stat
138 #else // normal compiler
139 #define ACCESS(access) , (access)
140 #endif // Salford C
141
142 // wxWindows
143 #ifndef WX_PRECOMP
144 #include "wx/string.h"
145 #include "wx/intl.h"
146 #include "wx/log.h"
147 #endif // !WX_PRECOMP
148
149 #include "wx/filename.h"
150 #include "wx/file.h"
151 #include "wx/filefn.h"
152
153 #ifdef __WXMSW__
154 #include "wx/msw/mslu.h"
155 #endif
156
157 #ifdef __WXWINCE__
158 #include "wx/msw/private.h"
159 #endif
160
161 // ============================================================================
162 // implementation of wxFile
163 // ============================================================================
164
165 // ----------------------------------------------------------------------------
166 // static functions
167 // ----------------------------------------------------------------------------
168
169 bool wxFile::Exists(const wxChar *name)
170 {
171 return wxFileExists(name);
172 }
173
174 bool wxFile::Access(const wxChar *name, OpenMode mode)
175 {
176 int how;
177
178 switch ( mode )
179 {
180 default:
181 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
182 // fall through
183
184 case read:
185 how = R_OK;
186 break;
187
188 case write:
189 how = W_OK;
190 break;
191
192 case read_write:
193 how = R_OK | W_OK;
194 break;
195 }
196
197 #ifdef __WXWINCE__
198 // FIXME: use CreateFile with 0 access to query the file
199 return TRUE;
200 #else
201 return wxAccess(name, how) == 0;
202 #endif
203 }
204
205 // ----------------------------------------------------------------------------
206 // opening/closing
207 // ----------------------------------------------------------------------------
208
209 // ctors
210 wxFile::wxFile(const wxChar *szFileName, OpenMode mode)
211 {
212 m_fd = fd_invalid;
213 m_error = FALSE;
214
215 Open(szFileName, mode);
216 }
217
218 // create the file, fail if it already exists and bOverwrite
219 bool wxFile::Create(const wxChar *szFileName, bool bOverwrite, int accessMode)
220 {
221 // if bOverwrite we create a new file or truncate the existing one,
222 // otherwise we only create the new file and fail if it already exists
223 #if defined(__WXMAC__) && !defined(__UNIX__) && !wxUSE_UNICODE
224 // Dominic Mazzoni [dmazzoni+@cs.cmu.edu] reports that open is still broken on the mac, so we replace
225 // int fd = open(wxUnix2MacFilename( szFileName ), O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
226 int fd = creat( szFileName , accessMode);
227 #else
228 #ifdef __WXWINCE__
229 HANDLE fileHandle = ::CreateFile(szFileName, GENERIC_WRITE, 0, NULL,
230 bOverwrite ? CREATE_ALWAYS : CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
231 0);
232 int fd = 0;
233 if (fileHandle == INVALID_HANDLE_VALUE)
234 fd = (int) fileHandle;
235 else
236 fd = -1;
237 #else
238 int fd = wxOpen( szFileName,
239 O_BINARY | O_WRONLY | O_CREAT |
240 (bOverwrite ? O_TRUNC : O_EXCL)
241 ACCESS(accessMode) );
242 #endif
243 #endif
244 if ( fd == -1 )
245 {
246 wxLogSysError(_("can't create file '%s'"), szFileName);
247 return FALSE;
248 }
249 else
250 {
251 Attach(fd);
252 return TRUE;
253 }
254 }
255
256 // open the file
257 bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
258 {
259 #ifdef __WXWINCE__
260 DWORD access = 0;
261 DWORD shareMode = 0;
262 DWORD disposition = 0;
263
264 int flags = O_BINARY;
265
266 switch ( mode )
267 {
268 case read:
269 access = GENERIC_READ;
270 shareMode = FILE_SHARE_READ|FILE_SHARE_WRITE;
271 disposition = OPEN_EXISTING;
272 break;
273
274 case write_append:
275 if ( wxFile::Exists(szFileName) )
276 {
277 access = GENERIC_READ|GENERIC_WRITE;
278 shareMode = FILE_SHARE_READ;
279 disposition = 0;
280 break;
281 }
282 //else: fall through as write_append is the same as write if the
283 // file doesn't exist
284
285 case write:
286 access = GENERIC_WRITE;
287 shareMode = 0;
288 disposition = TRUNCATE_EXISTING;
289 break;
290
291 case write_excl:
292 access = GENERIC_WRITE;
293 shareMode = 0;
294 disposition = TRUNCATE_EXISTING;
295 break;
296
297 case read_write:
298 access = GENERIC_READ|GENERIC_WRITE;
299 shareMode = 0;
300 disposition = 0;
301 break;
302 }
303
304 int fd = 0;
305 HANDLE fileHandle = ::CreateFile(szFileName, access, shareMode, NULL,
306 disposition, FILE_ATTRIBUTE_NORMAL, 0);
307 if (fileHandle == INVALID_HANDLE_VALUE)
308 fd = -1;
309 else
310 fd = (int) fileHandle;
311 #else
312 int flags = O_BINARY;
313
314 switch ( mode )
315 {
316 case read:
317 flags |= O_RDONLY;
318 break;
319
320 case write_append:
321 if ( wxFile::Exists(szFileName) )
322 {
323 flags |= O_WRONLY | O_APPEND;
324 break;
325 }
326 //else: fall through as write_append is the same as write if the
327 // file doesn't exist
328
329 case write:
330 flags |= O_WRONLY | O_CREAT | O_TRUNC;
331 break;
332
333 case write_excl:
334 flags |= O_WRONLY | O_CREAT | O_EXCL;
335 break;
336
337 case read_write:
338 flags |= O_RDWR;
339 break;
340 }
341
342 int fd = wxOpen( szFileName, flags ACCESS(accessMode));
343 #endif
344 if ( fd == -1 )
345 {
346 wxLogSysError(_("can't open file '%s'"), szFileName);
347 return FALSE;
348 }
349 else {
350 Attach(fd);
351 return TRUE;
352 }
353 }
354
355 // close
356 bool wxFile::Close()
357 {
358 if ( IsOpened() ) {
359 #ifdef __WXWINCE__
360 if (!CloseHandle((HANDLE) m_fd))
361 #else
362 if ( close(m_fd) == -1 )
363 #endif
364 {
365 wxLogSysError(_("can't close file descriptor %d"), m_fd);
366 m_fd = fd_invalid;
367 return FALSE;
368 }
369 else
370 m_fd = fd_invalid;
371 }
372
373 return TRUE;
374 }
375
376 // ----------------------------------------------------------------------------
377 // read/write
378 // ----------------------------------------------------------------------------
379
380 // read
381 off_t wxFile::Read(void *pBuf, off_t nCount)
382 {
383 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
384
385 #ifdef __WXWINCE__
386 DWORD bytesRead = 0;
387 int iRc = 0;
388 if (ReadFile((HANDLE) m_fd, pBuf, (DWORD) nCount, & bytesRead, NULL))
389 iRc = bytesRead;
390 else
391 iRc = -1;
392 #elif defined(__MWERKS__)
393 int iRc = ::read(m_fd, (char*) pBuf, nCount);
394 #else
395 int iRc = ::read(m_fd, pBuf, nCount);
396 #endif
397 if ( iRc == -1 ) {
398 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
399 return wxInvalidOffset;
400 }
401 else
402 return (size_t)iRc;
403 }
404
405 // write
406 size_t wxFile::Write(const void *pBuf, size_t nCount)
407 {
408 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
409
410 #ifdef __WXWINCE__
411 DWORD bytesRead = 0;
412 int iRc = 0;
413 if (WriteFile((HANDLE) m_fd, pBuf, (DWORD) nCount, & bytesRead, NULL))
414 iRc = bytesRead;
415 else
416 iRc = -1;
417 #elif defined(__MWERKS__)
418 #if __MSL__ >= 0x6000
419 int iRc = ::write(m_fd, (void*) pBuf, nCount);
420 #else
421 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
422 #endif
423 #else
424 int iRc = ::write(m_fd, pBuf, nCount);
425 #endif
426 if ( iRc == -1 ) {
427 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
428 m_error = TRUE;
429 return 0;
430 }
431 else
432 return iRc;
433 }
434
435 // flush
436 bool wxFile::Flush()
437 {
438 if ( IsOpened() ) {
439 #ifdef __WXWINCE__
440 // Do nothing
441 #elif defined(__VISUALC__) || wxHAVE_FSYNC
442 if ( wxFsync(m_fd) == -1 )
443 {
444 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
445 return FALSE;
446 }
447 #else // no fsync
448 // just do nothing
449 #endif // fsync
450 }
451
452 return TRUE;
453 }
454
455 // ----------------------------------------------------------------------------
456 // seek
457 // ----------------------------------------------------------------------------
458
459 // seek
460 off_t wxFile::Seek(off_t ofs, wxSeekMode mode)
461 {
462 wxASSERT( IsOpened() );
463
464 #ifdef __WXWINCE__
465 int origin;
466 switch ( mode ) {
467 default:
468 wxFAIL_MSG(_("unknown seek origin"));
469
470 case wxFromStart:
471 origin = FILE_BEGIN;
472 break;
473
474 case wxFromCurrent:
475 origin = FILE_CURRENT;
476 break;
477
478 case wxFromEnd:
479 origin = FILE_END;
480 break;
481 }
482
483 DWORD res = SetFilePointer((HANDLE) m_fd, ofs, 0, origin) ;
484 if (res == 0xFFFFFFFF && GetLastError() != NO_ERROR)
485 {
486 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
487 return wxInvalidOffset;
488 }
489 else
490 return (off_t)res;
491 #else
492 int origin;
493 switch ( mode ) {
494 default:
495 wxFAIL_MSG(_("unknown seek origin"));
496
497 case wxFromStart:
498 origin = SEEK_SET;
499 break;
500
501 case wxFromCurrent:
502 origin = SEEK_CUR;
503 break;
504
505 case wxFromEnd:
506 origin = SEEK_END;
507 break;
508 }
509
510 int iRc = lseek(m_fd, ofs, origin);
511 if ( iRc == -1 ) {
512 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
513 return wxInvalidOffset;
514 }
515 else
516 return (off_t)iRc;
517 #endif
518 }
519
520 // get current off_t
521 off_t wxFile::Tell() const
522 {
523 wxASSERT( IsOpened() );
524
525 #ifdef __WXWINCE__
526 DWORD res = SetFilePointer((HANDLE) m_fd, 0, 0, FILE_CURRENT) ;
527 if (res == 0xFFFFFFFF && GetLastError() != NO_ERROR)
528 {
529 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
530 return wxInvalidOffset;
531 }
532 else
533 return (off_t)res;
534 #else
535 int iRc = wxTell(m_fd);
536 if ( iRc == -1 ) {
537 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
538 return wxInvalidOffset;
539 }
540 else
541 return (off_t)iRc;
542 #endif
543 }
544
545 // get current file length
546 off_t wxFile::Length() const
547 {
548 wxASSERT( IsOpened() );
549
550 #ifdef __WXWINCE__
551 DWORD off0 = SetFilePointer((HANDLE) m_fd, 0, 0, FILE_CURRENT);
552 DWORD off1 = SetFilePointer((HANDLE) m_fd, 0, 0, FILE_END);
553 off_t len = off1;
554
555 // Restore position
556 SetFilePointer((HANDLE) m_fd, off0, 0, FILE_BEGIN);
557 return len;
558 #else
559 #ifdef __VISUALC__
560 int iRc = _filelength(m_fd);
561 #else // !VC++
562 int iRc = wxTell(m_fd);
563 if ( iRc != -1 ) {
564 // @ have to use const_cast :-(
565 int iLen = ((wxFile *)this)->SeekEnd();
566 if ( iLen != -1 ) {
567 // restore old position
568 if ( ((wxFile *)this)->Seek(iRc) == -1 ) {
569 // error
570 iLen = -1;
571 }
572 }
573
574 iRc = iLen;
575 }
576 #endif // VC++
577
578 if ( iRc == -1 ) {
579 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
580 return wxInvalidOffset;
581 }
582 else
583 return (off_t)iRc;
584 #endif
585 }
586
587 // is end of file reached?
588 bool wxFile::Eof() const
589 {
590 wxASSERT( IsOpened() );
591
592 #ifdef __WXWINCE__
593 DWORD off0 = SetFilePointer((HANDLE) m_fd, 0, 0, FILE_CURRENT);
594 DWORD off1 = SetFilePointer((HANDLE) m_fd, 0, 0, FILE_END);
595 if (off0 == off1)
596 return TRUE;
597 else
598 {
599 SetFilePointer((HANDLE) m_fd, off0, 0, FILE_BEGIN);
600 return FALSE;
601 }
602 #else
603 int iRc;
604
605 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
606 // @@ this doesn't work, of course, on unseekable file descriptors
607 off_t ofsCur = Tell(),
608 ofsMax = Length();
609 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
610 iRc = -1;
611 else
612 iRc = ofsCur == ofsMax;
613 #else // Windows and "native" compiler
614 iRc = eof(m_fd);
615 #endif // Windows/Unix
616
617 switch ( iRc ) {
618 case 1:
619 break;
620
621 case 0:
622 return FALSE;
623
624 case -1:
625 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
626 break;
627
628 default:
629 wxFAIL_MSG(_("invalid eof() return value."));
630 }
631
632 return TRUE;
633 #endif
634 }
635
636 // ============================================================================
637 // implementation of wxTempFile
638 // ============================================================================
639
640 // ----------------------------------------------------------------------------
641 // construction
642 // ----------------------------------------------------------------------------
643
644 wxTempFile::wxTempFile(const wxString& strName)
645 {
646 Open(strName);
647 }
648
649 bool wxTempFile::Open(const wxString& strName)
650 {
651 // we must have an absolute filename because otherwise CreateTempFileName()
652 // would create the temp file in $TMP (i.e. the system standard location
653 // for the temp files) which might be on another volume/drive/mount and
654 // wxRename()ing it later to m_strName from Commit() would then fail
655 //
656 // with the absolute filename, the temp file is created in the same
657 // directory as this one which ensures that wxRename() may work later
658 wxFileName fn(strName);
659 if ( !fn.IsAbsolute() )
660 {
661 fn.Normalize(wxPATH_NORM_ABSOLUTE);
662 }
663
664 m_strName = fn.GetFullPath();
665
666 m_strTemp = wxFileName::CreateTempFileName(m_strName, &m_file);
667
668 if ( m_strTemp.empty() )
669 {
670 // CreateTempFileName() failed
671 return FALSE;
672 }
673
674 #ifdef __UNIX__
675 // the temp file should have the same permissions as the original one
676 mode_t mode;
677
678 wxStructStat st;
679 if ( stat( (const char*) m_strName.fn_str(), &st) == 0 )
680 {
681 mode = st.st_mode;
682 }
683 else
684 {
685 // file probably didn't exist, just give it the default mode _using_
686 // user's umask (new files creation should respect umask)
687 mode_t mask = umask(0777);
688 mode = 0666 & ~mask;
689 umask(mask);
690 }
691
692 if ( chmod( (const char*) m_strTemp.fn_str(), mode) == -1 )
693 {
694 wxLogSysError(_("Failed to set temporary file permissions"));
695 }
696 #endif // Unix
697
698 return TRUE;
699 }
700
701 // ----------------------------------------------------------------------------
702 // destruction
703 // ----------------------------------------------------------------------------
704
705 wxTempFile::~wxTempFile()
706 {
707 if ( IsOpened() )
708 Discard();
709 }
710
711 bool wxTempFile::Commit()
712 {
713 m_file.Close();
714
715 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
716 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
717 return FALSE;
718 }
719
720 if ( wxRenameFile(m_strTemp, m_strName) != 0 ) {
721 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
722 return FALSE;
723 }
724
725 return TRUE;
726 }
727
728 void wxTempFile::Discard()
729 {
730 m_file.Close();
731 if ( wxRemove(m_strTemp) != 0 )
732 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
733 }
734
735 #endif // wxUSE_FILE
736