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