Oops, Watcom doesn't have _mktemp in DOS
[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(__DOS__) && defined(__WATCOMC__)
63 #include <io.h>
64 #elif (defined(__WXPM__))
65 #include <io.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 #if __MSL__ < 0x6000
73 int access( const char *path, int mode ) { return 0 ; }
74 #else
75 int _access( const char *path, int mode ) { return 0 ; }
76 #endif
77 char* mktemp( char * path ) { return path ;}
78 #include <stat.h>
79 #define W_OK 2
80 #define R_OK 4
81 #include <unistd.h>
82 #else
83 #error "Please specify the header with file functions declarations."
84 #endif //Win/UNIX
85
86 #include <stdio.h> // SEEK_xxx constants
87 #include <fcntl.h> // O_RDONLY &c
88
89 #ifndef __MWERKS__
90 #include <sys/types.h> // needed for stat
91 #include <sys/stat.h> // stat
92 #elif ( defined(__MWERKS__) && defined(__WXMSW__) )
93 #include <sys/types.h> // needed for stat
94 #include <sys/stat.h> // stat
95 #endif
96
97 #if defined(__BORLANDC__) || defined(_MSC_VER)
98 #define W_OK 2
99 #define R_OK 4
100 #endif
101
102 // there is no distinction between text and binary files under Unix, so define
103 // O_BINARY as 0 if the system headers don't do it already
104 #if defined(__UNIX__) && !defined(O_BINARY)
105 #define O_BINARY (0)
106 #endif //__UNIX__
107
108 #ifdef __SALFORDC__
109 #include <unix.h>
110 #endif
111
112 #ifndef MAX_PATH
113 #define MAX_PATH 512
114 #endif
115
116 // some broken compilers don't have 3rd argument in open() and creat()
117 #ifdef __SALFORDC__
118 #define ACCESS(access)
119 #define stat _stat
120 #else // normal compiler
121 #define ACCESS(access) , (access)
122 #endif // Salford C
123
124 // wxWindows
125 #ifndef WX_PRECOMP
126 #include "wx/string.h"
127 #include "wx/intl.h"
128 #include "wx/log.h"
129 #endif // !WX_PRECOMP
130
131 #include "wx/filename.h"
132 #include "wx/file.h"
133
134 // ============================================================================
135 // implementation of wxFile
136 // ============================================================================
137
138 // ----------------------------------------------------------------------------
139 // static functions
140 // ----------------------------------------------------------------------------
141 bool wxFile::Exists(const wxChar *name)
142 {
143 wxStructStat st;
144 #if wxUSE_UNICODE && wxMBFILES
145 wxCharBuffer fname = wxConvFile.cWC2MB(name);
146
147 return !wxAccess(fname, 0) &&
148 !wxStat(wxMBSTRINGCAST fname, &st) &&
149 (st.st_mode & S_IFREG);
150
151 #else
152 return !wxAccess(name, 0) &&
153 !wxStat(name, &st) &&
154 (st.st_mode & S_IFREG);
155 #endif
156 }
157
158 bool wxFile::Access(const wxChar *name, OpenMode mode)
159 {
160 int how = 0;
161
162 switch ( mode ) {
163 case read:
164 how = R_OK;
165 break;
166
167 case write:
168 how = W_OK;
169 break;
170
171 default:
172 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
173 }
174
175 return wxAccess(wxFNCONV(name), how) == 0;
176 }
177
178 // ----------------------------------------------------------------------------
179 // opening/closing
180 // ----------------------------------------------------------------------------
181
182 // ctors
183 wxFile::wxFile(const wxChar *szFileName, OpenMode mode)
184 {
185 m_fd = fd_invalid;
186 m_error = FALSE;
187
188 Open(szFileName, mode);
189 }
190
191 // create the file, fail if it already exists and bOverwrite
192 bool wxFile::Create(const wxChar *szFileName, bool bOverwrite, int accessMode)
193 {
194 // if bOverwrite we create a new file or truncate the existing one,
195 // otherwise we only create the new file and fail if it already exists
196 #if defined(__WXMAC__) && !defined(__UNIX__)
197 // Dominic Mazzoni [dmazzoni+@cs.cmu.edu] reports that open is still broken on the mac, so we replace
198 // int fd = open(wxUnix2MacFilename( szFileName ), O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
199 int fd = creat( szFileName , accessMode);
200 #else
201 int fd = wxOpen(wxFNCONV(szFileName),
202 O_BINARY | O_WRONLY | O_CREAT |
203 (bOverwrite ? O_TRUNC : O_EXCL)
204 ACCESS(accessMode));
205 #endif
206 if ( fd == -1 ) {
207 wxLogSysError(_("can't create file '%s'"), szFileName);
208 return FALSE;
209 }
210 else {
211 Attach(fd);
212 return TRUE;
213 }
214 }
215
216 // open the file
217 bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
218 {
219 int flags = O_BINARY;
220
221 switch ( mode ) {
222 case read:
223 flags |= O_RDONLY;
224 break;
225
226 case write_append:
227 if ( wxFile::Exists(szFileName) )
228 {
229 flags |= O_WRONLY | O_APPEND;
230 break;
231 }
232 //else: fall through as write_append is the same as write if the
233 // file doesn't exist
234
235 case write:
236 flags |= O_WRONLY | O_CREAT | O_TRUNC;
237 break;
238
239 case write_excl:
240 flags |= O_WRONLY | O_CREAT | O_EXCL;
241 break;
242
243 case read_write:
244 flags |= O_RDWR;
245 break;
246 }
247
248 int fd = wxOpen(wxFNCONV(szFileName), flags ACCESS(accessMode));
249 if ( fd == -1 ) {
250 wxLogSysError(_("can't open file '%s'"), szFileName);
251 return FALSE;
252 }
253 else {
254 Attach(fd);
255 return TRUE;
256 }
257 }
258
259 // close
260 bool wxFile::Close()
261 {
262 if ( IsOpened() ) {
263 if ( close(m_fd) == -1 ) {
264 wxLogSysError(_("can't close file descriptor %d"), m_fd);
265 m_fd = fd_invalid;
266 return FALSE;
267 }
268 else
269 m_fd = fd_invalid;
270 }
271
272 return TRUE;
273 }
274
275 // ----------------------------------------------------------------------------
276 // read/write
277 // ----------------------------------------------------------------------------
278
279 // read
280 off_t wxFile::Read(void *pBuf, off_t nCount)
281 {
282 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
283
284 #ifdef __MWERKS__
285 int iRc = ::read(m_fd, (char*) pBuf, nCount);
286 #else
287 int iRc = ::read(m_fd, pBuf, nCount);
288 #endif
289 if ( iRc == -1 ) {
290 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
291 return wxInvalidOffset;
292 }
293 else
294 return (size_t)iRc;
295 }
296
297 // write
298 size_t wxFile::Write(const void *pBuf, size_t nCount)
299 {
300 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
301
302 #ifdef __MWERKS__
303 #if __MSL__ >= 0x6000
304 int iRc = ::write(m_fd, (void*) pBuf, nCount);
305 #else
306 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
307 #endif
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 ( wxFsync(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 = wxTell(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 = wxTell(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 descriptor %d"), m_fd);
448 break;
449
450 default:
451 wxFAIL_MSG(_("invalid eof() return value."));
452 }
453
454 return TRUE;
455 }
456
457 // ============================================================================
458 // implementation of wxTempFile
459 // ============================================================================
460
461 // ----------------------------------------------------------------------------
462 // construction
463 // ----------------------------------------------------------------------------
464 wxTempFile::wxTempFile(const wxString& strName)
465 {
466 Open(strName);
467 }
468
469 bool wxTempFile::Open(const wxString& strName)
470 {
471 m_strName = strName;
472
473 m_strTemp = wxFileName::CreateTempFileName(strName);
474
475 if ( m_strTemp.empty() )
476 {
477 // CreateTempFileName() failed
478 return FALSE;
479 }
480
481 // actually open the file now (it must already exist)
482 if ( !m_file.Open(m_strTemp, wxFile::write) )
483 {
484 // opening existing file failed?
485 return FALSE;
486 }
487
488 #ifdef __UNIX__
489 // the temp file should have the same permissions as the original one
490 mode_t mode;
491
492 wxStructStat st;
493 if ( stat(strName.fn_str(), &st) == 0 )
494 {
495 mode = st.st_mode;
496 }
497 else
498 {
499 // file probably didn't exist, just give it the default mode _using_
500 // user's umask (new files creation should respect umask)
501 mode_t mask = umask(0777);
502 mode = 0666 & ~mask;
503 umask(mask);
504 }
505
506 if ( chmod(m_strTemp.mb_str(), mode) == -1 )
507 {
508 wxLogSysError(_("Failed to set temporary file permissions"));
509 }
510 #endif // Unix
511
512 return TRUE;
513 }
514
515 // ----------------------------------------------------------------------------
516 // destruction
517 // ----------------------------------------------------------------------------
518
519 wxTempFile::~wxTempFile()
520 {
521 if ( IsOpened() )
522 Discard();
523 }
524
525 bool wxTempFile::Commit()
526 {
527 m_file.Close();
528
529 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
530 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
531 return FALSE;
532 }
533
534 if ( wxRename(m_strTemp, m_strName) != 0 ) {
535 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
536 return FALSE;
537 }
538
539 return TRUE;
540 }
541
542 void wxTempFile::Discard()
543 {
544 m_file.Close();
545 if ( wxRemove(m_strTemp) != 0 )
546 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
547 }
548
549 #endif // wxUSE_FILE
550