made Tell/Seek/Length() return wxFileSize_t as well
[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 // ============================================================================
148 // implementation of wxFile
149 // ============================================================================
150
151 // ----------------------------------------------------------------------------
152 // static functions
153 // ----------------------------------------------------------------------------
154
155 bool wxFile::Exists(const wxChar *name)
156 {
157 return wxFileExists(name);
158 }
159
160 bool wxFile::Access(const wxChar *name, OpenMode mode)
161 {
162 int how;
163
164 switch ( mode )
165 {
166 default:
167 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
168 // fall through
169
170 case read:
171 how = R_OK;
172 break;
173
174 case write:
175 how = W_OK;
176 break;
177
178 case read_write:
179 how = R_OK | W_OK;
180 break;
181 }
182
183 return wxAccess(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__) && !wxUSE_UNICODE
205 // Dominic Mazzoni [dmazzoni+@cs.cmu.edu] reports that open is still broken on the mac, so we replace
206 // int fd = open( szFileName , O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
207 int fd = creat( szFileName , accessMode);
208 #else
209 int fd = wxOpen( szFileName,
210 O_BINARY | O_WRONLY | O_CREAT |
211 (bOverwrite ? O_TRUNC : O_EXCL)
212 ACCESS(accessMode) );
213 #endif
214 if ( fd == -1 )
215 {
216 wxLogSysError(_("can't create file '%s'"), szFileName);
217 return false;
218 }
219 else
220 {
221 Attach(fd);
222 return true;
223 }
224 }
225
226 // open the file
227 bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
228 {
229 int flags = O_BINARY;
230
231 switch ( mode )
232 {
233 case read:
234 flags |= O_RDONLY;
235 break;
236
237 case write_append:
238 if ( wxFile::Exists(szFileName) )
239 {
240 flags |= O_WRONLY | O_APPEND;
241 break;
242 }
243 //else: fall through as write_append is the same as write if the
244 // file doesn't exist
245
246 case write:
247 flags |= O_WRONLY | O_CREAT | O_TRUNC;
248 break;
249
250 case write_excl:
251 flags |= O_WRONLY | O_CREAT | O_EXCL;
252 break;
253
254 case read_write:
255 flags |= O_RDWR;
256 break;
257 }
258
259 #ifdef __WINDOWS__
260 // only read/write bits for "all" are supported by this function under
261 // Windows, and VC++ 8 returns EINVAL if any other bits are used in
262 // accessMode, so clear them as they have at best no effect anyhow
263 accessMode &= wxS_IRUSR | wxS_IWUSR;
264 #endif // __WINDOWS__
265
266 int fd = wxOpen( szFileName, flags ACCESS(accessMode));
267
268 if ( fd == -1 )
269 {
270 wxLogSysError(_("can't open file '%s'"), szFileName);
271 return false;
272 }
273 else {
274 Attach(fd);
275 return true;
276 }
277 }
278
279 // close
280 bool wxFile::Close()
281 {
282 if ( IsOpened() ) {
283 if (wxClose(m_fd) == -1)
284 {
285 wxLogSysError(_("can't close file descriptor %d"), m_fd);
286 m_fd = fd_invalid;
287 return false;
288 }
289 else
290 m_fd = fd_invalid;
291 }
292
293 return true;
294 }
295
296 // ----------------------------------------------------------------------------
297 // read/write
298 // ----------------------------------------------------------------------------
299
300 // read
301 wxFileSize_t wxFile::Read(void *pBuf, wxFileSize_t nCount)
302 {
303 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
304
305 wxFileSize_t iRc = wxRead(m_fd, pBuf, nCount);
306
307 if ( iRc == wxInvalidOffset )
308 {
309 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
310 }
311
312 return iRc;
313 }
314
315 // write
316 wxFileSize_t wxFile::Write(const void *pBuf, wxFileSize_t nCount)
317 {
318 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
319
320 wxFileSize_t iRc = wxWrite(m_fd, pBuf, nCount);
321
322 if ( iRc == wxInvalidOffset )
323 {
324 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
325 m_error = true;
326 iRc = 0;
327 }
328
329 return (wxFileSize_t)iRc;
330 }
331
332 // flush
333 bool wxFile::Flush()
334 {
335 if ( IsOpened() ) {
336 #if defined(__VISUALC__) || wxHAVE_FSYNC
337 if ( wxFsync(m_fd) == -1 )
338 {
339 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
340 return false;
341 }
342 #else // no fsync
343 // just do nothing
344 #endif // fsync
345 }
346
347 return true;
348 }
349
350 // ----------------------------------------------------------------------------
351 // seek
352 // ----------------------------------------------------------------------------
353
354 // seek
355 wxFileSize_t wxFile::Seek(wxFileOffset ofs, wxSeekMode mode)
356 {
357 wxASSERT( IsOpened() );
358
359 int origin;
360 switch ( mode ) {
361 default:
362 wxFAIL_MSG(_("unknown seek origin"));
363
364 case wxFromStart:
365 origin = SEEK_SET;
366 break;
367
368 case wxFromCurrent:
369 origin = SEEK_CUR;
370 break;
371
372 case wxFromEnd:
373 origin = SEEK_END;
374 break;
375 }
376
377 if (ofs == (wxFileOffset) wxInvalidOffset)
378 {
379 wxLogSysError(_("can't seek on file descriptor %d, large files support is not enabled."), m_fd);
380 return wxInvalidOffset;
381 }
382 wxFileSize_t iRc = wxSeek(m_fd, ofs, origin);
383 if ( iRc == wxInvalidOffset )
384 {
385 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
386 }
387
388 return iRc;
389 }
390
391 // get current file offset
392 wxFileSize_t wxFile::Tell() const
393 {
394 wxASSERT( IsOpened() );
395
396 wxFileSize_t iRc = wxTell(m_fd);
397 if ( iRc == wxInvalidOffset )
398 {
399 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
400 }
401
402 return iRc;
403 }
404
405 // get current file length
406 wxFileSize_t wxFile::Length() const
407 {
408 wxASSERT( IsOpened() );
409
410 wxFileSize_t iRc = Tell();
411 if ( iRc != wxInvalidOffset ) {
412 // have to use const_cast :-(
413 wxFileSize_t iLen = ((wxFile *)this)->SeekEnd();
414 if ( iLen != wxInvalidOffset ) {
415 // restore old position
416 if ( ((wxFile *)this)->Seek(iRc) == wxInvalidOffset ) {
417 // error
418 iLen = wxInvalidOffset;
419 }
420 }
421
422 iRc = iLen;
423 }
424
425 if ( iRc == wxInvalidOffset )
426 {
427 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
428 }
429
430 return iRc;
431 }
432
433 // is end of file reached?
434 bool wxFile::Eof() const
435 {
436 wxASSERT( IsOpened() );
437
438 wxFileSize_t iRc;
439
440 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
441 // @@ this doesn't work, of course, on unseekable file descriptors
442 wxFileSize_t ofsCur = Tell(),
443 ofsMax = Length();
444 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
445 iRc = wxInvalidOffset;
446 else
447 iRc = ofsCur == ofsMax;
448 #else // Windows and "native" compiler
449 iRc = wxEof(m_fd);
450 #endif // Windows/Unix
451
452 switch ( iRc ) {
453 case 1:
454 break;
455
456 case 0:
457 return false;
458
459 case wxInvalidOffset:
460 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
461 break;
462
463 default:
464 wxFAIL_MSG(_("invalid eof() return value."));
465 }
466
467 return true;
468 }
469
470 // ============================================================================
471 // implementation of wxTempFile
472 // ============================================================================
473
474 // ----------------------------------------------------------------------------
475 // construction
476 // ----------------------------------------------------------------------------
477
478 wxTempFile::wxTempFile(const wxString& strName)
479 {
480 Open(strName);
481 }
482
483 bool wxTempFile::Open(const wxString& strName)
484 {
485 // we must have an absolute filename because otherwise CreateTempFileName()
486 // would create the temp file in $TMP (i.e. the system standard location
487 // for the temp files) which might be on another volume/drive/mount and
488 // wxRename()ing it later to m_strName from Commit() would then fail
489 //
490 // with the absolute filename, the temp file is created in the same
491 // directory as this one which ensures that wxRename() may work later
492 wxFileName fn(strName);
493 if ( !fn.IsAbsolute() )
494 {
495 fn.Normalize(wxPATH_NORM_ABSOLUTE);
496 }
497
498 m_strName = fn.GetFullPath();
499
500 m_strTemp = wxFileName::CreateTempFileName(m_strName, &m_file);
501
502 if ( m_strTemp.empty() )
503 {
504 // CreateTempFileName() failed
505 return false;
506 }
507
508 #ifdef __UNIX__
509 // the temp file should have the same permissions as the original one
510 mode_t mode;
511
512 wxStructStat st;
513 if ( stat( (const char*) m_strName.fn_str(), &st) == 0 )
514 {
515 mode = st.st_mode;
516 }
517 else
518 {
519 // file probably didn't exist, just give it the default mode _using_
520 // user's umask (new files creation should respect umask)
521 mode_t mask = umask(0777);
522 mode = 0666 & ~mask;
523 umask(mask);
524 }
525
526 if ( chmod( (const char*) m_strTemp.fn_str(), mode) == -1 )
527 {
528 #ifndef __OS2__
529 wxLogSysError(_("Failed to set temporary file permissions"));
530 #endif
531 }
532 #endif // Unix
533
534 return true;
535 }
536
537 // ----------------------------------------------------------------------------
538 // destruction
539 // ----------------------------------------------------------------------------
540
541 wxTempFile::~wxTempFile()
542 {
543 if ( IsOpened() )
544 Discard();
545 }
546
547 bool wxTempFile::Commit()
548 {
549 m_file.Close();
550
551 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
552 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
553 return false;
554 }
555
556 if ( !wxRenameFile(m_strTemp, m_strName) ) {
557 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
558 return false;
559 }
560
561 return true;
562 }
563
564 void wxTempFile::Discard()
565 {
566 m_file.Close();
567 if ( wxRemove(m_strTemp) != 0 )
568 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
569 }
570
571 #endif // wxUSE_FILE
572