]>
git.saurik.com Git - wxWidgets.git/blob - src/common/file.cpp
1 /////////////////////////////////////////////////////////////////////////////
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 /////////////////////////////////////////////////////////////////////////////
14 TODO: remove all the WinCE ugliness from here, implement the wxOpen(),
15 wxSeek(), ... functions in a separate file for WinCE instead!!!
18 // ----------------------------------------------------------------------------
20 // ----------------------------------------------------------------------------
22 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
23 #pragma implementation "file.h"
26 // For compilers that support precompilation, includes "wx.h".
27 #include "wx/wxprec.h"
36 #if defined(__WXMSW__) && !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
40 #define WIN32_LEAN_AND_MEAN
62 #elif defined(__WXMSW__) && defined(__WXWINCE__)
63 // TODO: what to include?
64 #elif (defined(__OS2__))
66 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
71 #include "wx/msw/wrapwin.h"
73 #elif defined(__DOS__)
74 #if defined(__WATCOMC__)
76 #elif defined(__DJGPP__)
81 #error "Please specify the header with file functions declarations."
83 #elif (defined(__WXSTUBS__))
84 // Have to ifdef this for different environments
86 #elif (defined(__WXMAC__))
88 int access( const char *path
, int mode
) { return 0 ; }
90 int _access( const char *path
, int mode
) { return 0 ; }
92 char* mktemp( char * path
) { return path
;}
96 #error "Please specify the header with file functions declarations."
99 #include <stdio.h> // SEEK_xxx constants
102 #include <fcntl.h> // O_RDONLY &c
107 #elif !defined(__MWERKS__)
108 #include <sys/types.h> // needed for stat
109 #include <sys/stat.h> // stat
110 #elif defined(__MWERKS__) && ( defined(__WXMSW__) || defined(__MACH__) )
111 #include <sys/types.h> // needed for stat
112 #include <sys/stat.h> // stat
115 // Windows compilers don't have these constants
119 F_OK
= 0, // test for existence
120 X_OK
= 1, // execute permission
126 // there is no distinction between text and binary files under Unix, so define
127 // O_BINARY as 0 if the system headers don't do it already
128 #if defined(__UNIX__) && !defined(O_BINARY)
140 // some broken compilers don't have 3rd argument in open() and creat()
142 #define ACCESS(access)
144 #else // normal compiler
145 #define ACCESS(access) , (access)
150 #include "wx/string.h"
153 #endif // !WX_PRECOMP
155 #include "wx/filename.h"
157 #include "wx/filefn.h"
160 #include "wx/msw/mslu.h"
164 #include "wx/msw/private.h"
167 // ============================================================================
168 // implementation of wxFile
169 // ============================================================================
171 // ----------------------------------------------------------------------------
173 // ----------------------------------------------------------------------------
175 bool wxFile::Exists(const wxChar
*name
)
177 return wxFileExists(name
);
180 bool wxFile::Access(const wxChar
*name
, OpenMode mode
)
187 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
204 // FIXME: use CreateFile with 0 access to query the file
207 return wxAccess(name
, how
) == 0;
211 // ----------------------------------------------------------------------------
213 // ----------------------------------------------------------------------------
216 wxFile::wxFile(const wxChar
*szFileName
, OpenMode mode
)
221 Open(szFileName
, mode
);
224 // create the file, fail if it already exists and bOverwrite
225 bool wxFile::Create(const wxChar
*szFileName
, bool bOverwrite
, int accessMode
)
227 // if bOverwrite we create a new file or truncate the existing one,
228 // otherwise we only create the new file and fail if it already exists
229 #if defined(__WXMAC__) && !defined(__UNIX__) && !wxUSE_UNICODE
230 // Dominic Mazzoni [dmazzoni+@cs.cmu.edu] reports that open is still broken on the mac, so we replace
231 // int fd = open( szFileName , O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
232 int fd
= creat( szFileName
, accessMode
);
235 HANDLE fileHandle
= ::CreateFile(szFileName
, GENERIC_WRITE
, 0, NULL
,
236 bOverwrite
? CREATE_ALWAYS
: CREATE_NEW
, FILE_ATTRIBUTE_NORMAL
,
239 if (fileHandle
== INVALID_HANDLE_VALUE
)
240 fd
= (int) fileHandle
;
244 int fd
= wxOpen( szFileName
,
245 O_BINARY
| O_WRONLY
| O_CREAT
|
246 (bOverwrite
? O_TRUNC
: O_EXCL
)
247 ACCESS(accessMode
) );
252 wxLogSysError(_("can't create file '%s'"), szFileName
);
263 bool wxFile::Open(const wxChar
*szFileName
, OpenMode mode
, int accessMode
)
268 DWORD disposition
= 0;
273 access
= GENERIC_READ
;
274 shareMode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
275 disposition
= OPEN_EXISTING
;
279 if ( wxFile::Exists(szFileName
) )
281 access
= GENERIC_READ
|GENERIC_WRITE
;
282 shareMode
= FILE_SHARE_READ
;
286 //else: fall through as write_append is the same as write if the
287 // file doesn't exist
290 access
= GENERIC_WRITE
;
292 disposition
= TRUNCATE_EXISTING
;
296 access
= GENERIC_WRITE
;
298 disposition
= TRUNCATE_EXISTING
;
302 access
= GENERIC_READ
|GENERIC_WRITE
;
309 HANDLE fileHandle
= ::CreateFile(szFileName
, access
, shareMode
, NULL
,
310 disposition
, FILE_ATTRIBUTE_NORMAL
, 0);
311 if (fileHandle
== INVALID_HANDLE_VALUE
)
314 fd
= (int) fileHandle
;
316 int flags
= O_BINARY
;
325 if ( wxFile::Exists(szFileName
) )
327 flags
|= O_WRONLY
| O_APPEND
;
330 //else: fall through as write_append is the same as write if the
331 // file doesn't exist
334 flags
|= O_WRONLY
| O_CREAT
| O_TRUNC
;
338 flags
|= O_WRONLY
| O_CREAT
| O_EXCL
;
347 // only read/write bits for "all" are supported by this function under
348 // Windows, and VC++ 8 returns EINVAL if any other bits are used in
349 // accessMode, so clear them as they have at best no effect anyhow
350 accessMode
&= wxS_IRUSR
| wxS_IWUSR
;
351 #endif // __WINDOWS__
353 int fd
= wxOpen( szFileName
, flags
ACCESS(accessMode
));
357 wxLogSysError(_("can't open file '%s'"), szFileName
);
371 if (!CloseHandle((HANDLE
) m_fd
))
373 if ( close(m_fd
) == -1 )
376 wxLogSysError(_("can't close file descriptor %d"), m_fd
);
387 // ----------------------------------------------------------------------------
389 // ----------------------------------------------------------------------------
392 off_t
wxFile::Read(void *pBuf
, off_t nCount
)
394 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
399 if (ReadFile((HANDLE
) m_fd
, pBuf
, (DWORD
) nCount
, & bytesRead
, NULL
))
403 #elif defined(__MWERKS__)
404 int iRc
= ::read(m_fd
, (char*) pBuf
, nCount
);
406 int iRc
= ::read(m_fd
, pBuf
, nCount
);
409 wxLogSysError(_("can't read from file descriptor %d"), m_fd
);
410 return wxInvalidOffset
;
417 size_t wxFile::Write(const void *pBuf
, size_t nCount
)
419 wxCHECK( (pBuf
!= NULL
) && IsOpened(), 0 );
422 DWORD bytesWritten
= 0;
424 if (WriteFile((HANDLE
) m_fd
, pBuf
, (DWORD
) nCount
, & bytesWritten
, NULL
))
428 #elif defined(__MWERKS__)
429 #if __MSL__ >= 0x6000
430 int iRc
= ::write(m_fd
, (void*) pBuf
, nCount
);
432 int iRc
= ::write(m_fd
, (const char*) pBuf
, nCount
);
435 int iRc
= ::write(m_fd
, pBuf
, nCount
);
438 wxLogSysError(_("can't write to file descriptor %d"), m_fd
);
452 #elif defined(__VISUALC__) || wxHAVE_FSYNC
453 if ( wxFsync(m_fd
) == -1 )
455 wxLogSysError(_("can't flush file descriptor %d"), m_fd
);
466 // ----------------------------------------------------------------------------
468 // ----------------------------------------------------------------------------
471 off_t
wxFile::Seek(off_t ofs
, wxSeekMode mode
)
473 wxASSERT( IsOpened() );
479 wxFAIL_MSG(_("unknown seek origin"));
486 origin
= FILE_CURRENT
;
494 DWORD res
= SetFilePointer((HANDLE
) m_fd
, ofs
, 0, origin
) ;
495 if (res
== 0xFFFFFFFF && GetLastError() != NO_ERROR
)
497 wxLogSysError(_("can't seek on file descriptor %d"), m_fd
);
498 return wxInvalidOffset
;
506 wxFAIL_MSG(_("unknown seek origin"));
521 int iRc
= lseek(m_fd
, ofs
, origin
);
523 wxLogSysError(_("can't seek on file descriptor %d"), m_fd
);
524 return wxInvalidOffset
;
532 off_t
wxFile::Tell() const
534 wxASSERT( IsOpened() );
537 DWORD res
= SetFilePointer((HANDLE
) m_fd
, 0, 0, FILE_CURRENT
) ;
538 if (res
== 0xFFFFFFFF && GetLastError() != NO_ERROR
)
540 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd
);
541 return wxInvalidOffset
;
546 int iRc
= wxTell(m_fd
);
548 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd
);
549 return wxInvalidOffset
;
556 // get current file length
557 off_t
wxFile::Length() const
559 wxASSERT( IsOpened() );
562 DWORD off0
= SetFilePointer((HANDLE
) m_fd
, 0, 0, FILE_CURRENT
);
563 DWORD off1
= SetFilePointer((HANDLE
) m_fd
, 0, 0, FILE_END
);
567 SetFilePointer((HANDLE
) m_fd
, off0
, 0, FILE_BEGIN
);
571 int iRc
= _filelength(m_fd
);
573 int iRc
= wxTell(m_fd
);
575 // @ have to use const_cast :-(
576 int iLen
= ((wxFile
*)this)->SeekEnd();
578 // restore old position
579 if ( ((wxFile
*)this)->Seek(iRc
) == -1 ) {
590 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd
);
591 return wxInvalidOffset
;
598 // is end of file reached?
599 bool wxFile::Eof() const
601 wxASSERT( IsOpened() );
604 DWORD off0
= SetFilePointer((HANDLE
) m_fd
, 0, 0, FILE_CURRENT
);
605 DWORD off1
= SetFilePointer((HANDLE
) m_fd
, 0, 0, FILE_END
);
610 SetFilePointer((HANDLE
) m_fd
, off0
, 0, FILE_BEGIN
);
616 #if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
617 // @@ this doesn't work, of course, on unseekable file descriptors
618 off_t ofsCur
= Tell(),
620 if ( ofsCur
== wxInvalidOffset
|| ofsMax
== wxInvalidOffset
)
623 iRc
= ofsCur
== ofsMax
;
624 #else // Windows and "native" compiler
626 #endif // Windows/Unix
636 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd
);
640 wxFAIL_MSG(_("invalid eof() return value."));
647 // ============================================================================
648 // implementation of wxTempFile
649 // ============================================================================
651 // ----------------------------------------------------------------------------
653 // ----------------------------------------------------------------------------
655 wxTempFile::wxTempFile(const wxString
& strName
)
660 bool wxTempFile::Open(const wxString
& strName
)
662 // we must have an absolute filename because otherwise CreateTempFileName()
663 // would create the temp file in $TMP (i.e. the system standard location
664 // for the temp files) which might be on another volume/drive/mount and
665 // wxRename()ing it later to m_strName from Commit() would then fail
667 // with the absolute filename, the temp file is created in the same
668 // directory as this one which ensures that wxRename() may work later
669 wxFileName
fn(strName
);
670 if ( !fn
.IsAbsolute() )
672 fn
.Normalize(wxPATH_NORM_ABSOLUTE
);
675 m_strName
= fn
.GetFullPath();
677 m_strTemp
= wxFileName::CreateTempFileName(m_strName
, &m_file
);
679 if ( m_strTemp
.empty() )
681 // CreateTempFileName() failed
686 // the temp file should have the same permissions as the original one
690 if ( stat( (const char*) m_strName
.fn_str(), &st
) == 0 )
696 // file probably didn't exist, just give it the default mode _using_
697 // user's umask (new files creation should respect umask)
698 mode_t mask
= umask(0777);
703 if ( chmod( (const char*) m_strTemp
.fn_str(), mode
) == -1 )
706 wxLogSysError(_("Failed to set temporary file permissions"));
714 // ----------------------------------------------------------------------------
716 // ----------------------------------------------------------------------------
718 wxTempFile::~wxTempFile()
724 bool wxTempFile::Commit()
728 if ( wxFile::Exists(m_strName
) && wxRemove(m_strName
) != 0 ) {
729 wxLogSysError(_("can't remove file '%s'"), m_strName
.c_str());
733 if ( !wxRenameFile(m_strTemp
, m_strName
) ) {
734 wxLogSysError(_("can't commit changes to file '%s'"), m_strName
.c_str());
741 void wxTempFile::Discard()
744 if ( wxRemove(m_strTemp
) != 0 )
745 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp
.c_str());