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