]> git.saurik.com Git - wxWidgets.git/blame - src/common/file.cpp
removed useless inclusion of wx/datetime.h
[wxWidgets.git] / src / common / file.cpp
CommitLineData
c801d85f 1/////////////////////////////////////////////////////////////////////////////
f172cb82 2// Name: src/common/file.cpp
c801d85f
KB
3// Purpose: wxFile - encapsulates low-level "file descriptor"
4// wxTempFile
5// Author: Vadim Zeitlin
6// Modified by:
7// Created: 29/01/98
8// RCS-ID: $Id$
9// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
65571936 10// Licence: wxWindows licence
c801d85f
KB
11/////////////////////////////////////////////////////////////////////////////
12
13// ----------------------------------------------------------------------------
14// headers
15// ----------------------------------------------------------------------------
16
c801d85f
KB
17// For compilers that support precompilation, includes "wx.h".
18#include "wx/wxprec.h"
c801d85f
KB
19
20#ifdef __BORLANDC__
ce4169a4 21 #pragma hdrstop
c801d85f
KB
22#endif
23
ce4169a4
RR
24#if wxUSE_FILE
25
c801d85f 26// standard
1c193821 27#if defined(__WXMSW__) && !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
30a5be97 28
f172cb82
VZ
29#define WIN32_LEAN_AND_MEAN
30#define NOSERVICE
31#define NOIME
32#define NOATOM
33#define NOGDI
34#define NOGDICAPMASKS
35#define NOMETAFILE
36#define NOMINMAX
37#define NOMSG
38#define NOOPENFILE
39#define NORASTEROPS
40#define NOSCROLL
41#define NOSOUND
42#define NOSYSMETRICS
43#define NOTEXTMETRIC
44#define NOWH
45#define NOCOMM
46#define NOKANJI
47#define NOCRYPT
48#define NOMCX
a3ef5bf5 49
1c193821 50#elif defined(__WXMSW__) && defined(__WXWINCE__)
d109c584 51 #include "wx/msw/missing.h"
5a3912f2
SN
52#elif (defined(__OS2__))
53 #include <io.h>
c801d85f 54#elif (defined(__UNIX__) || defined(__GNUWIN32__))
3f4a0c5b 55 #include <unistd.h>
fd938b11 56 #include <time.h>
732b8386 57 #include <sys/stat.h>
3f4a0c5b 58 #ifdef __GNUWIN32__
9ed0d735 59 #include "wx/msw/wrapwin.h"
3f4a0c5b 60 #endif
d3b4d710
VS
61#elif defined(__DOS__)
62 #if defined(__WATCOMC__)
63 #include <io.h>
64 #elif defined(__DJGPP__)
65 #include <io.h>
66 #include <unistd.h>
67 #include <stdio.h>
68 #else
69 #error "Please specify the header with file functions declarations."
70 #endif
34138703 71#elif (defined(__WXSTUBS__))
3f4a0c5b
VZ
72 // Have to ifdef this for different environments
73 #include <io.h>
17dff81c 74#elif (defined(__WXMAC__))
5b781a67 75#if __MSL__ < 0x6000
3f4a0c5b 76 int access( const char *path, int mode ) { return 0 ; }
5b781a67
SC
77#else
78 int _access( const char *path, int mode ) { return 0 ; }
79#endif
3f4a0c5b 80 char* mktemp( char * path ) { return path ;}
5b781a67 81 #include <stat.h>
6294ac2e 82 #include <unistd.h>
c801d85f 83#else
3f4a0c5b 84 #error "Please specify the header with file functions declarations."
c801d85f
KB
85#endif //Win/UNIX
86
87#include <stdio.h> // SEEK_xxx constants
1c193821 88
4ea2c29f
VZ
89// Windows compilers don't have these constants
90#ifndef W_OK
91 enum
92 {
93 F_OK = 0, // test for existence
94 X_OK = 1, // execute permission
95 W_OK = 2, // write
96 R_OK = 4 // read
97 };
98#endif // W_OK
34138703 99
77ffb593 100// wxWidgets
ade35f11
VZ
101#ifndef WX_PRECOMP
102 #include "wx/string.h"
103 #include "wx/intl.h"
ade35f11 104 #include "wx/log.h"
0bf751e7 105 #include "wx/crt.h"
ade35f11
VZ
106#endif // !WX_PRECOMP
107
108#include "wx/filename.h"
44d568b6 109#include "wx/file.h"
4ea2c29f 110#include "wx/filefn.h"
f6bcfd97 111
7cbe148e
SN
112// there is no distinction between text and binary files under Unix, so define
113// O_BINARY as 0 if the system headers don't do it already
114#if defined(__UNIX__) && !defined(O_BINARY)
115 #define O_BINARY (0)
116#endif //__UNIX__
117
28f5082b
VS
118#ifdef __WXMSW__
119 #include "wx/msw/mslu.h"
120#endif
121
1c193821
JS
122#ifdef __WXWINCE__
123 #include "wx/msw/private.h"
124#endif
125
7cbe148e
SN
126#ifndef MAX_PATH
127 #define MAX_PATH 512
128#endif
30984dea 129
c801d85f
KB
130// ============================================================================
131// implementation of wxFile
132// ============================================================================
133
134// ----------------------------------------------------------------------------
135// static functions
136// ----------------------------------------------------------------------------
4ea2c29f 137
fcea31d5 138bool wxFile::Exists(const wxString& name)
246037e2 139{
4ea2c29f 140 return wxFileExists(name);
d1427b70
VZ
141}
142
fcea31d5 143bool wxFile::Access(const wxString& name, OpenMode mode)
d1427b70 144{
4ea2c29f
VZ
145 int how;
146
147 switch ( mode )
148 {
149 default:
150 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
151 // fall through
d1427b70 152
49d5d881
VZ
153 case read:
154 how = R_OK;
155 break;
d1427b70 156
49d5d881
VZ
157 case write:
158 how = W_OK;
159 break;
d1427b70 160
4ea2c29f
VZ
161 case read_write:
162 how = R_OK | W_OK;
163 break;
49d5d881 164 }
d1427b70 165
4ea2c29f 166 return wxAccess(name, how) == 0;
c801d85f
KB
167}
168
169// ----------------------------------------------------------------------------
170// opening/closing
171// ----------------------------------------------------------------------------
172
173// ctors
11aac4ba 174wxFile::wxFile(const wxString& fileName, OpenMode mode)
c801d85f 175{
49d5d881 176 m_fd = fd_invalid;
a62848fd 177 m_error = false;
c801d85f 178
11aac4ba 179 Open(fileName, mode);
c801d85f
KB
180}
181
c801d85f 182// create the file, fail if it already exists and bOverwrite
fcea31d5 183bool wxFile::Create(const wxString& fileName, bool bOverwrite, int accessMode)
c801d85f 184{
49d5d881
VZ
185 // if bOverwrite we create a new file or truncate the existing one,
186 // otherwise we only create the new file and fail if it already exists
fcea31d5 187 int fd = wxOpen( fileName,
92980e90 188 O_BINARY | O_WRONLY | O_CREAT |
f172cb82
VZ
189 (bOverwrite ? O_TRUNC : O_EXCL),
190 accessMode );
92980e90
RR
191 if ( fd == -1 )
192 {
fcea31d5 193 wxLogSysError(_("can't create file '%s'"), fileName);
a62848fd 194 return false;
49d5d881 195 }
769627d7
DS
196
197 Attach(fd);
198 return true;
c801d85f
KB
199}
200
201// open the file
fcea31d5 202bool wxFile::Open(const wxString& fileName, OpenMode mode, int accessMode)
c801d85f 203{
49d5d881 204 int flags = O_BINARY;
c801d85f 205
92980e90
RR
206 switch ( mode )
207 {
49d5d881
VZ
208 case read:
209 flags |= O_RDONLY;
210 break;
c801d85f 211
f6bcfd97 212 case write_append:
fcea31d5 213 if ( wxFile::Exists(fileName) )
f6bcfd97
BP
214 {
215 flags |= O_WRONLY | O_APPEND;
216 break;
217 }
218 //else: fall through as write_append is the same as write if the
219 // file doesn't exist
220
49d5d881
VZ
221 case write:
222 flags |= O_WRONLY | O_CREAT | O_TRUNC;
223 break;
61b02744 224
68164137
RL
225 case write_excl:
226 flags |= O_WRONLY | O_CREAT | O_EXCL;
227 break;
228
49d5d881
VZ
229 case read_write:
230 flags |= O_RDWR;
231 break;
232 }
c801d85f 233
cc8cc54f
VZ
234#ifdef __WINDOWS__
235 // only read/write bits for "all" are supported by this function under
236 // Windows, and VC++ 8 returns EINVAL if any other bits are used in
237 // accessMode, so clear them as they have at best no effect anyhow
238 accessMode &= wxS_IRUSR | wxS_IWUSR;
239#endif // __WINDOWS__
240
f172cb82 241 int fd = wxOpen( fileName, flags, accessMode);
6294ac2e 242
92980e90
RR
243 if ( fd == -1 )
244 {
fcea31d5 245 wxLogSysError(_("can't open file '%s'"), fileName);
a62848fd 246 return false;
49d5d881 247 }
769627d7
DS
248
249 Attach(fd);
250 return true;
c801d85f
KB
251}
252
253// close
61b02744 254bool wxFile::Close()
c801d85f 255{
49d5d881 256 if ( IsOpened() ) {
6294ac2e 257 if (wxClose(m_fd) == -1)
1c193821 258 {
49d5d881
VZ
259 wxLogSysError(_("can't close file descriptor %d"), m_fd);
260 m_fd = fd_invalid;
a62848fd 261 return false;
49d5d881
VZ
262 }
263 else
264 m_fd = fd_invalid;
61b02744 265 }
61b02744 266
a62848fd 267 return true;
c801d85f
KB
268}
269
270// ----------------------------------------------------------------------------
271// read/write
272// ----------------------------------------------------------------------------
273
274// read
f8a586e0 275ssize_t wxFile::Read(void *pBuf, size_t nCount)
c801d85f 276{
49d5d881 277 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
c801d85f 278
30984dea 279 ssize_t iRc = wxRead(m_fd, pBuf, nCount);
6294ac2e 280
30984dea 281 if ( iRc == -1 )
02aef13c 282 {
49d5d881 283 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
f8a586e0 284 return wxInvalidOffset;
49d5d881 285 }
02aef13c
VZ
286
287 return iRc;
c801d85f
KB
288}
289
290// write
30984dea 291size_t wxFile::Write(const void *pBuf, size_t nCount)
c801d85f 292{
49d5d881 293 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
c801d85f 294
30984dea 295 ssize_t iRc = wxWrite(m_fd, pBuf, nCount);
6294ac2e 296
30984dea 297 if ( iRc == -1 )
02aef13c 298 {
49d5d881 299 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
a62848fd 300 m_error = true;
02aef13c 301 iRc = 0;
49d5d881 302 }
02aef13c 303
30984dea 304 return iRc;
c801d85f
KB
305}
306
b1c67394
VZ
307bool wxFile::Write(const wxString& s, const wxMBConv& conv)
308{
309 const wxWX2MBbuf buf = s.mb_str(conv);
310 if ( !buf )
311 return false;
312
313 const size_t size = strlen(buf); // FIXME: use buf.length() when available
314 return Write(buf, size) == size;
315}
316
c801d85f
KB
317// flush
318bool wxFile::Flush()
319{
c8ccc915 320#ifdef HAVE_FSYNC
608a34bf
VZ
321 // fsync() only works on disk files and returns errors for pipes, don't
322 // call it then
323 if ( IsOpened() && GetKind() == wxFILE_KIND_DISK )
324 {
f6bcfd97 325 if ( wxFsync(m_fd) == -1 )
09914df7
VZ
326 {
327 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
a62848fd 328 return false;
09914df7 329 }
49d5d881 330 }
c8ccc915 331#endif // HAVE_FSYNC
c801d85f 332
a62848fd 333 return true;
c801d85f
KB
334}
335
336// ----------------------------------------------------------------------------
337// seek
338// ----------------------------------------------------------------------------
339
340// seek
30984dea 341wxFileOffset wxFile::Seek(wxFileOffset ofs, wxSeekMode mode)
c801d85f 342{
686a3ee0
VZ
343 wxASSERT_MSG( IsOpened(), _T("can't seek on closed file") );
344 wxCHECK_MSG( ofs != wxInvalidOffset || mode != wxFromStart,
345 wxInvalidOffset,
346 _T("invalid absolute file offset") );
49d5d881 347
a1b82138 348 int origin;
49d5d881 349 switch ( mode ) {
a1b82138 350 default:
fe4a2829 351 wxFAIL_MSG(_T("unknown seek origin"));
a1b82138 352
49d5d881 353 case wxFromStart:
a1b82138 354 origin = SEEK_SET;
49d5d881
VZ
355 break;
356
357 case wxFromCurrent:
a1b82138 358 origin = SEEK_CUR;
49d5d881
VZ
359 break;
360
361 case wxFromEnd:
a1b82138 362 origin = SEEK_END;
49d5d881 363 break;
49d5d881
VZ
364 }
365
30984dea 366 wxFileOffset iRc = wxSeek(m_fd, ofs, origin);
02aef13c
VZ
367 if ( iRc == wxInvalidOffset )
368 {
49d5d881 369 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
49d5d881 370 }
02aef13c
VZ
371
372 return iRc;
c801d85f
KB
373}
374
02aef13c 375// get current file offset
30984dea 376wxFileOffset wxFile::Tell() const
c801d85f 377{
49d5d881
VZ
378 wxASSERT( IsOpened() );
379
30984dea 380 wxFileOffset iRc = wxTell(m_fd);
02aef13c
VZ
381 if ( iRc == wxInvalidOffset )
382 {
49d5d881 383 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
49d5d881 384 }
02aef13c
VZ
385
386 return iRc;
c801d85f
KB
387}
388
389// get current file length
30984dea 390wxFileOffset wxFile::Length() const
c801d85f 391{
49d5d881 392 wxASSERT( IsOpened() );
c801d85f 393
30984dea 394 wxFileOffset iRc = Tell();
02aef13c
VZ
395 if ( iRc != wxInvalidOffset ) {
396 // have to use const_cast :-(
30984dea 397 wxFileOffset iLen = ((wxFile *)this)->SeekEnd();
02aef13c 398 if ( iLen != wxInvalidOffset ) {
49d5d881 399 // restore old position
02aef13c 400 if ( ((wxFile *)this)->Seek(iRc) == wxInvalidOffset ) {
49d5d881 401 // error
02aef13c 402 iLen = wxInvalidOffset;
49d5d881 403 }
c801d85f 404 }
c801d85f 405
49d5d881
VZ
406 iRc = iLen;
407 }
49d5d881 408
02aef13c
VZ
409 if ( iRc == wxInvalidOffset )
410 {
49d5d881 411 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
c801d85f 412 }
02aef13c
VZ
413
414 return iRc;
c801d85f
KB
415}
416
417// is end of file reached?
418bool wxFile::Eof() const
419{
49d5d881 420 wxASSERT( IsOpened() );
c801d85f 421
30984dea 422 wxFileOffset iRc;
61b02744 423
f172cb82 424#if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ )
61b02744 425 // @@ this doesn't work, of course, on unseekable file descriptors
30984dea 426 wxFileOffset ofsCur = Tell(),
49d5d881 427 ofsMax = Length();
1678ad78 428 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
02aef13c 429 iRc = wxInvalidOffset;
61b02744 430 else
49d5d881
VZ
431 iRc = ofsCur == ofsMax;
432#else // Windows and "native" compiler
6294ac2e 433 iRc = wxEof(m_fd);
49d5d881 434#endif // Windows/Unix
c801d85f 435
b9daf00a
WS
436 if ( iRc == 1)
437 {}
438 else if ( iRc == 0 )
439 return false;
440 else if ( iRc == wxInvalidOffset )
441 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
442 else
fe4a2829 443 wxFAIL_MSG(_T("invalid eof() return value."));
c801d85f 444
a62848fd 445 return true;
c801d85f
KB
446}
447
448// ============================================================================
449// implementation of wxTempFile
450// ============================================================================
451
452// ----------------------------------------------------------------------------
453// construction
454// ----------------------------------------------------------------------------
44b62d54 455
c801d85f
KB
456wxTempFile::wxTempFile(const wxString& strName)
457{
49d5d881 458 Open(strName);
c801d85f
KB
459}
460
461bool wxTempFile::Open(const wxString& strName)
462{
44b62d54
VZ
463 // we must have an absolute filename because otherwise CreateTempFileName()
464 // would create the temp file in $TMP (i.e. the system standard location
465 // for the temp files) which might be on another volume/drive/mount and
466 // wxRename()ing it later to m_strName from Commit() would then fail
467 //
468 // with the absolute filename, the temp file is created in the same
469 // directory as this one which ensures that wxRename() may work later
470 wxFileName fn(strName);
471 if ( !fn.IsAbsolute() )
472 {
473 fn.Normalize(wxPATH_NORM_ABSOLUTE);
474 }
475
476 m_strName = fn.GetFullPath();
246037e2 477
44b62d54 478 m_strTemp = wxFileName::CreateTempFileName(m_strName, &m_file);
ade35f11
VZ
479
480 if ( m_strTemp.empty() )
481 {
482 // CreateTempFileName() failed
a62848fd 483 return false;
ade35f11 484 }
49d5d881 485
49d5d881 486#ifdef __UNIX__
ade35f11
VZ
487 // the temp file should have the same permissions as the original one
488 mode_t mode;
a62848fd 489
f6bcfd97 490 wxStructStat st;
ca11abde 491 if ( stat( (const char*) m_strName.fn_str(), &st) == 0 )
49d5d881 492 {
ade35f11 493 mode = st.st_mode;
49d5d881
VZ
494 }
495 else
496 {
ade35f11 497 // file probably didn't exist, just give it the default mode _using_
68164137 498 // user's umask (new files creation should respect umask)
ade35f11
VZ
499 mode_t mask = umask(0777);
500 mode = 0666 & ~mask;
501 umask(mask);
49d5d881 502 }
49d5d881 503
ca11abde 504 if ( chmod( (const char*) m_strTemp.fn_str(), mode) == -1 )
fe99e285 505 {
5a3912f2 506#ifndef __OS2__
ade35f11 507 wxLogSysError(_("Failed to set temporary file permissions"));
5a3912f2 508#endif
fe99e285 509 }
49d5d881 510#endif // Unix
246037e2 511
a62848fd 512 return true;
c801d85f
KB
513}
514
515// ----------------------------------------------------------------------------
516// destruction
517// ----------------------------------------------------------------------------
518
519wxTempFile::~wxTempFile()
520{
49d5d881
VZ
521 if ( IsOpened() )
522 Discard();
c801d85f
KB
523}
524
525bool wxTempFile::Commit()
526{
49d5d881 527 m_file.Close();
c801d85f 528
f6bcfd97 529 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
49d5d881 530 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
a62848fd 531 return false;
49d5d881 532 }
c801d85f 533
f35746ce 534 if ( !wxRenameFile(m_strTemp, m_strName) ) {
49d5d881 535 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
a62848fd 536 return false;
49d5d881 537 }
c801d85f 538
a62848fd 539 return true;
c801d85f
KB
540}
541
542void wxTempFile::Discard()
543{
49d5d881 544 m_file.Close();
f6bcfd97 545 if ( wxRemove(m_strTemp) != 0 )
49d5d881 546 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
c801d85f 547}
ce4169a4 548
ade35f11 549#endif // wxUSE_FILE
cc985fac 550