]> git.saurik.com Git - wxWidgets.git/blob - src/common/file.cpp
some != NULL checks
[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 #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, so define
126 // O_BINARY as 0 if the system headers don't do it already
127 #if defined(__UNIX__) && !defined(O_BINARY)
128 #define O_BINARY (0)
129 #endif //__UNIX__
130
131 #ifdef __SALFORDC__
132 #include <unix.h>
133 #endif
134
135 // wxWindows
136 #include "wx/string.h"
137 #include "wx/intl.h"
138 #include "wx/file.h"
139 #include "wx/log.h"
140
141 #ifndef MAX_PATH
142 #define MAX_PATH 512
143 #endif
144
145 // some broken compilers don't have 3rd argument in open() and creat()
146 #ifdef __SALFORDC__
147 #define ACCESS(access)
148 #define stat _stat
149 #else // normal compiler
150 #define ACCESS(access) , (access)
151 #endif // Salford C
152
153 // ============================================================================
154 // implementation of wxFile
155 // ============================================================================
156
157 // ----------------------------------------------------------------------------
158 // static functions
159 // ----------------------------------------------------------------------------
160 bool wxFile::Exists(const wxChar *name)
161 {
162 struct stat st;
163 #if wxUSE_UNICODE && wxMBFILES
164 wxCharBuffer fname = wxConvFile.cWC2MB(name);
165
166 #ifdef __WXMAC__
167 return !access(wxUnix2MacFilename( name ) , 0) && !stat(wxUnix2MacFilename( name ), &st) && (st.st_mode & S_IFREG);
168 #else
169 return !access(fname, 0) &&
170 !stat(wxMBSTRINGCAST fname, &st) &&
171 (st.st_mode & S_IFREG);
172 #endif
173 #else
174 #ifdef __WXMAC__
175 return !access(wxUnix2MacFilename( name ) , 0) && !stat(wxUnix2MacFilename( name ), &st) && (st.st_mode & S_IFREG);
176 #else
177 return !access(name, 0) &&
178 !stat((wxChar*) name, &st) &&
179 (st.st_mode & S_IFREG);
180 #endif
181 #endif
182 }
183
184 bool wxFile::Access(const wxChar *name, OpenMode mode)
185 {
186 int how = 0;
187
188 switch ( mode ) {
189 case read:
190 how = R_OK;
191 break;
192
193 case write:
194 how = W_OK;
195 break;
196
197 default:
198 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
199 }
200
201 return access(wxFNCONV(name), how) == 0;
202 }
203
204 // ----------------------------------------------------------------------------
205 // opening/closing
206 // ----------------------------------------------------------------------------
207
208 // ctors
209 wxFile::wxFile(const wxChar *szFileName, OpenMode mode)
210 {
211 m_fd = fd_invalid;
212 m_error = FALSE;
213
214 Open(szFileName, mode);
215 }
216
217 // create the file, fail if it already exists and bOverwrite
218 bool wxFile::Create(const wxChar *szFileName, bool bOverwrite, int accessMode)
219 {
220 // if bOverwrite we create a new file or truncate the existing one,
221 // otherwise we only create the new file and fail if it already exists
222 #ifdef __WXMAC__
223 int fd = open(wxUnix2MacFilename( szFileName ), O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
224 #else
225 int fd = open(wxFNCONV(szFileName),
226 O_BINARY | O_WRONLY | O_CREAT |
227 (bOverwrite ? O_TRUNC : O_EXCL)
228 ACCESS(accessMode));
229 #endif
230 if ( fd == -1 ) {
231 wxLogSysError(_("can't create file '%s'"), szFileName);
232 return FALSE;
233 }
234 else {
235 Attach(fd);
236 return TRUE;
237 }
238 }
239
240 // open the file
241 bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
242 {
243 int flags = O_BINARY;
244
245 switch ( mode ) {
246 case read:
247 flags |= O_RDONLY;
248 break;
249
250 case write:
251 flags |= O_WRONLY | O_CREAT | O_TRUNC;
252 break;
253
254 case write_append:
255 flags |= O_WRONLY | O_APPEND;
256 break;
257
258 case read_write:
259 flags |= O_RDWR;
260 break;
261 }
262
263 #ifdef __WXMAC__
264 int fd = open(wxUnix2MacFilename( szFileName ), flags, access);
265 #else
266 int fd = open(wxFNCONV(szFileName), flags ACCESS(accessMode));
267 #endif
268 if ( fd == -1 ) {
269 wxLogSysError(_("can't open file '%s'"), szFileName);
270 return FALSE;
271 }
272 else {
273 Attach(fd);
274 return TRUE;
275 }
276 }
277
278 // close
279 bool wxFile::Close()
280 {
281 if ( IsOpened() ) {
282 if ( close(m_fd) == -1 ) {
283 wxLogSysError(_("can't close file descriptor %d"), m_fd);
284 m_fd = fd_invalid;
285 return FALSE;
286 }
287 else
288 m_fd = fd_invalid;
289 }
290
291 return TRUE;
292 }
293
294 // ----------------------------------------------------------------------------
295 // read/write
296 // ----------------------------------------------------------------------------
297
298 // read
299 off_t wxFile::Read(void *pBuf, off_t nCount)
300 {
301 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
302
303 #ifdef __MWERKS__
304 int iRc = ::read(m_fd, (char*) pBuf, nCount);
305 #else
306 int iRc = ::read(m_fd, pBuf, nCount);
307 #endif
308 if ( iRc == -1 ) {
309 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
310 return wxInvalidOffset;
311 }
312 else
313 return (size_t)iRc;
314 }
315
316 // write
317 size_t wxFile::Write(const void *pBuf, size_t nCount)
318 {
319 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
320
321 #ifdef __MWERKS__
322 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
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
336 bool wxFile::Flush()
337 {
338 if ( IsOpened() ) {
339 #if defined(__VISUALC__) || wxHAVE_FSYNC
340 if ( fsync(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
358 off_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
390 off_t wxFile::Tell() const
391 {
392 wxASSERT( IsOpened() );
393
394 int iRc = tell(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
404 off_t wxFile::Length() const
405 {
406 wxASSERT( IsOpened() );
407
408 #ifdef __VISUALC__
409 int iRc = _filelength(m_fd);
410 #else // !VC++
411 int iRc = tell(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?
436 bool wxFile::Eof() const
437 {
438 wxASSERT( IsOpened() );
439
440 int iRc;
441
442 #if 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 wxTempFile::wxTempFile(const wxString& strName)
480 {
481 Open(strName);
482 }
483
484 bool wxTempFile::Open(const wxString& strName)
485 {
486 m_strName = strName;
487
488 // we want to create the file in the same directory as strName because
489 // otherwise rename() in Commit() might not work (if the files are on
490 // different partitions for example). Unfortunately, the only standard
491 // (POSIX) temp file creation function tmpnam() can't do it.
492 #if defined(__UNIX__) || defined(__WXSTUBS__)|| defined( __WXMAC__ )
493 static const wxChar *szMktempSuffix = wxT("XXXXXX");
494 m_strTemp << strName << szMktempSuffix;
495 // can use the cast because length doesn't change
496 mktemp(wxMBSTRINGCAST m_strTemp.mb_str());
497 #elif defined(__WXPM__)
498 // for now just create a file
499 // future enhancements can be to set some extended attributes for file systems
500 // OS/2 supports that have them (HPFS, FAT32) and security (HPFS386)
501 static const wxChar *szMktempSuffix = wxT("XXX");
502 m_strTemp << strName << szMktempSuffix;
503 mkdir(m_strTemp.GetWriteBuf(MAX_PATH));
504 #else // Windows
505 wxString strPath;
506 wxSplitPath(strName, &strPath, NULL, NULL);
507 if ( strPath.IsEmpty() )
508 strPath = wxT('.'); // GetTempFileName will fail if we give it empty string
509 #ifdef __WIN32__
510 if ( !GetTempFileName(strPath, wxT("wx_"),0, m_strTemp.GetWriteBuf(MAX_PATH)) )
511 #else
512 // Not sure why MSVC++ 1.5 header defines first param as BYTE - bug?
513 if ( !GetTempFileName((BYTE) (DWORD)(const wxChar*) strPath, wxT("wx_"),0, m_strTemp.GetWriteBuf(MAX_PATH)) )
514 #endif
515 wxLogLastError(wxT("GetTempFileName"));
516 m_strTemp.UngetWriteBuf();
517 #endif // Windows/Unix
518
519 int access = wxS_DEFAULT;
520 #ifdef __UNIX__
521 // create the file with the same mode as the original one under Unix
522 mode_t umaskOld = 0; // just to suppress compiler warning
523 bool changedUmask;
524
525 struct stat st;
526 if ( stat(strName.fn_str(), &st) == 0 )
527 {
528 // this assumes that only lower bits of st_mode contain the access
529 // rights, but it's true for at least all Unices which have S_IXXXX()
530 // macros, so should not be less portable than using (not POSIX)
531 // S_IFREG &c
532 access = st.st_mode & 0777;
533
534 // we want to create the file with exactly the same access rights as
535 // the original one, so disable the user's umask for the moment
536 umaskOld = umask(0);
537 changedUmask = TRUE;
538 }
539 else
540 {
541 // file probably didn't exist, just create with default mode _using_
542 // user's umask (new files creation should respet umask)
543 changedUmask = FALSE;
544 }
545 #endif // Unix
546
547 bool ok = m_file.Open(m_strTemp, wxFile::write, access);
548
549 #ifdef __UNIX__
550 if ( changedUmask )
551 {
552 // restore umask now that the file is created
553 (void)umask(umaskOld);
554 }
555 #endif // Unix
556
557 return ok;
558 }
559
560 // ----------------------------------------------------------------------------
561 // destruction
562 // ----------------------------------------------------------------------------
563
564 wxTempFile::~wxTempFile()
565 {
566 if ( IsOpened() )
567 Discard();
568 }
569
570 bool wxTempFile::Commit()
571 {
572 m_file.Close();
573
574 #ifndef __WXMAC__
575 if ( wxFile::Exists(m_strName) && remove(m_strName.fn_str()) != 0 ) {
576 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
577 return FALSE;
578 }
579
580 if ( rename(m_strTemp.fn_str(), m_strName.fn_str()) != 0 ) {
581 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
582 return FALSE;
583 }
584 #else
585 if ( wxFile::Exists(m_strName) && remove(wxUnix2MacFilename( m_strName )) != 0 ) {
586 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
587 return FALSE;
588 }
589
590 if ( rename(wxUnix2MacFilename( m_strTemp ), wxUnix2MacFilename( m_strName )) != 0 ) {
591 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
592 return FALSE;
593 }
594 #endif
595
596 return TRUE;
597 }
598
599 void wxTempFile::Discard()
600 {
601 m_file.Close();
602 #ifndef __WXMAC__
603 if ( remove(m_strTemp.fn_str()) != 0 )
604 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
605 #else
606 if ( remove( wxUnix2MacFilename(m_strTemp.fn_str())) != 0 )
607 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
608 #endif
609 }
610
611 #endif
612