wxTempFile now respects the access rights under Unix
[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 #include "wx/defs.h"
24
25 #ifdef __BORLANDC__
26 #pragma hdrstop
27 #endif
28
29 // standard
30 #if defined(__WXMSW__) && !defined(__GNUWIN32__)
31 #include <io.h>
32
33 #ifndef __SALFORDC__
34 #define WIN32_LEAN_AND_MEAN
35 #define NOSERVICE
36 #define NOIME
37 #define NOATOM
38 #define NOGDI
39 #define NOGDICAPMASKS
40 #define NOMETAFILE
41 #define NOMINMAX
42 #define NOMSG
43 #define NOOPENFILE
44 #define NORASTEROPS
45 #define NOSCROLL
46 #define NOSOUND
47 #define NOSYSMETRICS
48 #define NOTEXTMETRIC
49 #define NOWH
50 #define NOCOMM
51 #define NOKANJI
52 #define NOCRYPT
53 #define NOMCX
54 #endif
55
56 #include <windows.h> // for GetTempFileName
57 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
58 #include <unistd.h>
59 #ifdef __GNUWIN32__
60 #include <windows.h>
61 #endif
62 #elif (defined(__WXSTUBS__))
63 // Have to ifdef this for different environments
64 #include <io.h>
65 #elif (defined(__WXMAC__))
66 int access( const char *path, int mode ) { return 0 ; }
67 char* mktemp( char * path ) { return path ;}
68 #include <unistd.h>
69 #include <unix.h>
70 #define W_OK 2
71 #define R_OK 4
72 #else
73 #error "Please specify the header with file functions declarations."
74 #endif //Win/UNIX
75
76 #include <stdio.h> // SEEK_xxx constants
77 #include <fcntl.h> // O_RDONLY &c
78
79 #ifndef __MWERKS__
80 #include <sys/types.h> // needed for stat
81 #include <sys/stat.h> // stat
82 #endif
83
84 // Microsoft compiler loves underscores, feed them to it
85 #ifdef __VISUALC__
86 // functions
87 #define open _open
88 #define close _close
89 #define read _read
90 #define write _write
91 #define lseek _lseek
92 #define fsync _commit
93 #define access _access
94 #define eof _eof
95
96 // types
97 #define stat _stat
98
99 // constants
100
101 #define O_RDONLY _O_RDONLY
102 #define O_WRONLY _O_WRONLY
103 #define O_RDWR _O_RDWR
104 #define O_EXCL _O_EXCL
105 #define O_CREAT _O_CREAT
106 #define O_BINARY _O_BINARY
107
108 #define S_IFDIR _S_IFDIR
109 #define S_IFREG _S_IFREG
110 #else
111 #define tell(fd) lseek(fd, 0, SEEK_CUR)
112 #endif // VC++
113
114 #if defined(__BORLANDC__) || defined(_MSC_VER)
115 #define W_OK 2
116 #define R_OK 4
117 #endif
118
119 // there is no distinction between text and binary files under Unix
120 #ifdef __UNIX__
121 #define O_BINARY (0)
122 #endif //__UNIX__
123
124 #ifdef __SALFORDC__
125 #include <unix.h>
126 #endif
127
128 // wxWindows
129 #include <wx/string.h>
130 #include <wx/intl.h>
131 #include <wx/file.h>
132 #include <wx/log.h>
133
134 #ifndef MAX_PATH
135 #define MAX_PATH 512
136 #endif
137
138 #ifdef __WXMAC__
139 char gwxMacFileName[ MAX_PATH ] ;
140 char gwxMacFileName2[ MAX_PATH ] ;
141 char gwxMacFileName3[ MAX_PATH ] ;
142 #endif
143
144 // some broken compilers don't have 3rd argument in open() and creat()
145 #ifdef __SALFORDC__
146 #define ACCESS(access)
147 #define stat _stat
148 #else // normal compiler
149 #define ACCESS(access) , (access)
150 #endif // Salford C
151
152 // ============================================================================
153 // implementation of wxFile
154 // ============================================================================
155
156 // ----------------------------------------------------------------------------
157 // static functions
158 // ----------------------------------------------------------------------------
159 bool wxFile::Exists(const char *name)
160 {
161 struct stat st;
162
163 return !access(name, 0) &&
164 !stat((char*) name, &st) &&
165 (st.st_mode & S_IFREG);
166 }
167
168 bool wxFile::Access(const char *name, OpenMode mode)
169 {
170 int how = 0;
171
172 switch ( mode ) {
173 case read:
174 how = R_OK;
175 break;
176
177 case write:
178 how = W_OK;
179 break;
180
181 default:
182 wxFAIL_MSG("bad wxFile::Access mode parameter.");
183 }
184
185 return access(name, how) == 0;
186 }
187
188 // ----------------------------------------------------------------------------
189 // opening/closing
190 // ----------------------------------------------------------------------------
191
192 // ctors
193 wxFile::wxFile(const char *szFileName, OpenMode mode)
194 {
195 m_fd = fd_invalid;
196 m_error = FALSE;
197
198 Open(szFileName, mode);
199 }
200
201 // dtor
202 wxFile::~wxFile()
203 {
204 Close();
205 }
206
207 // create the file, fail if it already exists and bOverwrite
208 bool wxFile::Create(const char *szFileName, bool bOverwrite, int accessMode)
209 {
210 // if bOverwrite we create a new file or truncate the existing one,
211 // otherwise we only create the new file and fail if it already exists
212 int fd = open(szFileName,
213 O_WRONLY | O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL)
214 ACCESS(accessMode));
215
216 if ( fd == -1 ) {
217 wxLogSysError(_("can't create file '%s'"), szFileName);
218 return FALSE;
219 }
220 else {
221 Attach(fd);
222 return TRUE;
223 }
224 }
225
226 // open the file
227 bool wxFile::Open(const char *szFileName, OpenMode mode, int accessMode)
228 {
229 int flags = O_BINARY;
230
231 switch ( mode ) {
232 case read:
233 flags |= O_RDONLY;
234 break;
235
236 case write:
237 flags |= O_WRONLY | O_CREAT | O_TRUNC;
238 break;
239
240 case write_append:
241 flags |= O_WRONLY | O_APPEND;
242 break;
243
244 case read_write:
245 flags |= O_RDWR;
246 break;
247 }
248
249 int fd = open(szFileName, flags ACCESS(accessMode));
250
251 if ( fd == -1 ) {
252 wxLogSysError(_("can't open file '%s'"), szFileName);
253 return FALSE;
254 }
255 else {
256 Attach(fd);
257 return TRUE;
258 }
259 }
260
261 // close
262 bool wxFile::Close()
263 {
264 if ( IsOpened() ) {
265 if ( close(m_fd) == -1 ) {
266 wxLogSysError(_("can't close file descriptor %d"), m_fd);
267 m_fd = fd_invalid;
268 return FALSE;
269 }
270 else
271 m_fd = fd_invalid;
272 }
273
274 return TRUE;
275 }
276
277 // ----------------------------------------------------------------------------
278 // read/write
279 // ----------------------------------------------------------------------------
280
281 // read
282 off_t wxFile::Read(void *pBuf, off_t nCount)
283 {
284 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
285
286 #ifdef __MWERKS__
287 int iRc = ::read(m_fd, (char*) pBuf, nCount);
288 #else
289 int iRc = ::read(m_fd, pBuf, nCount);
290 #endif
291 if ( iRc == -1 ) {
292 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
293 return wxInvalidOffset;
294 }
295 else
296 return (size_t)iRc;
297 }
298
299 // write
300 size_t wxFile::Write(const void *pBuf, size_t nCount)
301 {
302 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
303
304 #ifdef __MWERKS__
305 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
306 #else
307 int iRc = ::write(m_fd, pBuf, nCount);
308 #endif
309 if ( iRc == -1 ) {
310 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
311 m_error = TRUE;
312 return 0;
313 }
314 else
315 return iRc;
316 }
317
318 // flush
319 bool wxFile::Flush()
320 {
321 if ( IsOpened() ) {
322 #if defined(__VISUALC__) || wxHAVE_FSYNC
323 if ( fsync(m_fd) == -1 )
324 {
325 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
326 return FALSE;
327 }
328 #else // no fsync
329 // just do nothing
330 #endif // fsync
331 }
332
333 return TRUE;
334 }
335
336 // ----------------------------------------------------------------------------
337 // seek
338 // ----------------------------------------------------------------------------
339
340 // seek
341 off_t wxFile::Seek(off_t ofs, wxSeekMode mode)
342 {
343 wxASSERT( IsOpened() );
344
345 int flag = -1;
346 switch ( mode ) {
347 case wxFromStart:
348 flag = SEEK_SET;
349 break;
350
351 case wxFromCurrent:
352 flag = SEEK_CUR;
353 break;
354
355 case wxFromEnd:
356 flag = SEEK_END;
357 break;
358
359 default:
360 wxFAIL_MSG(_("unknown seek origin"));
361 }
362
363 int iRc = lseek(m_fd, ofs, flag);
364 if ( iRc == -1 ) {
365 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
366 return wxInvalidOffset;
367 }
368 else
369 return (off_t)iRc;
370 }
371
372 // get current off_t
373 off_t wxFile::Tell() const
374 {
375 wxASSERT( IsOpened() );
376
377 int iRc = tell(m_fd);
378 if ( iRc == -1 ) {
379 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
380 return wxInvalidOffset;
381 }
382 else
383 return (off_t)iRc;
384 }
385
386 // get current file length
387 off_t wxFile::Length() const
388 {
389 wxASSERT( IsOpened() );
390
391 #ifdef __VISUALC__
392 int iRc = _filelength(m_fd);
393 #else // !VC++
394 int iRc = tell(m_fd);
395 if ( iRc != -1 ) {
396 // @ have to use const_cast :-(
397 int iLen = ((wxFile *)this)->SeekEnd();
398 if ( iLen != -1 ) {
399 // restore old position
400 if ( ((wxFile *)this)->Seek(iRc) == -1 ) {
401 // error
402 iLen = -1;
403 }
404 }
405
406 iRc = iLen;
407 }
408 #endif // VC++
409
410 if ( iRc == -1 ) {
411 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
412 return wxInvalidOffset;
413 }
414 else
415 return (off_t)iRc;
416 }
417
418 // is end of file reached?
419 bool wxFile::Eof() const
420 {
421 wxASSERT( IsOpened() );
422
423 int iRc;
424
425 #if defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
426 // @@ this doesn't work, of course, on unseekable file descriptors
427 off_t ofsCur = Tell(),
428 ofsMax = Length();
429 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
430 iRc = -1;
431 else
432 iRc = ofsCur == ofsMax;
433 #else // Windows and "native" compiler
434 iRc = eof(m_fd);
435 #endif // Windows/Unix
436
437 switch ( iRc ) {
438 case 1:
439 break;
440
441 case 0:
442 return FALSE;
443
444 case -1:
445 wxLogSysError(_("can't determine if the end of file is reached on \
446 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 // we want to create the file in the same directory as strName because
473 // otherwise rename() in Commit() might not work (if the files are on
474 // different partitions for example). Unfortunately, the only standard
475 // (POSIX) temp file creation function tmpnam() can't do it.
476 #if defined(__UNIX__) || defined(__WXSTUBS__)|| defined( __WXMAC__ )
477 static const char *szMktempSuffix = "XXXXXX";
478 m_strTemp << strName << szMktempSuffix;
479 mktemp((char *)m_strTemp.c_str()); // will do because length doesn't change
480 #else // Windows
481 wxString strPath;
482 wxSplitPath(strName, &strPath, NULL, NULL);
483 if ( strPath.IsEmpty() )
484 strPath = '.'; // GetTempFileName will fail if we give it empty string
485 #ifdef __WIN32__
486 if ( !GetTempFileName(strPath, "wx_",0, m_strTemp.GetWriteBuf(MAX_PATH)) )
487 #else
488 // Not sure why MSVC++ 1.5 header defines first param as BYTE - bug?
489 if ( !GetTempFileName((BYTE) (const char*) strPath, "wx_",0, m_strTemp.GetWriteBuf(MAX_PATH)) )
490 #endif
491 wxLogLastError("GetTempFileName");
492 m_strTemp.UngetWriteBuf();
493 #endif // Windows/Unix
494
495 int access = wxS_DEFAULT;
496 #ifdef __UNIX__
497 // create the file with the same mode as the original one under Unix
498 struct stat st;
499 if ( stat(strName, &st) == 0 )
500 {
501 // this assumes that only lower bits of st_mode contain the access
502 // rights, but it's true for at least all Unices which have S_IXXXX()
503 // macros, so should not be less portable than using (not POSIX)
504 // S_IFREG &c
505 access = st.st_mode & 0777;
506 }
507 else
508 {
509 wxLogLastError("stat");
510 }
511
512 // we want to create the file with exactly the same access rights as the
513 // original one, so disable the user's umask for the moment
514 mode_t umaskOld = umask(0);
515 #endif // Unix
516
517 bool ok = m_file.Open(m_strTemp, wxFile::write, access);
518
519 #ifdef __UNIX__
520 // restore umask now that the file is created
521 (void)umask(umaskOld);
522 #endif // Unix
523
524 return ok;
525 }
526
527 // ----------------------------------------------------------------------------
528 // destruction
529 // ----------------------------------------------------------------------------
530
531 wxTempFile::~wxTempFile()
532 {
533 if ( IsOpened() )
534 Discard();
535 }
536
537 bool wxTempFile::Commit()
538 {
539 m_file.Close();
540
541 if ( wxFile::Exists(m_strName) && remove(m_strName) != 0 ) {
542 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
543 return FALSE;
544 }
545
546 if ( rename(m_strTemp, m_strName) != 0 ) {
547 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
548 return FALSE;
549 }
550
551 return TRUE;
552 }
553
554 void wxTempFile::Discard()
555 {
556 m_file.Close();
557 if ( remove(m_strTemp) != 0 )
558 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
559 }