Add wxFile::{Get,Clear}LastError() functions.
[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(__WXMSW__) && !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(__WXMSW__) && 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 #elif defined(__WXPALMOS__)
84 #include "wx/palmos/missing.h"
85 #else
86 #error "Please specify the header with file functions declarations."
87 #endif //Win/UNIX
88
89 #include <stdio.h> // SEEK_xxx constants
90
91 #ifndef __WXWINCE__
92 #include <errno.h>
93 #endif
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 // wxWidgets
107 #ifndef WX_PRECOMP
108 #include "wx/string.h"
109 #include "wx/intl.h"
110 #include "wx/log.h"
111 #include "wx/crt.h"
112 #endif // !WX_PRECOMP
113
114 #include "wx/filename.h"
115 #include "wx/file.h"
116 #include "wx/filefn.h"
117
118 // there is no distinction between text and binary files under Unix, so define
119 // O_BINARY as 0 if the system headers don't do it already
120 #if defined(__UNIX__) && !defined(O_BINARY)
121 #define O_BINARY (0)
122 #endif //__UNIX__
123
124 #ifdef __WXMSW__
125 #include "wx/msw/mslu.h"
126 #endif
127
128 #ifdef __WXWINCE__
129 #include "wx/msw/private.h"
130 #endif
131
132 #ifndef MAX_PATH
133 #define MAX_PATH 512
134 #endif
135
136 // ============================================================================
137 // implementation of wxFile
138 // ============================================================================
139
140 // ----------------------------------------------------------------------------
141 // static functions
142 // ----------------------------------------------------------------------------
143
144 bool wxFile::Exists(const wxString& name)
145 {
146 return wxFileExists(name);
147 }
148
149 bool wxFile::Access(const wxString& name, OpenMode mode)
150 {
151 int how;
152
153 switch ( mode )
154 {
155 default:
156 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
157 // fall through
158
159 case read:
160 how = R_OK;
161 break;
162
163 case write:
164 how = W_OK;
165 break;
166
167 case read_write:
168 how = R_OK | W_OK;
169 break;
170 }
171
172 return wxAccess(name, how) == 0;
173 }
174
175 // ----------------------------------------------------------------------------
176 // opening/closing
177 // ----------------------------------------------------------------------------
178
179 // ctors
180 wxFile::wxFile(const wxString& fileName, OpenMode mode)
181 {
182 m_fd = fd_invalid;
183 m_lasterror = 0;
184
185 Open(fileName, mode);
186 }
187
188 bool wxFile::CheckForError(wxFileOffset rc) const
189 {
190 if ( rc != -1 )
191 return false;
192
193 const_cast<wxFile *>(this)->m_lasterror =
194 #ifndef __WXWINCE__
195 errno
196 #else
197 ::GetLastError()
198 #endif
199 ;
200
201 return true;
202 }
203
204 // create the file, fail if it already exists and bOverwrite
205 bool wxFile::Create(const wxString& fileName, bool bOverwrite, int accessMode)
206 {
207 // if bOverwrite we create a new file or truncate the existing one,
208 // otherwise we only create the new file and fail if it already exists
209 int fd = wxOpen( fileName,
210 O_BINARY | O_WRONLY | O_CREAT |
211 (bOverwrite ? O_TRUNC : O_EXCL),
212 accessMode );
213 if ( CheckForError(fd) )
214 {
215 wxLogSysError(_("can't create file '%s'"), fileName);
216 return false;
217 }
218
219 Attach(fd);
220 return true;
221 }
222
223 // open the file
224 bool wxFile::Open(const wxString& fileName, OpenMode mode, int accessMode)
225 {
226 int flags = O_BINARY;
227
228 switch ( mode )
229 {
230 case read:
231 flags |= O_RDONLY;
232 break;
233
234 case write_append:
235 if ( wxFile::Exists(fileName) )
236 {
237 flags |= O_WRONLY | O_APPEND;
238 break;
239 }
240 //else: fall through as write_append is the same as write if the
241 // file doesn't exist
242
243 case write:
244 flags |= O_WRONLY | O_CREAT | O_TRUNC;
245 break;
246
247 case write_excl:
248 flags |= O_WRONLY | O_CREAT | O_EXCL;
249 break;
250
251 case read_write:
252 flags |= O_RDWR;
253 break;
254 }
255
256 #ifdef __WINDOWS__
257 // only read/write bits for "all" are supported by this function under
258 // Windows, and VC++ 8 returns EINVAL if any other bits are used in
259 // accessMode, so clear them as they have at best no effect anyhow
260 accessMode &= wxS_IRUSR | wxS_IWUSR;
261 #endif // __WINDOWS__
262
263 int fd = wxOpen( fileName, flags, accessMode);
264
265 if ( CheckForError(fd) )
266 {
267 wxLogSysError(_("can't open file '%s'"), fileName);
268 return false;
269 }
270
271 Attach(fd);
272 return true;
273 }
274
275 // close
276 bool wxFile::Close()
277 {
278 if ( IsOpened() ) {
279 if ( CheckForError(wxClose(m_fd)) )
280 {
281 wxLogSysError(_("can't close file descriptor %d"), m_fd);
282 m_fd = fd_invalid;
283 return false;
284 }
285 else
286 m_fd = fd_invalid;
287 }
288
289 return true;
290 }
291
292 // ----------------------------------------------------------------------------
293 // read/write
294 // ----------------------------------------------------------------------------
295
296 // read
297 ssize_t wxFile::Read(void *pBuf, size_t nCount)
298 {
299 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
300
301 ssize_t iRc = wxRead(m_fd, pBuf, nCount);
302
303 if ( CheckForError(iRc) )
304 {
305 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
306 return wxInvalidOffset;
307 }
308
309 return iRc;
310 }
311
312 // write
313 size_t wxFile::Write(const void *pBuf, size_t nCount)
314 {
315 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
316
317 ssize_t iRc = wxWrite(m_fd, pBuf, nCount);
318
319 if ( CheckForError(iRc) )
320 {
321 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
322 iRc = 0;
323 }
324
325 return iRc;
326 }
327
328 bool wxFile::Write(const wxString& s, const wxMBConv& conv)
329 {
330 const wxWX2MBbuf buf = s.mb_str(conv);
331 if ( !buf )
332 return false;
333
334 #if wxUSE_UNICODE
335 const size_t size = buf.length();
336 #else
337 const size_t size = s.length();
338 #endif
339
340 return Write(buf, size) == size;
341 }
342
343 // flush
344 bool wxFile::Flush()
345 {
346 #ifdef HAVE_FSYNC
347 // fsync() only works on disk files and returns errors for pipes, don't
348 // call it then
349 if ( IsOpened() && GetKind() == wxFILE_KIND_DISK )
350 {
351 if ( CheckForError(wxFsync(m_fd)) )
352 {
353 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
354 return false;
355 }
356 }
357 #endif // HAVE_FSYNC
358
359 return true;
360 }
361
362 // ----------------------------------------------------------------------------
363 // seek
364 // ----------------------------------------------------------------------------
365
366 // seek
367 wxFileOffset wxFile::Seek(wxFileOffset ofs, wxSeekMode mode)
368 {
369 wxASSERT_MSG( IsOpened(), wxT("can't seek on closed file") );
370 wxCHECK_MSG( ofs != wxInvalidOffset || mode != wxFromStart,
371 wxInvalidOffset,
372 wxT("invalid absolute file offset") );
373
374 int origin;
375 switch ( mode ) {
376 default:
377 wxFAIL_MSG(wxT("unknown seek origin"));
378
379 case wxFromStart:
380 origin = SEEK_SET;
381 break;
382
383 case wxFromCurrent:
384 origin = SEEK_CUR;
385 break;
386
387 case wxFromEnd:
388 origin = SEEK_END;
389 break;
390 }
391
392 wxFileOffset iRc = wxSeek(m_fd, ofs, origin);
393 if ( CheckForError(iRc) )
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 ( CheckForError(iRc) )
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 // we use a special method for Linux systems where files in sysfs (i.e.
421 // those under /sys typically) return length of 4096 bytes even when
422 // they're much smaller -- this is a problem as it results in errors later
423 // when we try reading 4KB from them
424 #ifdef __LINUX__
425 struct stat st;
426 if ( fstat(m_fd, &st) == 0 )
427 {
428 // returning 0 for the special files indicates to the caller that they
429 // are not seekable
430 return st.st_blocks ? st.st_size : 0;
431 }
432 //else: failed to stat, try the normal method
433 #endif // __LINUX__
434
435 wxFileOffset iRc = Tell();
436 if ( iRc != wxInvalidOffset ) {
437 wxFileOffset iLen = const_cast<wxFile *>(this)->SeekEnd();
438 if ( iLen != wxInvalidOffset ) {
439 // restore old position
440 if ( ((wxFile *)this)->Seek(iRc) == wxInvalidOffset ) {
441 // error
442 iLen = wxInvalidOffset;
443 }
444 }
445
446 iRc = iLen;
447 }
448
449 if ( iRc == wxInvalidOffset )
450 {
451 // last error was already set by Tell()
452 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
453 }
454
455 return iRc;
456 }
457
458 // is end of file reached?
459 bool wxFile::Eof() const
460 {
461 wxASSERT( IsOpened() );
462
463 wxFileOffset iRc;
464
465 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ )
466 // @@ this doesn't work, of course, on unseekable file descriptors
467 wxFileOffset ofsCur = Tell(),
468 ofsMax = Length();
469 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
470 iRc = wxInvalidOffset;
471 else
472 iRc = ofsCur == ofsMax;
473 #else // Windows and "native" compiler
474 iRc = wxEof(m_fd);
475 #endif // Windows/Unix
476
477 if ( iRc == 0 )
478 return false;
479
480 if ( iRc == wxInvalidOffset )
481 {
482 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
483 }
484 else if ( iRc != 1 )
485 {
486 wxFAIL_MSG(wxT("invalid eof() return value."));
487 }
488
489 return true;
490 }
491
492 // ============================================================================
493 // implementation of wxTempFile
494 // ============================================================================
495
496 // ----------------------------------------------------------------------------
497 // construction
498 // ----------------------------------------------------------------------------
499
500 wxTempFile::wxTempFile(const wxString& strName)
501 {
502 Open(strName);
503 }
504
505 bool wxTempFile::Open(const wxString& strName)
506 {
507 // we must have an absolute filename because otherwise CreateTempFileName()
508 // would create the temp file in $TMP (i.e. the system standard location
509 // for the temp files) which might be on another volume/drive/mount and
510 // wxRename()ing it later to m_strName from Commit() would then fail
511 //
512 // with the absolute filename, the temp file is created in the same
513 // directory as this one which ensures that wxRename() may work later
514 wxFileName fn(strName);
515 if ( !fn.IsAbsolute() )
516 {
517 fn.Normalize(wxPATH_NORM_ABSOLUTE);
518 }
519
520 m_strName = fn.GetFullPath();
521
522 m_strTemp = wxFileName::CreateTempFileName(m_strName, &m_file);
523
524 if ( m_strTemp.empty() )
525 {
526 // CreateTempFileName() failed
527 return false;
528 }
529
530 #ifdef __UNIX__
531 // the temp file should have the same permissions as the original one
532 mode_t mode;
533
534 wxStructStat st;
535 if ( stat( (const char*) m_strName.fn_str(), &st) == 0 )
536 {
537 mode = st.st_mode;
538 }
539 else
540 {
541 // file probably didn't exist, just give it the default mode _using_
542 // user's umask (new files creation should respect umask)
543 mode_t mask = umask(0777);
544 mode = 0666 & ~mask;
545 umask(mask);
546 }
547
548 if ( chmod( (const char*) m_strTemp.fn_str(), mode) == -1 )
549 {
550 #ifndef __OS2__
551 wxLogSysError(_("Failed to set temporary file permissions"));
552 #endif
553 }
554 #endif // Unix
555
556 return true;
557 }
558
559 // ----------------------------------------------------------------------------
560 // destruction
561 // ----------------------------------------------------------------------------
562
563 wxTempFile::~wxTempFile()
564 {
565 if ( IsOpened() )
566 Discard();
567 }
568
569 bool wxTempFile::Commit()
570 {
571 m_file.Close();
572
573 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
574 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
575 return false;
576 }
577
578 if ( !wxRenameFile(m_strTemp, m_strName) ) {
579 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
580 return false;
581 }
582
583 return true;
584 }
585
586 void wxTempFile::Discard()
587 {
588 m_file.Close();
589 if ( wxRemove(m_strTemp) != 0 )
590 {
591 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
592 }
593 }
594
595 #endif // wxUSE_FILE
596