]>
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(__WINDOWS__) && !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
29 #define WIN32_LEAN_AND_MEAN
50 #elif defined(__WINDOWS__) && 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
;}
84 #error "Please specify the header with file functions declarations."
87 #include <stdio.h> // SEEK_xxx constants
93 // Windows compilers don't have these constants
97 F_OK
= 0, // test for existence
98 X_OK
= 1, // execute permission
106 #include "wx/string.h"
110 #endif // !WX_PRECOMP
112 #include "wx/filename.h"
114 #include "wx/filefn.h"
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)
123 #include "wx/msw/mslu.h"
127 #include "wx/msw/private.h"
134 // ============================================================================
135 // implementation of wxFile
136 // ============================================================================
138 // ----------------------------------------------------------------------------
140 // ----------------------------------------------------------------------------
142 bool wxFile::Exists(const wxString
& name
)
144 return wxFileExists(name
);
147 bool wxFile::Access(const wxString
& name
, OpenMode mode
)
154 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
170 return wxAccess(name
, how
) == 0;
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
178 wxFile::wxFile(const wxString
& fileName
, OpenMode mode
)
183 Open(fileName
, mode
);
186 bool wxFile::CheckForError(wxFileOffset rc
) const
191 const_cast<wxFile
*>(this)->m_lasterror
=
202 // create the file, fail if it already exists and bOverwrite
203 bool wxFile::Create(const wxString
& fileName
, bool bOverwrite
, int accessMode
)
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
),
211 if ( CheckForError(fildes
) )
213 wxLogSysError(_("can't create file '%s'"), fileName
);
222 bool wxFile::Open(const wxString
& fileName
, OpenMode mode
, int accessMode
)
224 int flags
= O_BINARY
;
233 if ( wxFile::Exists(fileName
) )
235 flags
|= O_WRONLY
| O_APPEND
;
238 //else: fall through as write_append is the same as write if the
239 // file doesn't exist
242 flags
|= O_WRONLY
| O_CREAT
| O_TRUNC
;
246 flags
|= O_WRONLY
| O_CREAT
| O_EXCL
;
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__
261 int fildes
= wxOpen( fileName
, flags
, accessMode
);
263 if ( CheckForError(fildes
) )
265 wxLogSysError(_("can't open file '%s'"), fileName
);
277 if ( CheckForError(wxClose(m_fd
)) )
279 wxLogSysError(_("can't close file descriptor %d"), m_fd
);
290 // ----------------------------------------------------------------------------
292 // ----------------------------------------------------------------------------
294 bool wxFile::ReadAll(wxString
*str
, const wxMBConv
& conv
)
296 wxCHECK_MSG( str
, false, wxS("Output string must be non-NULL") );
298 ssize_t length
= Length();
299 wxCHECK_MSG( (wxFileOffset
)length
== Length(), false, wxT("huge file not supported") );
301 wxCharBuffer
buf(length
);
302 char* p
= buf
.data();
305 static const unsigned READSIZE
= 4096;
307 ssize_t nread
= Read(p
, length
> READSIZE
? READSIZE
: length
);
308 if ( nread
== wxInvalidOffset
)
312 if ( length
<= nread
)
320 wxString
strTmp(buf
, conv
);
327 ssize_t
wxFile::Read(void *pBuf
, size_t nCount
)
329 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
331 ssize_t iRc
= wxRead(m_fd
, pBuf
, nCount
);
333 if ( CheckForError(iRc
) )
335 wxLogSysError(_("can't read from file descriptor %d"), m_fd
);
336 return wxInvalidOffset
;
343 size_t wxFile::Write(const void *pBuf
, size_t nCount
)
345 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
347 ssize_t iRc
= wxWrite(m_fd
, pBuf
, nCount
);
349 if ( CheckForError(iRc
) )
351 wxLogSysError(_("can't write to file descriptor %d"), m_fd
);
358 bool wxFile::Write(const wxString
& s
, const wxMBConv
& conv
)
360 const wxWX2MBbuf buf
= s
.mb_str(conv
);
365 const size_t size
= buf
.length();
367 const size_t size
= s
.length();
370 return Write(buf
, size
) == size
;
377 // fsync() only works on disk files and returns errors for pipes, don't
379 if ( IsOpened() && GetKind() == wxFILE_KIND_DISK
)
381 if ( CheckForError(wxFsync(m_fd
)) )
383 wxLogSysError(_("can't flush file descriptor %d"), m_fd
);
392 // ----------------------------------------------------------------------------
394 // ----------------------------------------------------------------------------
397 wxFileOffset
wxFile::Seek(wxFileOffset ofs
, wxSeekMode mode
)
399 wxASSERT_MSG( IsOpened(), wxT("can't seek on closed file") );
400 wxCHECK_MSG( ofs
!= wxInvalidOffset
|| mode
!= wxFromStart
,
402 wxT("invalid absolute file offset") );
407 wxFAIL_MSG(wxT("unknown seek origin"));
422 wxFileOffset iRc
= wxSeek(m_fd
, ofs
, origin
);
423 if ( CheckForError(iRc
) )
425 wxLogSysError(_("can't seek on file descriptor %d"), m_fd
);
431 // get current file offset
432 wxFileOffset
wxFile::Tell() const
434 wxASSERT( IsOpened() );
436 wxFileOffset iRc
= wxTell(m_fd
);
437 if ( CheckForError(iRc
) )
439 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd
);
445 // get current file length
446 wxFileOffset
wxFile::Length() const
448 wxASSERT( IsOpened() );
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
456 if ( fstat(m_fd
, &st
) == 0 )
458 // returning 0 for the special files indicates to the caller that they
460 return st
.st_blocks
? st
.st_size
: 0;
462 //else: failed to stat, try the normal method
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
) {
472 iLen
= wxInvalidOffset
;
479 if ( iRc
== wxInvalidOffset
)
481 // last error was already set by Tell()
482 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd
);
488 // is end of file reached?
489 bool wxFile::Eof() const
491 wxASSERT( IsOpened() );
495 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__)
496 // @@ this doesn't work, of course, on unseekable file descriptors
497 wxFileOffset ofsCur
= Tell(),
499 if ( ofsCur
== wxInvalidOffset
|| ofsMax
== wxInvalidOffset
)
500 iRc
= wxInvalidOffset
;
502 iRc
= ofsCur
== ofsMax
;
503 #else // Windows and "native" compiler
505 #endif // Windows/Unix
510 if ( iRc
== wxInvalidOffset
)
512 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd
);
516 wxFAIL_MSG(wxT("invalid eof() return value."));
522 // ============================================================================
523 // implementation of wxTempFile
524 // ============================================================================
526 // ----------------------------------------------------------------------------
528 // ----------------------------------------------------------------------------
530 wxTempFile::wxTempFile(const wxString
& strName
)
535 bool wxTempFile::Open(const wxString
& strName
)
537 // we must have an absolute filename because otherwise CreateTempFileName()
538 // would create the temp file in $TMP (i.e. the system standard location
539 // for the temp files) which might be on another volume/drive/mount and
540 // wxRename()ing it later to m_strName from Commit() would then fail
542 // with the absolute filename, the temp file is created in the same
543 // directory as this one which ensures that wxRename() may work later
544 wxFileName
fn(strName
);
545 if ( !fn
.IsAbsolute() )
547 fn
.Normalize(wxPATH_NORM_ABSOLUTE
);
550 m_strName
= fn
.GetFullPath();
552 m_strTemp
= wxFileName::CreateTempFileName(m_strName
, &m_file
);
554 if ( m_strTemp
.empty() )
556 // CreateTempFileName() failed
561 // the temp file should have the same permissions as the original one
565 if ( stat( (const char*) m_strName
.fn_str(), &st
) == 0 )
571 // file probably didn't exist, just give it the default mode _using_
572 // user's umask (new files creation should respect umask)
573 mode_t mask
= umask(0777);
578 if ( chmod( (const char*) m_strTemp
.fn_str(), mode
) == -1 )
581 wxLogSysError(_("Failed to set temporary file permissions"));
589 // ----------------------------------------------------------------------------
591 // ----------------------------------------------------------------------------
593 wxTempFile::~wxTempFile()
599 bool wxTempFile::Commit()
603 if ( wxFile::Exists(m_strName
) && wxRemove(m_strName
) != 0 ) {
604 wxLogSysError(_("can't remove file '%s'"), m_strName
.c_str());
608 if ( !wxRenameFile(m_strTemp
, m_strName
) ) {
609 wxLogSysError(_("can't commit changes to file '%s'"), m_strName
.c_str());
616 void wxTempFile::Discard()
619 if ( wxRemove(m_strTemp
) != 0 )
621 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp
.c_str());