]> git.saurik.com Git - wxWidgets.git/blob - src/common/file.cpp
d6b4620e7dbb2bc319e336df30fad3fbb7c6017d
[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 ssize_t length = 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 ssize_t 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 if ( length <= nread )
313 break;
314
315 length -= nread;
316 }
317
318 *p = 0;
319
320 wxString strTmp(buf, conv);
321 str->swap(strTmp);
322
323 return true;
324 }
325
326 // read
327 ssize_t wxFile::Read(void *pBuf, size_t nCount)
328 {
329 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
330
331 ssize_t iRc = wxRead(m_fd, pBuf, nCount);
332
333 if ( CheckForError(iRc) )
334 {
335 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
336 return wxInvalidOffset;
337 }
338
339 return iRc;
340 }
341
342 // write
343 size_t wxFile::Write(const void *pBuf, size_t nCount)
344 {
345 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
346
347 ssize_t iRc = wxWrite(m_fd, pBuf, nCount);
348
349 if ( CheckForError(iRc) )
350 {
351 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
352 iRc = 0;
353 }
354
355 return iRc;
356 }
357
358 bool wxFile::Write(const wxString& s, const wxMBConv& conv)
359 {
360 const wxWX2MBbuf buf = s.mb_str(conv);
361 if ( !buf )
362 return false;
363
364 #if wxUSE_UNICODE
365 const size_t size = buf.length();
366 #else
367 const size_t size = s.length();
368 #endif
369
370 return Write(buf, size) == size;
371 }
372
373 // flush
374 bool wxFile::Flush()
375 {
376 #ifdef HAVE_FSYNC
377 // fsync() only works on disk files and returns errors for pipes, don't
378 // call it then
379 if ( IsOpened() && GetKind() == wxFILE_KIND_DISK )
380 {
381 if ( CheckForError(wxFsync(m_fd)) )
382 {
383 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
384 return false;
385 }
386 }
387 #endif // HAVE_FSYNC
388
389 return true;
390 }
391
392 // ----------------------------------------------------------------------------
393 // seek
394 // ----------------------------------------------------------------------------
395
396 // seek
397 wxFileOffset wxFile::Seek(wxFileOffset ofs, wxSeekMode mode)
398 {
399 wxASSERT_MSG( IsOpened(), wxT("can't seek on closed file") );
400 wxCHECK_MSG( ofs != wxInvalidOffset || mode != wxFromStart,
401 wxInvalidOffset,
402 wxT("invalid absolute file offset") );
403
404 int origin;
405 switch ( mode ) {
406 default:
407 wxFAIL_MSG(wxT("unknown seek origin"));
408
409 case wxFromStart:
410 origin = SEEK_SET;
411 break;
412
413 case wxFromCurrent:
414 origin = SEEK_CUR;
415 break;
416
417 case wxFromEnd:
418 origin = SEEK_END;
419 break;
420 }
421
422 wxFileOffset iRc = wxSeek(m_fd, ofs, origin);
423 if ( CheckForError(iRc) )
424 {
425 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
426 }
427
428 return iRc;
429 }
430
431 // get current file offset
432 wxFileOffset wxFile::Tell() const
433 {
434 wxASSERT( IsOpened() );
435
436 wxFileOffset iRc = wxTell(m_fd);
437 if ( CheckForError(iRc) )
438 {
439 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
440 }
441
442 return iRc;
443 }
444
445 // get current file length
446 wxFileOffset wxFile::Length() const
447 {
448 wxASSERT( IsOpened() );
449
450 // we use a special method for Linux systems where files in sysfs (i.e.
451 // those under /sys typically) return length of 4096 bytes even when
452 // they're much smaller -- this is a problem as it results in errors later
453 // when we try reading 4KB from them
454 #ifdef __LINUX__
455 struct stat st;
456 if ( fstat(m_fd, &st) == 0 )
457 {
458 // returning 0 for the special files indicates to the caller that they
459 // are not seekable
460 return st.st_blocks ? st.st_size : 0;
461 }
462 //else: failed to stat, try the normal method
463 #endif // __LINUX__
464
465 wxFileOffset iRc = Tell();
466 if ( iRc != wxInvalidOffset ) {
467 wxFileOffset iLen = const_cast<wxFile *>(this)->SeekEnd();
468 if ( iLen != wxInvalidOffset ) {
469 // restore old position
470 if ( ((wxFile *)this)->Seek(iRc) == wxInvalidOffset ) {
471 // error
472 iLen = wxInvalidOffset;
473 }
474 }
475
476 iRc = iLen;
477 }
478
479 if ( iRc == wxInvalidOffset )
480 {
481 // last error was already set by Tell()
482 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
483 }
484
485 return iRc;
486 }
487
488 // is end of file reached?
489 bool wxFile::Eof() const
490 {
491 wxASSERT( IsOpened() );
492
493 wxFileOffset iRc;
494
495 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__)
496 // @@ this doesn't work, of course, on unseekable file descriptors
497 wxFileOffset ofsCur = Tell(),
498 ofsMax = Length();
499 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
500 iRc = wxInvalidOffset;
501 else
502 iRc = ofsCur == ofsMax;
503 #else // Windows and "native" compiler
504 iRc = wxEof(m_fd);
505 #endif // Windows/Unix
506
507 if ( iRc == 0 )
508 return false;
509
510 if ( iRc == wxInvalidOffset )
511 {
512 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
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