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