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