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