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