]> git.saurik.com Git - wxWidgets.git/blame - src/common/file.cpp
Added comment explaining that it's not necessary to use LEX and YACC on
[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>
246037e2 10// Licence: wxWindows license
c801d85f
KB
11/////////////////////////////////////////////////////////////////////////////
12
13// ----------------------------------------------------------------------------
14// headers
15// ----------------------------------------------------------------------------
16
17#ifdef __GNUG__
3f4a0c5b 18 #pragma implementation "file.h"
c801d85f
KB
19#endif
20
21// For compilers that support precompilation, includes "wx.h".
22#include "wx/wxprec.h"
c801d85f
KB
23
24#ifdef __BORLANDC__
ce4169a4 25 #pragma hdrstop
c801d85f
KB
26#endif
27
ce4169a4
RR
28#if wxUSE_FILE
29
c801d85f 30// standard
fac3b423 31#if defined(__WXMSW__) && !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
c801d85f 32 #include <io.h>
30a5be97 33
a3ef5bf5 34#ifndef __SALFORDC__
49d5d881
VZ
35 #define WIN32_LEAN_AND_MEAN
36 #define NOSERVICE
37 #define NOIME
38 #define NOATOM
39 #define NOGDI
40 #define NOGDICAPMASKS
41 #define NOMETAFILE
42 #define NOMINMAX
43 #define NOMSG
44 #define NOOPENFILE
45 #define NORASTEROPS
46 #define NOSCROLL
47 #define NOSOUND
48 #define NOSYSMETRICS
49 #define NOTEXTMETRIC
50 #define NOWH
51 #define NOCOMM
52 #define NOKANJI
53 #define NOCRYPT
54 #define NOMCX
a3ef5bf5
JS
55#endif
56
49d5d881 57 #include <windows.h> // for GetTempFileName
c801d85f 58#elif (defined(__UNIX__) || defined(__GNUWIN32__))
3f4a0c5b
VZ
59 #include <unistd.h>
60 #ifdef __GNUWIN32__
61 #include <windows.h>
62 #endif
c2ff79b1
DW
63#elif (defined(__WXPM__))
64 #include <io.h>
c2ff79b1
DW
65 #define W_OK 2
66 #define R_OK 4
34138703 67#elif (defined(__WXSTUBS__))
3f4a0c5b
VZ
68 // Have to ifdef this for different environments
69 #include <io.h>
17dff81c 70#elif (defined(__WXMAC__))
5b781a67 71#if __MSL__ < 0x6000
3f4a0c5b 72 int access( const char *path, int mode ) { return 0 ; }
5b781a67
SC
73#else
74 int _access( const char *path, int mode ) { return 0 ; }
75#endif
3f4a0c5b 76 char* mktemp( char * path ) { return path ;}
5b781a67 77 #include <stat.h>
3f4a0c5b
VZ
78 #define W_OK 2
79 #define R_OK 4
5b781a67 80 #include <unistd.h>
c801d85f 81#else
3f4a0c5b 82 #error "Please specify the header with file functions declarations."
c801d85f
KB
83#endif //Win/UNIX
84
85#include <stdio.h> // SEEK_xxx constants
86#include <fcntl.h> // O_RDONLY &c
a3ef5bf5 87
469e1e5c 88#ifndef __MWERKS__
3f4a0c5b
VZ
89 #include <sys/types.h> // needed for stat
90 #include <sys/stat.h> // stat
469e1e5c 91#endif
c801d85f 92
3f4a0c5b 93#if defined(__BORLANDC__) || defined(_MSC_VER)
49d5d881
VZ
94 #define W_OK 2
95 #define R_OK 4
34138703
JS
96#endif
97
b12915c1
VZ
98// there is no distinction between text and binary files under Unix, so define
99// O_BINARY as 0 if the system headers don't do it already
100#if defined(__UNIX__) && !defined(O_BINARY)
49d5d881 101 #define O_BINARY (0)
246037e2 102#endif //__UNIX__
c801d85f 103
a3ef5bf5 104#ifdef __SALFORDC__
3f4a0c5b 105 #include <unix.h>
a3ef5bf5
JS
106#endif
107
81d66cf3 108#ifndef MAX_PATH
3f4a0c5b 109 #define MAX_PATH 512
81d66cf3 110#endif
c801d85f 111
49d5d881
VZ
112// some broken compilers don't have 3rd argument in open() and creat()
113#ifdef __SALFORDC__
114 #define ACCESS(access)
115 #define stat _stat
116#else // normal compiler
117 #define ACCESS(access) , (access)
118#endif // Salford C
119
f6bcfd97
BP
120// wxWindows
121#include "wx/string.h"
122#include "wx/intl.h"
123#include "wx/file.h"
124#include "wx/log.h"
125
c801d85f
KB
126// ============================================================================
127// implementation of wxFile
128// ============================================================================
129
130// ----------------------------------------------------------------------------
131// static functions
132// ----------------------------------------------------------------------------
50920146 133bool wxFile::Exists(const wxChar *name)
246037e2 134{
f6bcfd97 135 wxStructStat st;
50920146 136#if wxUSE_UNICODE && wxMBFILES
dcf924a3 137 wxCharBuffer fname = wxConvFile.cWC2MB(name);
a3ef5bf5 138
f6bcfd97
BP
139 return !wxAccess(fname, 0) &&
140 !wxStat(wxMBSTRINGCAST fname, &st) &&
50920146 141 (st.st_mode & S_IFREG);
bedaf53e 142
50920146 143#else
f6bcfd97
BP
144 return !wxAccess(name, 0) &&
145 !wxStat(name, &st) &&
49d5d881 146 (st.st_mode & S_IFREG);
50920146 147#endif
d1427b70
VZ
148}
149
50920146 150bool wxFile::Access(const wxChar *name, OpenMode mode)
d1427b70 151{
49d5d881 152 int how = 0;
d1427b70 153
49d5d881
VZ
154 switch ( mode ) {
155 case read:
156 how = R_OK;
157 break;
d1427b70 158
49d5d881
VZ
159 case write:
160 how = W_OK;
161 break;
d1427b70 162
49d5d881 163 default:
223d09f6 164 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
49d5d881 165 }
d1427b70 166
f6bcfd97 167 return wxAccess(wxFNCONV(name), how) == 0;
c801d85f
KB
168}
169
170// ----------------------------------------------------------------------------
171// opening/closing
172// ----------------------------------------------------------------------------
173
174// ctors
50920146 175wxFile::wxFile(const wxChar *szFileName, OpenMode mode)
c801d85f 176{
49d5d881
VZ
177 m_fd = fd_invalid;
178 m_error = FALSE;
c801d85f 179
49d5d881 180 Open(szFileName, mode);
c801d85f
KB
181}
182
c801d85f 183// create the file, fail if it already exists and bOverwrite
50920146 184bool wxFile::Create(const wxChar *szFileName, bool bOverwrite, int accessMode)
c801d85f 185{
49d5d881
VZ
186 // if bOverwrite we create a new file or truncate the existing one,
187 // otherwise we only create the new file and fail if it already exists
5fde6fcc 188#if defined(__WXMAC__) && !defined(__UNIX__)
5b781a67
SC
189 // Dominic Mazzoni [dmazzoni+@cs.cmu.edu] reports that open is still broken on the mac, so we replace
190 // int fd = open(wxUnix2MacFilename( szFileName ), O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
bedaf53e 191 int fd = creat( szFileName , accessMode);
7c74e7fe 192#else
f6bcfd97
BP
193 int fd = wxOpen(wxFNCONV(szFileName),
194 O_BINARY | O_WRONLY | O_CREAT |
195 (bOverwrite ? O_TRUNC : O_EXCL)
196 ACCESS(accessMode));
7c74e7fe 197#endif
49d5d881
VZ
198 if ( fd == -1 ) {
199 wxLogSysError(_("can't create file '%s'"), szFileName);
200 return FALSE;
201 }
202 else {
203 Attach(fd);
204 return TRUE;
205 }
c801d85f
KB
206}
207
208// open the file
50920146 209bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
c801d85f 210{
49d5d881 211 int flags = O_BINARY;
c801d85f 212
49d5d881
VZ
213 switch ( mode ) {
214 case read:
215 flags |= O_RDONLY;
216 break;
c801d85f 217
f6bcfd97
BP
218 case write_append:
219 if ( wxFile::Exists(szFileName) )
220 {
221 flags |= O_WRONLY | O_APPEND;
222 break;
223 }
224 //else: fall through as write_append is the same as write if the
225 // file doesn't exist
226
49d5d881
VZ
227 case write:
228 flags |= O_WRONLY | O_CREAT | O_TRUNC;
229 break;
61b02744 230
49d5d881
VZ
231 case read_write:
232 flags |= O_RDWR;
233 break;
234 }
c801d85f 235
f6bcfd97 236 int fd = wxOpen(wxFNCONV(szFileName), flags ACCESS(accessMode));
49d5d881
VZ
237 if ( fd == -1 ) {
238 wxLogSysError(_("can't open file '%s'"), szFileName);
239 return FALSE;
240 }
241 else {
242 Attach(fd);
243 return TRUE;
244 }
c801d85f
KB
245}
246
247// close
61b02744 248bool wxFile::Close()
c801d85f 249{
49d5d881
VZ
250 if ( IsOpened() ) {
251 if ( close(m_fd) == -1 ) {
252 wxLogSysError(_("can't close file descriptor %d"), m_fd);
253 m_fd = fd_invalid;
254 return FALSE;
255 }
256 else
257 m_fd = fd_invalid;
61b02744 258 }
61b02744 259
49d5d881 260 return TRUE;
c801d85f
KB
261}
262
263// ----------------------------------------------------------------------------
264// read/write
265// ----------------------------------------------------------------------------
266
267// read
268off_t wxFile::Read(void *pBuf, off_t nCount)
269{
49d5d881 270 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
c801d85f 271
469e1e5c 272#ifdef __MWERKS__
49d5d881 273 int iRc = ::read(m_fd, (char*) pBuf, nCount);
469e1e5c 274#else
49d5d881 275 int iRc = ::read(m_fd, pBuf, nCount);
469e1e5c 276#endif
49d5d881
VZ
277 if ( iRc == -1 ) {
278 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
279 return wxInvalidOffset;
280 }
281 else
282 return (size_t)iRc;
c801d85f
KB
283}
284
285// write
c86f1403 286size_t wxFile::Write(const void *pBuf, size_t nCount)
c801d85f 287{
49d5d881 288 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
c801d85f 289
469e1e5c 290#ifdef __MWERKS__
5b781a67
SC
291#if __MSL__ >= 0x6000
292 int iRc = ::write(m_fd, (void*) pBuf, nCount);
293#else
49d5d881 294 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
5b781a67 295#endif
469e1e5c 296#else
49d5d881 297 int iRc = ::write(m_fd, pBuf, nCount);
469e1e5c 298#endif
49d5d881
VZ
299 if ( iRc == -1 ) {
300 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
301 m_error = TRUE;
302 return 0;
303 }
304 else
305 return iRc;
c801d85f
KB
306}
307
308// flush
309bool wxFile::Flush()
310{
49d5d881
VZ
311 if ( IsOpened() ) {
312#if defined(__VISUALC__) || wxHAVE_FSYNC
f6bcfd97 313 if ( wxFsync(m_fd) == -1 )
09914df7
VZ
314 {
315 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
316 return FALSE;
317 }
49d5d881 318#else // no fsync
09914df7 319 // just do nothing
49d5d881
VZ
320#endif // fsync
321 }
c801d85f 322
49d5d881 323 return TRUE;
c801d85f
KB
324}
325
326// ----------------------------------------------------------------------------
327// seek
328// ----------------------------------------------------------------------------
329
330// seek
79c3e0e1 331off_t wxFile::Seek(off_t ofs, wxSeekMode mode)
c801d85f 332{
49d5d881
VZ
333 wxASSERT( IsOpened() );
334
a1b82138 335 int origin;
49d5d881 336 switch ( mode ) {
a1b82138
VZ
337 default:
338 wxFAIL_MSG(_("unknown seek origin"));
339
49d5d881 340 case wxFromStart:
a1b82138 341 origin = SEEK_SET;
49d5d881
VZ
342 break;
343
344 case wxFromCurrent:
a1b82138 345 origin = SEEK_CUR;
49d5d881
VZ
346 break;
347
348 case wxFromEnd:
a1b82138 349 origin = SEEK_END;
49d5d881 350 break;
49d5d881
VZ
351 }
352
a1b82138 353 int iRc = lseek(m_fd, ofs, origin);
49d5d881
VZ
354 if ( iRc == -1 ) {
355 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
356 return wxInvalidOffset;
357 }
358 else
359 return (off_t)iRc;
c801d85f
KB
360}
361
362// get current off_t
363off_t wxFile::Tell() const
364{
49d5d881
VZ
365 wxASSERT( IsOpened() );
366
f6bcfd97 367 int iRc = wxTell(m_fd);
49d5d881
VZ
368 if ( iRc == -1 ) {
369 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
370 return wxInvalidOffset;
371 }
372 else
373 return (off_t)iRc;
c801d85f
KB
374}
375
376// get current file length
377off_t wxFile::Length() const
378{
49d5d881 379 wxASSERT( IsOpened() );
c801d85f 380
49d5d881 381#ifdef __VISUALC__
c801d85f 382 int iRc = _filelength(m_fd);
49d5d881 383#else // !VC++
f6bcfd97 384 int iRc = wxTell(m_fd);
c801d85f 385 if ( iRc != -1 ) {
49d5d881
VZ
386 // @ have to use const_cast :-(
387 int iLen = ((wxFile *)this)->SeekEnd();
388 if ( iLen != -1 ) {
389 // restore old position
390 if ( ((wxFile *)this)->Seek(iRc) == -1 ) {
391 // error
392 iLen = -1;
393 }
c801d85f 394 }
c801d85f 395
49d5d881
VZ
396 iRc = iLen;
397 }
398#endif // VC++
399
400 if ( iRc == -1 ) {
401 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
402 return wxInvalidOffset;
c801d85f 403 }
49d5d881
VZ
404 else
405 return (off_t)iRc;
c801d85f
KB
406}
407
408// is end of file reached?
409bool wxFile::Eof() const
410{
49d5d881 411 wxASSERT( IsOpened() );
c801d85f 412
49d5d881 413 int iRc;
61b02744 414
49d5d881 415#if defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
61b02744
VZ
416 // @@ this doesn't work, of course, on unseekable file descriptors
417 off_t ofsCur = Tell(),
49d5d881 418 ofsMax = Length();
1678ad78 419 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
49d5d881 420 iRc = -1;
61b02744 421 else
49d5d881
VZ
422 iRc = ofsCur == ofsMax;
423#else // Windows and "native" compiler
61b02744 424 iRc = eof(m_fd);
49d5d881 425#endif // Windows/Unix
c801d85f 426
49d5d881
VZ
427 switch ( iRc ) {
428 case 1:
429 break;
c801d85f 430
49d5d881
VZ
431 case 0:
432 return FALSE;
c801d85f 433
49d5d881 434 case -1:
8e3f1261 435 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
49d5d881 436 break;
c801d85f 437
49d5d881
VZ
438 default:
439 wxFAIL_MSG(_("invalid eof() return value."));
440 }
c801d85f 441
49d5d881 442 return TRUE;
c801d85f
KB
443}
444
445// ============================================================================
446// implementation of wxTempFile
447// ============================================================================
448
449// ----------------------------------------------------------------------------
450// construction
451// ----------------------------------------------------------------------------
452wxTempFile::wxTempFile(const wxString& strName)
453{
49d5d881 454 Open(strName);
c801d85f
KB
455}
456
457bool wxTempFile::Open(const wxString& strName)
458{
49d5d881 459 m_strName = strName;
246037e2 460
49d5d881
VZ
461 // we want to create the file in the same directory as strName because
462 // otherwise rename() in Commit() might not work (if the files are on
463 // different partitions for example). Unfortunately, the only standard
464 // (POSIX) temp file creation function tmpnam() can't do it.
465#if defined(__UNIX__) || defined(__WXSTUBS__)|| defined( __WXMAC__ )
223d09f6 466 static const wxChar *szMktempSuffix = wxT("XXXXXX");
b59650be 467 m_strTemp << strName << szMktempSuffix;
e90c1d2a
VZ
468 // can use the cast because length doesn't change
469 mktemp(wxMBSTRINGCAST m_strTemp.mb_str());
c2ff79b1
DW
470#elif defined(__WXPM__)
471 // for now just create a file
472 // future enhancements can be to set some extended attributes for file systems
473 // OS/2 supports that have them (HPFS, FAT32) and security (HPFS386)
223d09f6 474 static const wxChar *szMktempSuffix = wxT("XXX");
c2ff79b1 475 m_strTemp << strName << szMktempSuffix;
f6bcfd97 476 ::DosCreateDir(m_strTemp.GetWriteBuf(MAX_PATH), NULL);
49d5d881 477#else // Windows
30a5be97
VZ
478 wxString strPath;
479 wxSplitPath(strName, &strPath, NULL, NULL);
480 if ( strPath.IsEmpty() )
223d09f6 481 strPath = wxT('.'); // GetTempFileName will fail if we give it empty string
81d66cf3 482#ifdef __WIN32__
223d09f6 483 if ( !GetTempFileName(strPath, wxT("wx_"),0, m_strTemp.GetWriteBuf(MAX_PATH)) )
81d66cf3 484#else
49d5d881 485 // Not sure why MSVC++ 1.5 header defines first param as BYTE - bug?
223d09f6 486 if ( !GetTempFileName((BYTE) (DWORD)(const wxChar*) strPath, wxT("wx_"),0, m_strTemp.GetWriteBuf(MAX_PATH)) )
81d66cf3 487#endif
223d09f6 488 wxLogLastError(wxT("GetTempFileName"));
30a5be97 489 m_strTemp.UngetWriteBuf();
49d5d881
VZ
490#endif // Windows/Unix
491
492 int access = wxS_DEFAULT;
493#ifdef __UNIX__
494 // create the file with the same mode as the original one under Unix
f46f1bc6 495 mode_t umaskOld = 0; // just to suppress compiler warning
fe99e285
VZ
496 bool changedUmask;
497
f6bcfd97 498 wxStructStat st;
50920146 499 if ( stat(strName.fn_str(), &st) == 0 )
49d5d881
VZ
500 {
501 // this assumes that only lower bits of st_mode contain the access
502 // rights, but it's true for at least all Unices which have S_IXXXX()
503 // macros, so should not be less portable than using (not POSIX)
504 // S_IFREG &c
505 access = st.st_mode & 0777;
fe99e285
VZ
506
507 // we want to create the file with exactly the same access rights as
508 // the original one, so disable the user's umask for the moment
509 umaskOld = umask(0);
510 changedUmask = TRUE;
49d5d881
VZ
511 }
512 else
513 {
fe99e285
VZ
514 // file probably didn't exist, just create with default mode _using_
515 // user's umask (new files creation should respet umask)
cedda7e6 516 changedUmask = FALSE;
49d5d881 517 }
49d5d881
VZ
518#endif // Unix
519
cedda7e6 520 bool ok = m_file.Open(m_strTemp, wxFile::write, access);
49d5d881
VZ
521
522#ifdef __UNIX__
fe99e285
VZ
523 if ( changedUmask )
524 {
525 // restore umask now that the file is created
526 (void)umask(umaskOld);
527 }
49d5d881 528#endif // Unix
246037e2 529
49d5d881 530 return ok;
c801d85f
KB
531}
532
533// ----------------------------------------------------------------------------
534// destruction
535// ----------------------------------------------------------------------------
536
537wxTempFile::~wxTempFile()
538{
49d5d881
VZ
539 if ( IsOpened() )
540 Discard();
c801d85f
KB
541}
542
543bool wxTempFile::Commit()
544{
49d5d881 545 m_file.Close();
c801d85f 546
f6bcfd97 547 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
49d5d881
VZ
548 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
549 return FALSE;
550 }
c801d85f 551
f6bcfd97 552 if ( wxRename(m_strTemp, m_strName) != 0 ) {
49d5d881
VZ
553 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
554 return FALSE;
555 }
c801d85f 556
49d5d881 557 return TRUE;
c801d85f
KB
558}
559
560void wxTempFile::Discard()
561{
49d5d881 562 m_file.Close();
f6bcfd97 563 if ( wxRemove(m_strTemp) != 0 )
49d5d881 564 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
c801d85f 565}
ce4169a4 566
cc985fac
PA
567#endif
568