1. new wxFFile class - as wxFile but uses fopen/fread/fseek... instead of
[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 // create the file, fail if it already exists and bOverwrite
210 bool wxFile::Create(const wxChar *szFileName, bool bOverwrite, int accessMode)
211 {
212 // if bOverwrite we create a new file or truncate the existing one,
213 // otherwise we only create the new file and fail if it already exists
214 int fd = open(wxFNCONV(szFileName),
215 O_WRONLY | O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL)
216 ACCESS(accessMode));
217
218 if ( fd == -1 ) {
219 wxLogSysError(_("can't create file '%s'"), szFileName);
220 return FALSE;
221 }
222 else {
223 Attach(fd);
224 return TRUE;
225 }
226 }
227
228 // open the file
229 bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
230 {
231 int flags = O_BINARY;
232
233 switch ( mode ) {
234 case read:
235 flags |= O_RDONLY;
236 break;
237
238 case write:
239 flags |= O_WRONLY | O_CREAT | O_TRUNC;
240 break;
241
242 case write_append:
243 flags |= O_WRONLY | O_APPEND;
244 break;
245
246 case read_write:
247 flags |= O_RDWR;
248 break;
249 }
250
251 int fd = open(wxFNCONV(szFileName), flags ACCESS(accessMode));
252
253 if ( fd == -1 ) {
254 wxLogSysError(_("can't open file '%s'"), szFileName);
255 return FALSE;
256 }
257 else {
258 Attach(fd);
259 return TRUE;
260 }
261 }
262
263 // close
264 bool wxFile::Close()
265 {
266 if ( IsOpened() ) {
267 if ( close(m_fd) == -1 ) {
268 wxLogSysError(_("can't close file descriptor %d"), m_fd);
269 m_fd = fd_invalid;
270 return FALSE;
271 }
272 else
273 m_fd = fd_invalid;
274 }
275
276 return TRUE;
277 }
278
279 // ----------------------------------------------------------------------------
280 // read/write
281 // ----------------------------------------------------------------------------
282
283 // read
284 off_t wxFile::Read(void *pBuf, off_t nCount)
285 {
286 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
287
288 #ifdef __MWERKS__
289 int iRc = ::read(m_fd, (char*) pBuf, nCount);
290 #else
291 int iRc = ::read(m_fd, pBuf, nCount);
292 #endif
293 if ( iRc == -1 ) {
294 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
295 return wxInvalidOffset;
296 }
297 else
298 return (size_t)iRc;
299 }
300
301 // write
302 size_t wxFile::Write(const void *pBuf, size_t nCount)
303 {
304 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
305
306 #ifdef __MWERKS__
307 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
308 #else
309 int iRc = ::write(m_fd, pBuf, nCount);
310 #endif
311 if ( iRc == -1 ) {
312 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
313 m_error = TRUE;
314 return 0;
315 }
316 else
317 return iRc;
318 }
319
320 // flush
321 bool wxFile::Flush()
322 {
323 if ( IsOpened() ) {
324 #if defined(__VISUALC__) || wxHAVE_FSYNC
325 if ( fsync(m_fd) == -1 )
326 {
327 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
328 return FALSE;
329 }
330 #else // no fsync
331 // just do nothing
332 #endif // fsync
333 }
334
335 return TRUE;
336 }
337
338 // ----------------------------------------------------------------------------
339 // seek
340 // ----------------------------------------------------------------------------
341
342 // seek
343 off_t wxFile::Seek(off_t ofs, wxSeekMode mode)
344 {
345 wxASSERT( IsOpened() );
346
347 int origin;
348 switch ( mode ) {
349 default:
350 wxFAIL_MSG(_("unknown seek origin"));
351
352 case wxFromStart:
353 origin = SEEK_SET;
354 break;
355
356 case wxFromCurrent:
357 origin = SEEK_CUR;
358 break;
359
360 case wxFromEnd:
361 origin = SEEK_END;
362 break;
363 }
364
365 int iRc = lseek(m_fd, ofs, origin);
366 if ( iRc == -1 ) {
367 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
368 return wxInvalidOffset;
369 }
370 else
371 return (off_t)iRc;
372 }
373
374 // get current off_t
375 off_t wxFile::Tell() const
376 {
377 wxASSERT( IsOpened() );
378
379 int iRc = tell(m_fd);
380 if ( iRc == -1 ) {
381 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
382 return wxInvalidOffset;
383 }
384 else
385 return (off_t)iRc;
386 }
387
388 // get current file length
389 off_t wxFile::Length() const
390 {
391 wxASSERT( IsOpened() );
392
393 #ifdef __VISUALC__
394 int iRc = _filelength(m_fd);
395 #else // !VC++
396 int iRc = tell(m_fd);
397 if ( iRc != -1 ) {
398 // @ have to use const_cast :-(
399 int iLen = ((wxFile *)this)->SeekEnd();
400 if ( iLen != -1 ) {
401 // restore old position
402 if ( ((wxFile *)this)->Seek(iRc) == -1 ) {
403 // error
404 iLen = -1;
405 }
406 }
407
408 iRc = iLen;
409 }
410 #endif // VC++
411
412 if ( iRc == -1 ) {
413 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
414 return wxInvalidOffset;
415 }
416 else
417 return (off_t)iRc;
418 }
419
420 // is end of file reached?
421 bool wxFile::Eof() const
422 {
423 wxASSERT( IsOpened() );
424
425 int iRc;
426
427 #if defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
428 // @@ this doesn't work, of course, on unseekable file descriptors
429 off_t ofsCur = Tell(),
430 ofsMax = Length();
431 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
432 iRc = -1;
433 else
434 iRc = ofsCur == ofsMax;
435 #else // Windows and "native" compiler
436 iRc = eof(m_fd);
437 #endif // Windows/Unix
438
439 switch ( iRc ) {
440 case 1:
441 break;
442
443 case 0:
444 return FALSE;
445
446 case -1:
447 wxLogSysError(_("can't determine if the end of file is reached on \
448 descriptor %d"), m_fd);
449 break;
450
451 default:
452 wxFAIL_MSG(_("invalid eof() return value."));
453 }
454
455 return TRUE;
456 }
457
458 // ============================================================================
459 // implementation of wxTempFile
460 // ============================================================================
461
462 // ----------------------------------------------------------------------------
463 // construction
464 // ----------------------------------------------------------------------------
465 wxTempFile::wxTempFile(const wxString& strName)
466 {
467 Open(strName);
468 }
469
470 bool wxTempFile::Open(const wxString& strName)
471 {
472 m_strName = strName;
473
474 // we want to create the file in the same directory as strName because
475 // otherwise rename() in Commit() might not work (if the files are on
476 // different partitions for example). Unfortunately, the only standard
477 // (POSIX) temp file creation function tmpnam() can't do it.
478 #if defined(__UNIX__) || defined(__WXSTUBS__)|| defined( __WXMAC__ )
479 static const wxChar *szMktempSuffix = _T("XXXXXX");
480 m_strTemp << strName << szMktempSuffix;
481 mktemp(MBSTRINGCAST m_strTemp.mb_str()); // will do because length doesn't change
482 #else // Windows
483 wxString strPath;
484 wxSplitPath(strName, &strPath, NULL, NULL);
485 if ( strPath.IsEmpty() )
486 strPath = _T('.'); // GetTempFileName will fail if we give it empty string
487 #ifdef __WIN32__
488 if ( !GetTempFileName(strPath, _T("wx_"),0, m_strTemp.GetWriteBuf(MAX_PATH)) )
489 #else
490 // Not sure why MSVC++ 1.5 header defines first param as BYTE - bug?
491 if ( !GetTempFileName((BYTE) (const wxChar*) strPath, _T("wx_"),0, m_strTemp.GetWriteBuf(MAX_PATH)) )
492 #endif
493 wxLogLastError(_T("GetTempFileName"));
494 m_strTemp.UngetWriteBuf();
495 #endif // Windows/Unix
496
497 int access = wxS_DEFAULT;
498 #ifdef __UNIX__
499 // create the file with the same mode as the original one under Unix
500 mode_t umaskOld = 0; // just to suppress compiler warning
501 bool changedUmask;
502
503 struct stat st;
504 if ( stat(strName.fn_str(), &st) == 0 )
505 {
506 // this assumes that only lower bits of st_mode contain the access
507 // rights, but it's true for at least all Unices which have S_IXXXX()
508 // macros, so should not be less portable than using (not POSIX)
509 // S_IFREG &c
510 access = st.st_mode & 0777;
511
512 // we want to create the file with exactly the same access rights as
513 // the original one, so disable the user's umask for the moment
514 umaskOld = umask(0);
515 changedUmask = TRUE;
516 }
517 else
518 {
519 // file probably didn't exist, just create with default mode _using_
520 // user's umask (new files creation should respet umask)
521 changedUmask = FALSE;
522 }
523 #endif // Unix
524
525 bool ok = m_file.Open(m_strTemp, wxFile::write, access);
526
527 #ifdef __UNIX__
528 if ( changedUmask )
529 {
530 // restore umask now that the file is created
531 (void)umask(umaskOld);
532 }
533 #endif // Unix
534
535 return ok;
536 }
537
538 // ----------------------------------------------------------------------------
539 // destruction
540 // ----------------------------------------------------------------------------
541
542 wxTempFile::~wxTempFile()
543 {
544 if ( IsOpened() )
545 Discard();
546 }
547
548 bool wxTempFile::Commit()
549 {
550 m_file.Close();
551
552 if ( wxFile::Exists(m_strName) && remove(m_strName.fn_str()) != 0 ) {
553 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
554 return FALSE;
555 }
556
557 if ( rename(m_strTemp.fn_str(), m_strName.fn_str()) != 0 ) {
558 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
559 return FALSE;
560 }
561
562 return TRUE;
563 }
564
565 void wxTempFile::Discard()
566 {
567 m_file.Close();
568 if ( remove(m_strTemp.fn_str()) != 0 )
569 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
570 }
571
572 #endif
573