]>
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
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ----------------------------------------------------------------------------
14 // ----------------------------------------------------------------------------
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
26 #if defined(__WINDOWS__) && !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
28 #define WIN32_LEAN_AND_MEAN
49 #elif defined(__WINDOWS__) && defined(__WXWINCE__)
50 #include "wx/msw/missing.h"
51 #elif (defined(__OS2__))
53 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
58 #include "wx/msw/wrapwin.h"
60 #elif defined(__DOS__)
61 #if defined(__WATCOMC__)
63 #elif defined(__DJGPP__)
68 #error "Please specify the header with file functions declarations."
70 #elif (defined(__WXSTUBS__))
71 // Have to ifdef this for different environments
73 #elif (defined(__WXMAC__))
75 int access( const char *path
, int mode
) { return 0 ; }
77 int _access( const char *path
, int mode
) { return 0 ; }
79 char* mktemp( char * path
) { return path
;}
83 #error "Please specify the header with file functions declarations."
86 #include <stdio.h> // SEEK_xxx constants
92 // Windows compilers don't have these constants
96 F_OK
= 0, // test for existence
97 X_OK
= 1, // execute permission
105 #include "wx/string.h"
109 #endif // !WX_PRECOMP
111 #include "wx/filename.h"
113 #include "wx/filefn.h"
115 // there is no distinction between text and binary files under Unix, so define
116 // O_BINARY as 0 if the system headers don't do it already
117 #if defined(__UNIX__) && !defined(O_BINARY)
122 #include "wx/msw/mslu.h"
126 #include "wx/msw/private.h"
133 // ============================================================================
134 // implementation of wxFile
135 // ============================================================================
137 // ----------------------------------------------------------------------------
139 // ----------------------------------------------------------------------------
141 bool wxFile::Exists(const wxString
& name
)
143 return wxFileExists(name
);
146 bool wxFile::Access(const wxString
& name
, OpenMode mode
)
153 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
169 return wxAccess(name
, how
) == 0;
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
177 wxFile::wxFile(const wxString
& fileName
, OpenMode mode
)
182 Open(fileName
, mode
);
185 bool wxFile::CheckForError(wxFileOffset rc
) const
190 const_cast<wxFile
*>(this)->m_lasterror
=
201 // create the file, fail if it already exists and bOverwrite
202 bool wxFile::Create(const wxString
& fileName
, bool bOverwrite
, int accessMode
)
204 // if bOverwrite we create a new file or truncate the existing one,
205 // otherwise we only create the new file and fail if it already exists
206 int fildes
= wxOpen( fileName
,
207 O_BINARY
| O_WRONLY
| O_CREAT
|
208 (bOverwrite
? O_TRUNC
: O_EXCL
),
210 if ( CheckForError(fildes
) )
212 wxLogSysError(_("can't create file '%s'"), fileName
);
221 bool wxFile::Open(const wxString
& fileName
, OpenMode mode
, int accessMode
)
223 int flags
= O_BINARY
;
232 if ( wxFile::Exists(fileName
) )
234 flags
|= O_WRONLY
| O_APPEND
;
237 //else: fall through as write_append is the same as write if the
238 // file doesn't exist
241 flags
|= O_WRONLY
| O_CREAT
| O_TRUNC
;
245 flags
|= O_WRONLY
| O_CREAT
| O_EXCL
;
254 // only read/write bits for "all" are supported by this function under
255 // Windows, and VC++ 8 returns EINVAL if any other bits are used in
256 // accessMode, so clear them as they have at best no effect anyhow
257 accessMode
&= wxS_IRUSR
| wxS_IWUSR
;
258 #endif // __WINDOWS__
260 int fildes
= wxOpen( fileName
, flags
, accessMode
);
262 if ( CheckForError(fildes
) )
264 wxLogSysError(_("can't open file '%s'"), fileName
);
276 if ( CheckForError(wxClose(m_fd
)) )
278 wxLogSysError(_("can't close file descriptor %d"), m_fd
);
289 // ----------------------------------------------------------------------------
291 // ----------------------------------------------------------------------------
293 bool wxFile::ReadAll(wxString
*str
, const wxMBConv
& conv
)
295 wxCHECK_MSG( str
, false, wxS("Output string must be non-NULL") );
297 ssize_t length
= Length();
298 wxCHECK_MSG( (wxFileOffset
)length
== Length(), false, wxT("huge file not supported") );
300 wxCharBuffer
buf(length
);
301 char* p
= buf
.data();
304 static const ssize_t READSIZE
= 4096;
306 ssize_t nread
= Read(p
, length
> READSIZE
? READSIZE
: length
);
307 if ( nread
== wxInvalidOffset
)
311 if ( length
<= nread
)
319 wxString
strTmp(buf
, conv
);
326 ssize_t
wxFile::Read(void *pBuf
, size_t nCount
)
328 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
330 ssize_t iRc
= wxRead(m_fd
, pBuf
, nCount
);
332 if ( CheckForError(iRc
) )
334 wxLogSysError(_("can't read from file descriptor %d"), m_fd
);
335 return wxInvalidOffset
;
342 size_t wxFile::Write(const void *pBuf
, size_t nCount
)
344 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
346 ssize_t iRc
= wxWrite(m_fd
, pBuf
, nCount
);
348 if ( CheckForError(iRc
) )
350 wxLogSysError(_("can't write to file descriptor %d"), m_fd
);
357 bool wxFile::Write(const wxString
& s
, const wxMBConv
& conv
)
359 const wxWX2MBbuf buf
= s
.mb_str(conv
);
364 const size_t size
= buf
.length();
366 const size_t size
= s
.length();
369 return Write(buf
, size
) == size
;
376 // fsync() only works on disk files and returns errors for pipes, don't
378 if ( IsOpened() && GetKind() == wxFILE_KIND_DISK
)
380 if ( CheckForError(wxFsync(m_fd
)) )
382 wxLogSysError(_("can't flush file descriptor %d"), m_fd
);
391 // ----------------------------------------------------------------------------
393 // ----------------------------------------------------------------------------
396 wxFileOffset
wxFile::Seek(wxFileOffset ofs
, wxSeekMode mode
)
398 wxASSERT_MSG( IsOpened(), wxT("can't seek on closed file") );
399 wxCHECK_MSG( ofs
!= wxInvalidOffset
|| mode
!= wxFromStart
,
401 wxT("invalid absolute file offset") );
406 wxFAIL_MSG(wxT("unknown seek origin"));
421 wxFileOffset iRc
= wxSeek(m_fd
, ofs
, origin
);
422 if ( CheckForError(iRc
) )
424 wxLogSysError(_("can't seek on file descriptor %d"), m_fd
);
430 // get current file offset
431 wxFileOffset
wxFile::Tell() const
433 wxASSERT( IsOpened() );
435 wxFileOffset iRc
= wxTell(m_fd
);
436 if ( CheckForError(iRc
) )
438 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd
);
444 // get current file length
445 wxFileOffset
wxFile::Length() const
447 wxASSERT( IsOpened() );
449 // we use a special method for Linux systems where files in sysfs (i.e.
450 // those under /sys typically) return length of 4096 bytes even when
451 // they're much smaller -- this is a problem as it results in errors later
452 // when we try reading 4KB from them
455 if ( fstat(m_fd
, &st
) == 0 )
457 // returning 0 for the special files indicates to the caller that they
459 return st
.st_blocks
? st
.st_size
: 0;
461 //else: failed to stat, try the normal method
464 wxFileOffset iRc
= Tell();
465 if ( iRc
!= wxInvalidOffset
) {
466 wxFileOffset iLen
= const_cast<wxFile
*>(this)->SeekEnd();
467 if ( iLen
!= wxInvalidOffset
) {
468 // restore old position
469 if ( ((wxFile
*)this)->Seek(iRc
) == wxInvalidOffset
) {
471 iLen
= wxInvalidOffset
;
478 if ( iRc
== wxInvalidOffset
)
480 // last error was already set by Tell()
481 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd
);
487 // is end of file reached?
488 bool wxFile::Eof() const
490 wxASSERT( IsOpened() );
494 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__)
495 // @@ this doesn't work, of course, on unseekable file descriptors
496 wxFileOffset ofsCur
= Tell(),
498 if ( ofsCur
== wxInvalidOffset
|| ofsMax
== wxInvalidOffset
)
499 iRc
= wxInvalidOffset
;
501 iRc
= ofsCur
== ofsMax
;
502 #else // Windows and "native" compiler
504 #endif // Windows/Unix
509 if ( iRc
== wxInvalidOffset
)
511 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd
);
517 // ============================================================================
518 // implementation of wxTempFile
519 // ============================================================================
521 // ----------------------------------------------------------------------------
523 // ----------------------------------------------------------------------------
525 wxTempFile::wxTempFile(const wxString
& strName
)
530 bool wxTempFile::Open(const wxString
& strName
)
532 // we must have an absolute filename because otherwise CreateTempFileName()
533 // would create the temp file in $TMP (i.e. the system standard location
534 // for the temp files) which might be on another volume/drive/mount and
535 // wxRename()ing it later to m_strName from Commit() would then fail
537 // with the absolute filename, the temp file is created in the same
538 // directory as this one which ensures that wxRename() may work later
539 wxFileName
fn(strName
);
540 if ( !fn
.IsAbsolute() )
542 fn
.Normalize(wxPATH_NORM_ABSOLUTE
);
545 m_strName
= fn
.GetFullPath();
547 m_strTemp
= wxFileName::CreateTempFileName(m_strName
, &m_file
);
549 if ( m_strTemp
.empty() )
551 // CreateTempFileName() failed
556 // the temp file should have the same permissions as the original one
560 if ( stat( (const char*) m_strName
.fn_str(), &st
) == 0 )
566 // file probably didn't exist, just give it the default mode _using_
567 // user's umask (new files creation should respect umask)
568 mode_t mask
= umask(0777);
573 if ( chmod( (const char*) m_strTemp
.fn_str(), mode
) == -1 )
576 wxLogSysError(_("Failed to set temporary file permissions"));
584 // ----------------------------------------------------------------------------
586 // ----------------------------------------------------------------------------
588 wxTempFile::~wxTempFile()
594 bool wxTempFile::Commit()
598 if ( wxFile::Exists(m_strName
) && wxRemove(m_strName
) != 0 ) {
599 wxLogSysError(_("can't remove file '%s'"), m_strName
.c_str());
603 if ( !wxRenameFile(m_strTemp
, m_strName
) ) {
604 wxLogSysError(_("can't commit changes to file '%s'"), m_strName
.c_str());
611 void wxTempFile::Discard()
614 if ( wxRemove(m_strTemp
) != 0 )
616 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp
.c_str());