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