]>
git.saurik.com Git - wxWidgets.git/blob - src/common/file.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/file.cpp
3 // Purpose: wxFile - encapsulates low-level "file descriptor"
5 // Author: Vadim Zeitlin
9 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 // ----------------------------------------------------------------------------
15 // ----------------------------------------------------------------------------
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
27 #if defined(__WXMSW__) && !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
29 #define WIN32_LEAN_AND_MEAN
50 #elif defined(__WXMSW__) && defined(__WXWINCE__)
51 #include "wx/msw/missing.h"
52 #elif (defined(__OS2__))
54 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
59 #include "wx/msw/wrapwin.h"
61 #elif defined(__DOS__)
62 #if defined(__WATCOMC__)
64 #elif defined(__DJGPP__)
69 #error "Please specify the header with file functions declarations."
71 #elif (defined(__WXSTUBS__))
72 // Have to ifdef this for different environments
74 #elif (defined(__WXMAC__))
76 int access( const char *path
, int mode
) { return 0 ; }
78 int _access( const char *path
, int mode
) { return 0 ; }
80 char* mktemp( char * path
) { return path
;}
83 #elif defined(__WXPALMOS__)
84 #include "wx/palmos/missing.h"
86 #error "Please specify the header with file functions declarations."
89 #include <stdio.h> // SEEK_xxx constants
91 // Windows compilers don't have these constants
95 F_OK
= 0, // test for existence
96 X_OK
= 1, // execute permission
104 #include "wx/string.h"
108 #endif // !WX_PRECOMP
110 #include "wx/filename.h"
112 #include "wx/filefn.h"
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)
121 #include "wx/msw/mslu.h"
125 #include "wx/msw/private.h"
132 // ============================================================================
133 // implementation of wxFile
134 // ============================================================================
136 // ----------------------------------------------------------------------------
138 // ----------------------------------------------------------------------------
140 bool wxFile::Exists(const wxString
& name
)
142 return wxFileExists(name
);
145 bool wxFile::Access(const wxString
& name
, OpenMode mode
)
152 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
168 return wxAccess(name
, how
) == 0;
171 // ----------------------------------------------------------------------------
173 // ----------------------------------------------------------------------------
176 wxFile::wxFile(const wxString
& fileName
, OpenMode mode
)
181 Open(fileName
, mode
);
184 // create the file, fail if it already exists and bOverwrite
185 bool wxFile::Create(const wxString
& fileName
, bool bOverwrite
, int accessMode
)
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
),
195 wxLogSysError(_("can't create file '%s'"), fileName
);
204 bool wxFile::Open(const wxString
& fileName
, OpenMode mode
, int accessMode
)
206 int flags
= O_BINARY
;
215 if ( wxFile::Exists(fileName
) )
217 flags
|= O_WRONLY
| O_APPEND
;
220 //else: fall through as write_append is the same as write if the
221 // file doesn't exist
224 flags
|= O_WRONLY
| O_CREAT
| O_TRUNC
;
228 flags
|= O_WRONLY
| O_CREAT
| O_EXCL
;
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__
243 int fd
= wxOpen( fileName
, flags
, accessMode
);
247 wxLogSysError(_("can't open file '%s'"), fileName
);
259 if (wxClose(m_fd
) == -1)
261 wxLogSysError(_("can't close file descriptor %d"), m_fd
);
272 // ----------------------------------------------------------------------------
274 // ----------------------------------------------------------------------------
277 ssize_t
wxFile::Read(void *pBuf
, size_t nCount
)
279 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
281 ssize_t iRc
= wxRead(m_fd
, pBuf
, nCount
);
285 wxLogSysError(_("can't read from file descriptor %d"), m_fd
);
286 return wxInvalidOffset
;
293 size_t wxFile::Write(const void *pBuf
, size_t nCount
)
295 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
297 ssize_t iRc
= wxWrite(m_fd
, pBuf
, nCount
);
301 wxLogSysError(_("can't write to file descriptor %d"), m_fd
);
309 bool wxFile::Write(const wxString
& s
, const wxMBConv
& conv
)
311 const wxWX2MBbuf buf
= s
.mb_str(conv
);
315 const size_t size
= strlen(buf
); // FIXME: use buf.length() when available
316 return Write(buf
, size
) == size
;
323 // fsync() only works on disk files and returns errors for pipes, don't
325 if ( IsOpened() && GetKind() == wxFILE_KIND_DISK
)
327 if ( wxFsync(m_fd
) == -1 )
329 wxLogSysError(_("can't flush file descriptor %d"), m_fd
);
338 // ----------------------------------------------------------------------------
340 // ----------------------------------------------------------------------------
343 wxFileOffset
wxFile::Seek(wxFileOffset ofs
, wxSeekMode mode
)
345 wxASSERT_MSG( IsOpened(), _T("can't seek on closed file") );
346 wxCHECK_MSG( ofs
!= wxInvalidOffset
|| mode
!= wxFromStart
,
348 _T("invalid absolute file offset") );
353 wxFAIL_MSG(_T("unknown seek origin"));
368 wxFileOffset iRc
= wxSeek(m_fd
, ofs
, origin
);
369 if ( iRc
== wxInvalidOffset
)
371 wxLogSysError(_("can't seek on file descriptor %d"), m_fd
);
377 // get current file offset
378 wxFileOffset
wxFile::Tell() const
380 wxASSERT( IsOpened() );
382 wxFileOffset iRc
= wxTell(m_fd
);
383 if ( iRc
== wxInvalidOffset
)
385 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd
);
391 // get current file length
392 wxFileOffset
wxFile::Length() const
394 wxASSERT( IsOpened() );
396 // we use a special method for Linux systems where files in sysfs (i.e.
397 // those under /sys typically) return length of 4096 bytes even when
398 // they're much smaller -- this is a problem as it results in errors later
399 // when we try reading 4KB from them
402 if ( fstat(m_fd
, &st
) == 0 )
404 // returning 0 for the special files indicates to the caller that they
406 return st
.st_blocks
? st
.st_size
: 0;
408 //else: failed to stat, try the normal method
411 wxFileOffset iRc
= Tell();
412 if ( iRc
!= wxInvalidOffset
) {
413 // have to use const_cast :-(
414 wxFileOffset iLen
= ((wxFile
*)this)->SeekEnd();
415 if ( iLen
!= wxInvalidOffset
) {
416 // restore old position
417 if ( ((wxFile
*)this)->Seek(iRc
) == wxInvalidOffset
) {
419 iLen
= wxInvalidOffset
;
426 if ( iRc
== wxInvalidOffset
)
428 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd
);
434 // is end of file reached?
435 bool wxFile::Eof() const
437 wxASSERT( IsOpened() );
441 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ )
442 // @@ this doesn't work, of course, on unseekable file descriptors
443 wxFileOffset ofsCur
= Tell(),
445 if ( ofsCur
== wxInvalidOffset
|| ofsMax
== wxInvalidOffset
)
446 iRc
= wxInvalidOffset
;
448 iRc
= ofsCur
== ofsMax
;
449 #else // Windows and "native" compiler
451 #endif // Windows/Unix
457 else if ( iRc
== wxInvalidOffset
)
458 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd
);
460 wxFAIL_MSG(_T("invalid eof() return value."));
465 // ============================================================================
466 // implementation of wxTempFile
467 // ============================================================================
469 // ----------------------------------------------------------------------------
471 // ----------------------------------------------------------------------------
473 wxTempFile::wxTempFile(const wxString
& strName
)
478 bool wxTempFile::Open(const wxString
& strName
)
480 // we must have an absolute filename because otherwise CreateTempFileName()
481 // would create the temp file in $TMP (i.e. the system standard location
482 // for the temp files) which might be on another volume/drive/mount and
483 // wxRename()ing it later to m_strName from Commit() would then fail
485 // with the absolute filename, the temp file is created in the same
486 // directory as this one which ensures that wxRename() may work later
487 wxFileName
fn(strName
);
488 if ( !fn
.IsAbsolute() )
490 fn
.Normalize(wxPATH_NORM_ABSOLUTE
);
493 m_strName
= fn
.GetFullPath();
495 m_strTemp
= wxFileName::CreateTempFileName(m_strName
, &m_file
);
497 if ( m_strTemp
.empty() )
499 // CreateTempFileName() failed
504 // the temp file should have the same permissions as the original one
508 if ( stat( (const char*) m_strName
.fn_str(), &st
) == 0 )
514 // file probably didn't exist, just give it the default mode _using_
515 // user's umask (new files creation should respect umask)
516 mode_t mask
= umask(0777);
521 if ( chmod( (const char*) m_strTemp
.fn_str(), mode
) == -1 )
524 wxLogSysError(_("Failed to set temporary file permissions"));
532 // ----------------------------------------------------------------------------
534 // ----------------------------------------------------------------------------
536 wxTempFile::~wxTempFile()
542 bool wxTempFile::Commit()
546 if ( wxFile::Exists(m_strName
) && wxRemove(m_strName
) != 0 ) {
547 wxLogSysError(_("can't remove file '%s'"), m_strName
.c_str());
551 if ( !wxRenameFile(m_strTemp
, m_strName
) ) {
552 wxLogSysError(_("can't commit changes to file '%s'"), m_strName
.c_str());
559 void wxTempFile::Discard()
562 if ( wxRemove(m_strTemp
) != 0 )
564 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp
.c_str());