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