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