]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/file.cpp
VC 7.1 warning fix
[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 licence
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(__WXMICROWIN__)
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#elif (defined(__UNIX__) || defined(__GNUWIN32__))
58 #include <unistd.h>
59 #include <sys/stat.h>
60 #ifdef __GNUWIN32__
61 #include <windows.h>
62 #endif
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
73#elif (defined(__WXPM__))
74 #include <io.h>
75#elif (defined(__WXSTUBS__))
76 // Have to ifdef this for different environments
77 #include <io.h>
78#elif (defined(__WXMAC__))
79#if __MSL__ < 0x6000
80 int access( const char *path, int mode ) { return 0 ; }
81#else
82 int _access( const char *path, int mode ) { return 0 ; }
83#endif
84 char* mktemp( char * path ) { return path ;}
85 #include <stat.h>
86 #include <unistd.h>
87#else
88 #error "Please specify the header with file functions declarations."
89#endif //Win/UNIX
90
91#include <stdio.h> // SEEK_xxx constants
92#include <fcntl.h> // O_RDONLY &c
93
94#ifndef __MWERKS__
95 #include <sys/types.h> // needed for stat
96 #include <sys/stat.h> // stat
97#elif defined(__MWERKS__) && ( defined(__WXMSW__) || defined(__MACH__) )
98 #include <sys/types.h> // needed for stat
99 #include <sys/stat.h> // stat
100#endif
101
102// Windows compilers don't have these constants
103#ifndef W_OK
104 enum
105 {
106 F_OK = 0, // test for existence
107 X_OK = 1, // execute permission
108 W_OK = 2, // write
109 R_OK = 4 // read
110 };
111#endif // W_OK
112
113// there is no distinction between text and binary files under Unix, so define
114// O_BINARY as 0 if the system headers don't do it already
115#if defined(__UNIX__) && !defined(O_BINARY)
116 #define O_BINARY (0)
117#endif //__UNIX__
118
119#ifdef __SALFORDC__
120 #include <unix.h>
121#endif
122
123#ifndef MAX_PATH
124 #define MAX_PATH 512
125#endif
126
127// some broken compilers don't have 3rd argument in open() and creat()
128#ifdef __SALFORDC__
129 #define ACCESS(access)
130 #define stat _stat
131#else // normal compiler
132 #define ACCESS(access) , (access)
133#endif // Salford C
134
135// wxWindows
136#ifndef WX_PRECOMP
137 #include "wx/string.h"
138 #include "wx/intl.h"
139 #include "wx/log.h"
140#endif // !WX_PRECOMP
141
142#include "wx/filename.h"
143#include "wx/file.h"
144#include "wx/filefn.h"
145
146#ifdef __WXMSW__
147 #include "wx/msw/mslu.h"
148#endif
149
150// ============================================================================
151// implementation of wxFile
152// ============================================================================
153
154// ----------------------------------------------------------------------------
155// static functions
156// ----------------------------------------------------------------------------
157
158bool wxFile::Exists(const wxChar *name)
159{
160 return wxFileExists(name);
161}
162
163bool wxFile::Access(const wxChar *name, OpenMode mode)
164{
165 int how;
166
167 switch ( mode )
168 {
169 default:
170 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
171 // fall through
172
173 case read:
174 how = R_OK;
175 break;
176
177 case write:
178 how = W_OK;
179 break;
180
181 case read_write:
182 how = R_OK | W_OK;
183 break;
184 }
185
186 return wxAccess(name, how) == 0;
187}
188
189// ----------------------------------------------------------------------------
190// opening/closing
191// ----------------------------------------------------------------------------
192
193// ctors
194wxFile::wxFile(const wxChar *szFileName, OpenMode mode)
195{
196 m_fd = fd_invalid;
197 m_error = FALSE;
198
199 Open(szFileName, mode);
200}
201
202// create the file, fail if it already exists and bOverwrite
203bool wxFile::Create(const wxChar *szFileName, bool bOverwrite, int accessMode)
204{
205 // if bOverwrite we create a new file or truncate the existing one,
206 // otherwise we only create the new file and fail if it already exists
207#if defined(__WXMAC__) && !defined(__UNIX__) && !wxUSE_UNICODE
208 // Dominic Mazzoni [dmazzoni+@cs.cmu.edu] reports that open is still broken on the mac, so we replace
209 // int fd = open(wxUnix2MacFilename( szFileName ), O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
210 int fd = creat( szFileName , accessMode);
211#else
212 int fd = wxOpen( szFileName,
213 O_BINARY | O_WRONLY | O_CREAT |
214 (bOverwrite ? O_TRUNC : O_EXCL)
215 ACCESS(accessMode) );
216#endif
217 if ( fd == -1 )
218 {
219 wxLogSysError(_("can't create file '%s'"), szFileName);
220 return FALSE;
221 }
222 else
223 {
224 Attach(fd);
225 return TRUE;
226 }
227}
228
229// open the file
230bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
231{
232 int flags = O_BINARY;
233
234 switch ( mode )
235 {
236 case read:
237 flags |= O_RDONLY;
238 break;
239
240 case write_append:
241 if ( wxFile::Exists(szFileName) )
242 {
243 flags |= O_WRONLY | O_APPEND;
244 break;
245 }
246 //else: fall through as write_append is the same as write if the
247 // file doesn't exist
248
249 case write:
250 flags |= O_WRONLY | O_CREAT | O_TRUNC;
251 break;
252
253 case write_excl:
254 flags |= O_WRONLY | O_CREAT | O_EXCL;
255 break;
256
257 case read_write:
258 flags |= O_RDWR;
259 break;
260 }
261
262 int fd = wxOpen( szFileName, flags ACCESS(accessMode));
263 if ( fd == -1 )
264 {
265 wxLogSysError(_("can't open file '%s'"), szFileName);
266 return FALSE;
267 }
268 else {
269 Attach(fd);
270 return TRUE;
271 }
272}
273
274// close
275bool wxFile::Close()
276{
277 if ( IsOpened() ) {
278 if ( close(m_fd) == -1 ) {
279 wxLogSysError(_("can't close file descriptor %d"), m_fd);
280 m_fd = fd_invalid;
281 return FALSE;
282 }
283 else
284 m_fd = fd_invalid;
285 }
286
287 return TRUE;
288}
289
290// ----------------------------------------------------------------------------
291// read/write
292// ----------------------------------------------------------------------------
293
294// read
295off_t wxFile::Read(void *pBuf, off_t nCount)
296{
297 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
298
299#ifdef __MWERKS__
300 int iRc = ::read(m_fd, (char*) pBuf, nCount);
301#else
302 int iRc = ::read(m_fd, pBuf, nCount);
303#endif
304 if ( iRc == -1 ) {
305 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
306 return wxInvalidOffset;
307 }
308 else
309 return (size_t)iRc;
310}
311
312// write
313size_t wxFile::Write(const void *pBuf, size_t nCount)
314{
315 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
316
317#ifdef __MWERKS__
318#if __MSL__ >= 0x6000
319 int iRc = ::write(m_fd, (void*) pBuf, nCount);
320#else
321 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
322#endif
323#else
324 int iRc = ::write(m_fd, pBuf, nCount);
325#endif
326 if ( iRc == -1 ) {
327 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
328 m_error = TRUE;
329 return 0;
330 }
331 else
332 return iRc;
333}
334
335// flush
336bool wxFile::Flush()
337{
338 if ( IsOpened() ) {
339#if defined(__VISUALC__) || wxHAVE_FSYNC
340 if ( wxFsync(m_fd) == -1 )
341 {
342 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
343 return FALSE;
344 }
345#else // no fsync
346 // just do nothing
347#endif // fsync
348 }
349
350 return TRUE;
351}
352
353// ----------------------------------------------------------------------------
354// seek
355// ----------------------------------------------------------------------------
356
357// seek
358off_t wxFile::Seek(off_t ofs, wxSeekMode mode)
359{
360 wxASSERT( IsOpened() );
361
362 int origin;
363 switch ( mode ) {
364 default:
365 wxFAIL_MSG(_("unknown seek origin"));
366
367 case wxFromStart:
368 origin = SEEK_SET;
369 break;
370
371 case wxFromCurrent:
372 origin = SEEK_CUR;
373 break;
374
375 case wxFromEnd:
376 origin = SEEK_END;
377 break;
378 }
379
380 int iRc = lseek(m_fd, ofs, origin);
381 if ( iRc == -1 ) {
382 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
383 return wxInvalidOffset;
384 }
385 else
386 return (off_t)iRc;
387}
388
389// get current off_t
390off_t wxFile::Tell() const
391{
392 wxASSERT( IsOpened() );
393
394 int iRc = wxTell(m_fd);
395 if ( iRc == -1 ) {
396 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
397 return wxInvalidOffset;
398 }
399 else
400 return (off_t)iRc;
401}
402
403// get current file length
404off_t wxFile::Length() const
405{
406 wxASSERT( IsOpened() );
407
408#ifdef __VISUALC__
409 int iRc = _filelength(m_fd);
410#else // !VC++
411 int iRc = wxTell(m_fd);
412 if ( iRc != -1 ) {
413 // @ have to use const_cast :-(
414 int iLen = ((wxFile *)this)->SeekEnd();
415 if ( iLen != -1 ) {
416 // restore old position
417 if ( ((wxFile *)this)->Seek(iRc) == -1 ) {
418 // error
419 iLen = -1;
420 }
421 }
422
423 iRc = iLen;
424 }
425#endif // VC++
426
427 if ( iRc == -1 ) {
428 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
429 return wxInvalidOffset;
430 }
431 else
432 return (off_t)iRc;
433}
434
435// is end of file reached?
436bool wxFile::Eof() const
437{
438 wxASSERT( IsOpened() );
439
440 int iRc;
441
442#if defined(__DOS__) || defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
443 // @@ this doesn't work, of course, on unseekable file descriptors
444 off_t ofsCur = Tell(),
445 ofsMax = Length();
446 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
447 iRc = -1;
448 else
449 iRc = ofsCur == ofsMax;
450#else // Windows and "native" compiler
451 iRc = eof(m_fd);
452#endif // Windows/Unix
453
454 switch ( iRc ) {
455 case 1:
456 break;
457
458 case 0:
459 return FALSE;
460
461 case -1:
462 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
463 break;
464
465 default:
466 wxFAIL_MSG(_("invalid eof() return value."));
467 }
468
469 return TRUE;
470}
471
472// ============================================================================
473// implementation of wxTempFile
474// ============================================================================
475
476// ----------------------------------------------------------------------------
477// construction
478// ----------------------------------------------------------------------------
479
480wxTempFile::wxTempFile(const wxString& strName)
481{
482 Open(strName);
483}
484
485bool wxTempFile::Open(const wxString& strName)
486{
487 // we must have an absolute filename because otherwise CreateTempFileName()
488 // would create the temp file in $TMP (i.e. the system standard location
489 // for the temp files) which might be on another volume/drive/mount and
490 // wxRename()ing it later to m_strName from Commit() would then fail
491 //
492 // with the absolute filename, the temp file is created in the same
493 // directory as this one which ensures that wxRename() may work later
494 wxFileName fn(strName);
495 if ( !fn.IsAbsolute() )
496 {
497 fn.Normalize(wxPATH_NORM_ABSOLUTE);
498 }
499
500 m_strName = fn.GetFullPath();
501
502 m_strTemp = wxFileName::CreateTempFileName(m_strName, &m_file);
503
504 if ( m_strTemp.empty() )
505 {
506 // CreateTempFileName() failed
507 return FALSE;
508 }
509
510#ifdef __UNIX__
511 // the temp file should have the same permissions as the original one
512 mode_t mode;
513
514 wxStructStat st;
515 if ( stat( (const char*) m_strName.fn_str(), &st) == 0 )
516 {
517 mode = st.st_mode;
518 }
519 else
520 {
521 // file probably didn't exist, just give it the default mode _using_
522 // user's umask (new files creation should respect umask)
523 mode_t mask = umask(0777);
524 mode = 0666 & ~mask;
525 umask(mask);
526 }
527
528 if ( chmod( (const char*) m_strTemp.fn_str(), mode) == -1 )
529 {
530 wxLogSysError(_("Failed to set temporary file permissions"));
531 }
532#endif // Unix
533
534 return TRUE;
535}
536
537// ----------------------------------------------------------------------------
538// destruction
539// ----------------------------------------------------------------------------
540
541wxTempFile::~wxTempFile()
542{
543 if ( IsOpened() )
544 Discard();
545}
546
547bool wxTempFile::Commit()
548{
549 m_file.Close();
550
551 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
552 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
553 return FALSE;
554 }
555
556 if ( wxRename(m_strTemp, m_strName) != 0 ) {
557 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
558 return FALSE;
559 }
560
561 return TRUE;
562}
563
564void wxTempFile::Discard()
565{
566 m_file.Close();
567 if ( wxRemove(m_strTemp) != 0 )
568 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
569}
570
571#endif // wxUSE_FILE
572