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