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