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