]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/file.cpp
updated setup.h for OpenVMS
[wxWidgets.git] / src / common / file.cpp
... / ...
CommitLineData
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
142bool wxFile::Exists(const wxString& name)
143{
144 return wxFileExists(name);
145}
146
147bool 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
178wxFile::wxFile(const wxString& fileName, OpenMode mode)
179{
180 m_fd = fd_invalid;
181 m_lasterror = 0;
182
183 Open(fileName, mode);
184}
185
186bool 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
203bool 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 fd = wxOpen( fileName,
208 O_BINARY | O_WRONLY | O_CREAT |
209 (bOverwrite ? O_TRUNC : O_EXCL),
210 accessMode );
211 if ( CheckForError(fd) )
212 {
213 wxLogSysError(_("can't create file '%s'"), fileName);
214 return false;
215 }
216
217 Attach(fd);
218 return true;
219}
220
221// open the file
222bool 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 fd = wxOpen( fileName, flags, accessMode);
262
263 if ( CheckForError(fd) )
264 {
265 wxLogSysError(_("can't open file '%s'"), fileName);
266 return false;
267 }
268
269 Attach(fd);
270 return true;
271}
272
273// close
274bool 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// read
295ssize_t wxFile::Read(void *pBuf, size_t nCount)
296{
297 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
298
299 ssize_t iRc = wxRead(m_fd, pBuf, nCount);
300
301 if ( CheckForError(iRc) )
302 {
303 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
304 return wxInvalidOffset;
305 }
306
307 return iRc;
308}
309
310// write
311size_t wxFile::Write(const void *pBuf, size_t nCount)
312{
313 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
314
315 ssize_t iRc = wxWrite(m_fd, pBuf, nCount);
316
317 if ( CheckForError(iRc) )
318 {
319 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
320 iRc = 0;
321 }
322
323 return iRc;
324}
325
326bool wxFile::Write(const wxString& s, const wxMBConv& conv)
327{
328 const wxWX2MBbuf buf = s.mb_str(conv);
329 if ( !buf )
330 return false;
331
332#if wxUSE_UNICODE
333 const size_t size = buf.length();
334#else
335 const size_t size = s.length();
336#endif
337
338 return Write(buf, size) == size;
339}
340
341// flush
342bool wxFile::Flush()
343{
344#ifdef HAVE_FSYNC
345 // fsync() only works on disk files and returns errors for pipes, don't
346 // call it then
347 if ( IsOpened() && GetKind() == wxFILE_KIND_DISK )
348 {
349 if ( CheckForError(wxFsync(m_fd)) )
350 {
351 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
352 return false;
353 }
354 }
355#endif // HAVE_FSYNC
356
357 return true;
358}
359
360// ----------------------------------------------------------------------------
361// seek
362// ----------------------------------------------------------------------------
363
364// seek
365wxFileOffset wxFile::Seek(wxFileOffset ofs, wxSeekMode mode)
366{
367 wxASSERT_MSG( IsOpened(), wxT("can't seek on closed file") );
368 wxCHECK_MSG( ofs != wxInvalidOffset || mode != wxFromStart,
369 wxInvalidOffset,
370 wxT("invalid absolute file offset") );
371
372 int origin;
373 switch ( mode ) {
374 default:
375 wxFAIL_MSG(wxT("unknown seek origin"));
376
377 case wxFromStart:
378 origin = SEEK_SET;
379 break;
380
381 case wxFromCurrent:
382 origin = SEEK_CUR;
383 break;
384
385 case wxFromEnd:
386 origin = SEEK_END;
387 break;
388 }
389
390 wxFileOffset iRc = wxSeek(m_fd, ofs, origin);
391 if ( CheckForError(iRc) )
392 {
393 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
394 }
395
396 return iRc;
397}
398
399// get current file offset
400wxFileOffset wxFile::Tell() const
401{
402 wxASSERT( IsOpened() );
403
404 wxFileOffset iRc = wxTell(m_fd);
405 if ( CheckForError(iRc) )
406 {
407 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
408 }
409
410 return iRc;
411}
412
413// get current file length
414wxFileOffset wxFile::Length() const
415{
416 wxASSERT( IsOpened() );
417
418 // we use a special method for Linux systems where files in sysfs (i.e.
419 // those under /sys typically) return length of 4096 bytes even when
420 // they're much smaller -- this is a problem as it results in errors later
421 // when we try reading 4KB from them
422#ifdef __LINUX__
423 struct stat st;
424 if ( fstat(m_fd, &st) == 0 )
425 {
426 // returning 0 for the special files indicates to the caller that they
427 // are not seekable
428 return st.st_blocks ? st.st_size : 0;
429 }
430 //else: failed to stat, try the normal method
431#endif // __LINUX__
432
433 wxFileOffset iRc = Tell();
434 if ( iRc != wxInvalidOffset ) {
435 wxFileOffset iLen = const_cast<wxFile *>(this)->SeekEnd();
436 if ( iLen != wxInvalidOffset ) {
437 // restore old position
438 if ( ((wxFile *)this)->Seek(iRc) == wxInvalidOffset ) {
439 // error
440 iLen = wxInvalidOffset;
441 }
442 }
443
444 iRc = iLen;
445 }
446
447 if ( iRc == wxInvalidOffset )
448 {
449 // last error was already set by Tell()
450 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
451 }
452
453 return iRc;
454}
455
456// is end of file reached?
457bool wxFile::Eof() const
458{
459 wxASSERT( IsOpened() );
460
461 wxFileOffset iRc;
462
463#if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__)
464 // @@ this doesn't work, of course, on unseekable file descriptors
465 wxFileOffset ofsCur = Tell(),
466 ofsMax = Length();
467 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
468 iRc = wxInvalidOffset;
469 else
470 iRc = ofsCur == ofsMax;
471#else // Windows and "native" compiler
472 iRc = wxEof(m_fd);
473#endif // Windows/Unix
474
475 if ( iRc == 0 )
476 return false;
477
478 if ( iRc == wxInvalidOffset )
479 {
480 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
481 }
482 else if ( iRc != 1 )
483 {
484 wxFAIL_MSG(wxT("invalid eof() return value."));
485 }
486
487 return true;
488}
489
490// ============================================================================
491// implementation of wxTempFile
492// ============================================================================
493
494// ----------------------------------------------------------------------------
495// construction
496// ----------------------------------------------------------------------------
497
498wxTempFile::wxTempFile(const wxString& strName)
499{
500 Open(strName);
501}
502
503bool wxTempFile::Open(const wxString& strName)
504{
505 // we must have an absolute filename because otherwise CreateTempFileName()
506 // would create the temp file in $TMP (i.e. the system standard location
507 // for the temp files) which might be on another volume/drive/mount and
508 // wxRename()ing it later to m_strName from Commit() would then fail
509 //
510 // with the absolute filename, the temp file is created in the same
511 // directory as this one which ensures that wxRename() may work later
512 wxFileName fn(strName);
513 if ( !fn.IsAbsolute() )
514 {
515 fn.Normalize(wxPATH_NORM_ABSOLUTE);
516 }
517
518 m_strName = fn.GetFullPath();
519
520 m_strTemp = wxFileName::CreateTempFileName(m_strName, &m_file);
521
522 if ( m_strTemp.empty() )
523 {
524 // CreateTempFileName() failed
525 return false;
526 }
527
528#ifdef __UNIX__
529 // the temp file should have the same permissions as the original one
530 mode_t mode;
531
532 wxStructStat st;
533 if ( stat( (const char*) m_strName.fn_str(), &st) == 0 )
534 {
535 mode = st.st_mode;
536 }
537 else
538 {
539 // file probably didn't exist, just give it the default mode _using_
540 // user's umask (new files creation should respect umask)
541 mode_t mask = umask(0777);
542 mode = 0666 & ~mask;
543 umask(mask);
544 }
545
546 if ( chmod( (const char*) m_strTemp.fn_str(), mode) == -1 )
547 {
548#ifndef __OS2__
549 wxLogSysError(_("Failed to set temporary file permissions"));
550#endif
551 }
552#endif // Unix
553
554 return true;
555}
556
557// ----------------------------------------------------------------------------
558// destruction
559// ----------------------------------------------------------------------------
560
561wxTempFile::~wxTempFile()
562{
563 if ( IsOpened() )
564 Discard();
565}
566
567bool wxTempFile::Commit()
568{
569 m_file.Close();
570
571 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
572 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
573 return false;
574 }
575
576 if ( !wxRenameFile(m_strTemp, m_strName) ) {
577 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
578 return false;
579 }
580
581 return true;
582}
583
584void wxTempFile::Discard()
585{
586 m_file.Close();
587 if ( wxRemove(m_strTemp) != 0 )
588 {
589 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
590 }
591}
592
593#endif // wxUSE_FILE
594