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