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