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