]>
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
95 // Windows compilers don't have these constants
99 F_OK
= 0, // test for existence
100 X_OK
= 1, // execute permission
108 #include "wx/string.h"
112 #endif // !WX_PRECOMP
114 #include "wx/filename.h"
116 #include "wx/filefn.h"
118 // there is no distinction between text and binary files under Unix, so define
119 // O_BINARY as 0 if the system headers don't do it already
120 #if defined(__UNIX__) && !defined(O_BINARY)
125 #include "wx/msw/mslu.h"
129 #include "wx/msw/private.h"
136 // ============================================================================
137 // implementation of wxFile
138 // ============================================================================
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
144 bool wxFile::Exists(const wxString
& name
)
146 return wxFileExists(name
);
149 bool wxFile::Access(const wxString
& name
, OpenMode mode
)
156 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
172 return wxAccess(name
, how
) == 0;
175 // ----------------------------------------------------------------------------
177 // ----------------------------------------------------------------------------
180 wxFile::wxFile(const wxString
& fileName
, OpenMode mode
)
185 Open(fileName
, mode
);
188 bool wxFile::CheckForError(wxFileOffset rc
) const
193 const_cast<wxFile
*>(this)->m_lasterror
=
204 // create the file, fail if it already exists and bOverwrite
205 bool wxFile::Create(const wxString
& fileName
, bool bOverwrite
, int accessMode
)
207 // if bOverwrite we create a new file or truncate the existing one,
208 // otherwise we only create the new file and fail if it already exists
209 int fd
= wxOpen( fileName
,
210 O_BINARY
| O_WRONLY
| O_CREAT
|
211 (bOverwrite
? O_TRUNC
: O_EXCL
),
213 if ( CheckForError(fd
) )
215 wxLogSysError(_("can't create file '%s'"), fileName
);
224 bool wxFile::Open(const wxString
& fileName
, OpenMode mode
, int accessMode
)
226 int flags
= O_BINARY
;
235 if ( wxFile::Exists(fileName
) )
237 flags
|= O_WRONLY
| O_APPEND
;
240 //else: fall through as write_append is the same as write if the
241 // file doesn't exist
244 flags
|= O_WRONLY
| O_CREAT
| O_TRUNC
;
248 flags
|= O_WRONLY
| O_CREAT
| O_EXCL
;
257 // only read/write bits for "all" are supported by this function under
258 // Windows, and VC++ 8 returns EINVAL if any other bits are used in
259 // accessMode, so clear them as they have at best no effect anyhow
260 accessMode
&= wxS_IRUSR
| wxS_IWUSR
;
261 #endif // __WINDOWS__
263 int fd
= wxOpen( fileName
, flags
, accessMode
);
265 if ( CheckForError(fd
) )
267 wxLogSysError(_("can't open file '%s'"), fileName
);
279 if ( CheckForError(wxClose(m_fd
)) )
281 wxLogSysError(_("can't close file descriptor %d"), m_fd
);
292 // ----------------------------------------------------------------------------
294 // ----------------------------------------------------------------------------
297 ssize_t
wxFile::Read(void *pBuf
, size_t nCount
)
299 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
301 ssize_t iRc
= wxRead(m_fd
, pBuf
, nCount
);
303 if ( CheckForError(iRc
) )
305 wxLogSysError(_("can't read from file descriptor %d"), m_fd
);
306 return wxInvalidOffset
;
313 size_t wxFile::Write(const void *pBuf
, size_t nCount
)
315 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
317 ssize_t iRc
= wxWrite(m_fd
, pBuf
, nCount
);
319 if ( CheckForError(iRc
) )
321 wxLogSysError(_("can't write to file descriptor %d"), m_fd
);
328 bool wxFile::Write(const wxString
& s
, const wxMBConv
& conv
)
330 const wxWX2MBbuf buf
= s
.mb_str(conv
);
335 const size_t size
= buf
.length();
337 const size_t size
= s
.length();
340 return Write(buf
, size
) == size
;
347 // fsync() only works on disk files and returns errors for pipes, don't
349 if ( IsOpened() && GetKind() == wxFILE_KIND_DISK
)
351 if ( CheckForError(wxFsync(m_fd
)) )
353 wxLogSysError(_("can't flush file descriptor %d"), m_fd
);
362 // ----------------------------------------------------------------------------
364 // ----------------------------------------------------------------------------
367 wxFileOffset
wxFile::Seek(wxFileOffset ofs
, wxSeekMode mode
)
369 wxASSERT_MSG( IsOpened(), wxT("can't seek on closed file") );
370 wxCHECK_MSG( ofs
!= wxInvalidOffset
|| mode
!= wxFromStart
,
372 wxT("invalid absolute file offset") );
377 wxFAIL_MSG(wxT("unknown seek origin"));
392 wxFileOffset iRc
= wxSeek(m_fd
, ofs
, origin
);
393 if ( CheckForError(iRc
) )
395 wxLogSysError(_("can't seek on file descriptor %d"), m_fd
);
401 // get current file offset
402 wxFileOffset
wxFile::Tell() const
404 wxASSERT( IsOpened() );
406 wxFileOffset iRc
= wxTell(m_fd
);
407 if ( CheckForError(iRc
) )
409 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd
);
415 // get current file length
416 wxFileOffset
wxFile::Length() const
418 wxASSERT( IsOpened() );
420 // we use a special method for Linux systems where files in sysfs (i.e.
421 // those under /sys typically) return length of 4096 bytes even when
422 // they're much smaller -- this is a problem as it results in errors later
423 // when we try reading 4KB from them
426 if ( fstat(m_fd
, &st
) == 0 )
428 // returning 0 for the special files indicates to the caller that they
430 return st
.st_blocks
? st
.st_size
: 0;
432 //else: failed to stat, try the normal method
435 wxFileOffset iRc
= Tell();
436 if ( iRc
!= wxInvalidOffset
) {
437 wxFileOffset iLen
= const_cast<wxFile
*>(this)->SeekEnd();
438 if ( iLen
!= wxInvalidOffset
) {
439 // restore old position
440 if ( ((wxFile
*)this)->Seek(iRc
) == wxInvalidOffset
) {
442 iLen
= wxInvalidOffset
;
449 if ( iRc
== wxInvalidOffset
)
451 // last error was already set by Tell()
452 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd
);
458 // is end of file reached?
459 bool wxFile::Eof() const
461 wxASSERT( IsOpened() );
465 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ )
466 // @@ this doesn't work, of course, on unseekable file descriptors
467 wxFileOffset ofsCur
= Tell(),
469 if ( ofsCur
== wxInvalidOffset
|| ofsMax
== wxInvalidOffset
)
470 iRc
= wxInvalidOffset
;
472 iRc
= ofsCur
== ofsMax
;
473 #else // Windows and "native" compiler
475 #endif // Windows/Unix
480 if ( iRc
== wxInvalidOffset
)
482 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd
);
486 wxFAIL_MSG(wxT("invalid eof() return value."));
492 // ============================================================================
493 // implementation of wxTempFile
494 // ============================================================================
496 // ----------------------------------------------------------------------------
498 // ----------------------------------------------------------------------------
500 wxTempFile::wxTempFile(const wxString
& strName
)
505 bool wxTempFile::Open(const wxString
& strName
)
507 // we must have an absolute filename because otherwise CreateTempFileName()
508 // would create the temp file in $TMP (i.e. the system standard location
509 // for the temp files) which might be on another volume/drive/mount and
510 // wxRename()ing it later to m_strName from Commit() would then fail
512 // with the absolute filename, the temp file is created in the same
513 // directory as this one which ensures that wxRename() may work later
514 wxFileName
fn(strName
);
515 if ( !fn
.IsAbsolute() )
517 fn
.Normalize(wxPATH_NORM_ABSOLUTE
);
520 m_strName
= fn
.GetFullPath();
522 m_strTemp
= wxFileName::CreateTempFileName(m_strName
, &m_file
);
524 if ( m_strTemp
.empty() )
526 // CreateTempFileName() failed
531 // the temp file should have the same permissions as the original one
535 if ( stat( (const char*) m_strName
.fn_str(), &st
) == 0 )
541 // file probably didn't exist, just give it the default mode _using_
542 // user's umask (new files creation should respect umask)
543 mode_t mask
= umask(0777);
548 if ( chmod( (const char*) m_strTemp
.fn_str(), mode
) == -1 )
551 wxLogSysError(_("Failed to set temporary file permissions"));
559 // ----------------------------------------------------------------------------
561 // ----------------------------------------------------------------------------
563 wxTempFile::~wxTempFile()
569 bool wxTempFile::Commit()
573 if ( wxFile::Exists(m_strName
) && wxRemove(m_strName
) != 0 ) {
574 wxLogSysError(_("can't remove file '%s'"), m_strName
.c_str());
578 if ( !wxRenameFile(m_strTemp
, m_strName
) ) {
579 wxLogSysError(_("can't commit changes to file '%s'"), m_strName
.c_str());
586 void wxTempFile::Discard()
589 if ( wxRemove(m_strTemp
) != 0 )
591 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp
.c_str());