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