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