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