]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/filefn.cpp
Reinsert missing ctor removed in date/time tidy
[wxWidgets.git] / src / common / filefn.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: filefn.cpp
3// Purpose: File- and directory-related functions
4// Author: Julian Smart
5// Modified by:
6// Created: 29/01/98
7// RCS-ID: $Id$
8// Copyright: (c) 1998 Julian Smart
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20#ifdef __GNUG__
21 #pragma implementation "filefn.h"
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26#include "wx/defs.h"
27
28#ifdef __BORLANDC__
29 #pragma hdrstop
30#endif
31
32#include "wx/utils.h"
33#include "wx/intl.h"
34#include "wx/file.h"
35#include "wx/filename.h"
36#include "wx/dir.h"
37
38// there are just too many of those...
39#ifdef __VISUALC__
40 #pragma warning(disable:4706) // assignment within conditional expression
41#endif // VC++
42
43#include <ctype.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#if !defined(__WATCOMC__)
48 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
49 #include <errno.h>
50 #endif
51#endif
52
53#if defined(__WXMAC__)
54 #include "wx/mac/private.h" // includes mac headers
55#endif
56
57#include <time.h>
58
59#ifndef __MWERKS__
60 #include <sys/types.h>
61 #include <sys/stat.h>
62#else
63#ifdef __MACH__
64#include <sys/types.h>
65#include <utime.h>
66#include <sys/stat.h>
67#include <unistd.h>
68#else
69 #include <stat.h>
70 #include <unistd.h>
71 #include <unix.h>
72 #include <fcntl.h>
73#endif
74#endif
75
76#ifdef __UNIX__
77 #include <unistd.h>
78 #include <dirent.h>
79 #include <fcntl.h>
80#endif
81
82#ifdef __WXPM__
83 #include <process.h>
84 #include "wx/os2/private.h"
85#endif
86#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
87#if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
88 #include <direct.h>
89 #include <dos.h>
90 #include <io.h>
91#endif // __WINDOWS__
92#endif // native Win compiler
93
94#if defined(__DOS__)
95 #ifdef __WATCOMC__
96 #include <direct.h>
97 #include <dos.h>
98 #include <io.h>
99 #endif
100 #ifdef __DJGPP__
101 #include <unistd.h>
102 #endif
103#endif
104
105#ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
106 // this (3.1 I believe) and how to test for it.
107 // If this works for Borland 4.0 as well, then no worries.
108 #include <dir.h>
109#endif
110
111#ifdef __SALFORDC__
112 #include <dir.h>
113 #include <unix.h>
114#endif
115
116#include "wx/log.h"
117
118// No, Cygwin doesn't appear to have fnmatch.h after all.
119#if defined(HAVE_FNMATCH_H)
120 #include "fnmatch.h"
121#endif
122
123#ifdef __WINDOWS__
124 #include <windows.h>
125 #include "wx/msw/mslu.h"
126
127 // for _getcwd
128 #ifdef __MINGW32__
129 #include <io.h>
130 #endif
131
132 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
133 //
134 // note that it must be included after <windows.h>
135 #ifdef __GNUWIN32__
136 #ifdef __CYGWIN__
137 #include <sys/cygwin.h>
138 #endif
139 #endif // __GNUWIN32__
140#endif // __WINDOWS__
141
142// TODO: Borland probably has _wgetcwd as well?
143#ifdef _MSC_VER
144 #define HAVE_WGETCWD
145#endif
146
147// ----------------------------------------------------------------------------
148// constants
149// ----------------------------------------------------------------------------
150
151#ifndef _MAXPATHLEN
152 #define _MAXPATHLEN 1024
153#endif
154
155#ifdef __WXMAC__
156# ifdef __DARWIN__
157# include "MoreFilesX.h"
158# else
159# include "MoreFiles.h"
160# include "MoreFilesExtras.h"
161# include "FullPath.h"
162# include "FSpCompat.h"
163# endif
164#endif
165
166// ----------------------------------------------------------------------------
167// private globals
168// ----------------------------------------------------------------------------
169
170// MT-FIXME: get rid of this horror and all code using it
171static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
172
173#if defined(__VISAGECPP__) && __IBMCPP__ >= 400
174//
175// VisualAge C++ V4.0 cannot have any external linkage const decs
176// in headers included by more than one primary source
177//
178const off_t wxInvalidOffset = (off_t)-1;
179#endif
180
181// ----------------------------------------------------------------------------
182// macros
183// ----------------------------------------------------------------------------
184
185// we need to translate Mac filenames before passing them to OS functions
186#define OS_FILENAME(s) (s.fn_str())
187
188// ============================================================================
189// implementation
190// ============================================================================
191
192#ifdef wxNEED_WX_UNISTD_H
193
194WXDLLEXPORT int wxStat( const wxChar *file_name, wxStructStat *buf )
195{
196 return stat( wxConvFile.cWX2MB( file_name ), buf );
197}
198
199WXDLLEXPORT int wxAccess( const wxChar *pathname, int mode )
200{
201 return access( wxConvFile.cWX2MB( pathname ), mode );
202}
203
204WXDLLEXPORT int wxOpen( const wxChar *pathname, int flags, mode_t mode )
205{
206 return open( wxConvFile.cWX2MB( pathname ), flags, mode );
207}
208
209#endif
210 // wxNEED_WX_UNISTD_H
211
212// ----------------------------------------------------------------------------
213// wxPathList
214// ----------------------------------------------------------------------------
215
216IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
217
218void wxPathList::Add (const wxString& path)
219{
220 wxStringList::Add (WXSTRINGCAST path);
221}
222
223// Add paths e.g. from the PATH environment variable
224void wxPathList::AddEnvList (const wxString& envVariable)
225{
226 static const wxChar PATH_TOKS[] =
227#ifdef __WINDOWS__
228 /*
229 The space has been removed from the tokenizers, otherwise a
230 path such as "C:\Program Files" would be split into 2 paths:
231 "C:\Program" and "Files"
232 */
233// wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
234 wxT(";"); // Don't seperate with colon in DOS (used for drive)
235#else
236 wxT(" :;");
237#endif
238
239 wxChar *val = wxGetenv (WXSTRINGCAST envVariable);
240 if (val && *val)
241 {
242 wxChar *s = copystring (val);
243 wxChar *save_ptr, *token = wxStrtok (s, PATH_TOKS, &save_ptr);
244
245 if (token)
246 {
247 Add(token);
248 while (token)
249 {
250 if ( (token = wxStrtok ((wxChar *) NULL, PATH_TOKS, &save_ptr))
251 != NULL )
252 {
253 Add(token);
254 }
255 }
256 }
257
258 // suppress warning about unused variable save_ptr when wxStrtok() is a
259 // macro which throws away its third argument
260 save_ptr = token;
261
262 delete [] s;
263 }
264}
265
266// Given a full filename (with path), ensure that that file can
267// be accessed again USING FILENAME ONLY by adding the path
268// to the list if not already there.
269void wxPathList::EnsureFileAccessible (const wxString& path)
270{
271 wxString path_only(wxPathOnly(path));
272 if ( !path_only.IsEmpty() )
273 {
274 if ( !Member(path_only) )
275 Add(path_only);
276 }
277}
278
279bool wxPathList::Member (const wxString& path)
280{
281 for (wxStringList::Node *node = GetFirst(); node; node = node->GetNext())
282 {
283 wxString path2( node->GetData() );
284 if (
285#if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
286 // Case INDEPENDENT
287 path.CompareTo (path2, wxString::ignoreCase) == 0
288#else
289 // Case sensitive File System
290 path.CompareTo (path2) == 0
291#endif
292 )
293 return TRUE;
294 }
295 return FALSE;
296}
297
298wxString wxPathList::FindValidPath (const wxString& file)
299{
300 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer, file)))
301 return wxString(wxFileFunctionsBuffer);
302
303 wxChar buf[_MAXPATHLEN];
304 wxStrcpy(buf, wxFileFunctionsBuffer);
305
306 wxChar *filename = (wxChar*) NULL; /* shut up buggy egcs warning */
307 filename = wxIsAbsolutePath (buf) ? wxFileNameFromPath (buf) : (wxChar *)buf;
308
309 for (wxStringList::Node *node = GetFirst(); node; node = node->GetNext())
310 {
311 wxChar *path = node->GetData();
312 wxStrcpy (wxFileFunctionsBuffer, path);
313 wxChar ch = wxFileFunctionsBuffer[wxStrlen(wxFileFunctionsBuffer)-1];
314 if (ch != wxT('\\') && ch != wxT('/'))
315 wxStrcat (wxFileFunctionsBuffer, wxT("/"));
316 wxStrcat (wxFileFunctionsBuffer, filename);
317#ifdef __WINDOWS__
318 wxUnix2DosFilename (wxFileFunctionsBuffer);
319#endif
320 if (wxFileExists (wxFileFunctionsBuffer))
321 {
322 return wxString(wxFileFunctionsBuffer); // Found!
323 }
324 } // for()
325
326 return wxEmptyString; // Not found
327}
328
329wxString wxPathList::FindAbsoluteValidPath (const wxString& file)
330{
331 wxString f = FindValidPath(file);
332 if ( wxIsAbsolutePath(f) )
333 return f;
334
335 wxString buf;
336 wxGetWorkingDirectory(wxStringBuffer(buf, _MAXPATHLEN), _MAXPATHLEN);
337
338 if ( !wxEndsWithPathSeparator(buf) )
339 {
340 buf += wxFILE_SEP_PATH;
341 }
342 buf += f;
343
344 return buf;
345}
346
347bool
348wxFileExists (const wxString& filename)
349{
350 // we must use GetFileAttributes() instead of the ANSI C functions because
351 // it can cope with network (UNC) paths unlike them
352#if defined(__WIN32__) && !defined(__WXMICROWIN__)
353 DWORD ret = ::GetFileAttributes(filename);
354
355 return (ret != (DWORD)-1) && !(ret & FILE_ATTRIBUTE_DIRECTORY);
356#else // !__WIN32__
357 wxStructStat st;
358 return wxStat(filename, &st) == 0 && (st.st_mode & S_IFREG);
359#endif // __WIN32__/!__WIN32__
360}
361
362bool
363wxIsAbsolutePath (const wxString& filename)
364{
365 if (filename != wxT(""))
366 {
367#if defined(__WXMAC__) && !defined(__DARWIN__)
368 // Classic or Carbon CodeWarrior like
369 // Carbon with Apple DevTools is Unix like
370
371 // This seems wrong to me, but there is no fix. since
372 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
373 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
374 if (filename.Find(':') != wxNOT_FOUND && filename[0] != ':')
375 return TRUE ;
376#else
377 // Unix like or Windows
378 if (filename[0] == wxT('/'))
379 return TRUE;
380#endif
381#ifdef __VMS__
382 if ((filename[0] == wxT('[') && filename[1] != wxT('.')))
383 return TRUE;
384#endif
385#ifdef __WINDOWS__
386 // MSDOS like
387 if (filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':')))
388 return TRUE;
389#endif
390 }
391 return FALSE ;
392}
393
394/*
395 * Strip off any extension (dot something) from end of file,
396 * IF one exists. Inserts zero into buffer.
397 *
398 */
399
400void wxStripExtension(wxChar *buffer)
401{
402 int len = wxStrlen(buffer);
403 int i = len-1;
404 while (i > 0)
405 {
406 if (buffer[i] == wxT('.'))
407 {
408 buffer[i] = 0;
409 break;
410 }
411 i --;
412 }
413}
414
415void wxStripExtension(wxString& buffer)
416{
417 size_t len = buffer.Length();
418 size_t i = len-1;
419 while (i > 0)
420 {
421 if (buffer.GetChar(i) == wxT('.'))
422 {
423 buffer = buffer.Left(i);
424 break;
425 }
426 i --;
427 }
428}
429
430// Destructive removal of /./ and /../ stuff
431wxChar *wxRealPath (wxChar *path)
432{
433#ifdef __WXMSW__
434 static const wxChar SEP = wxT('\\');
435 wxUnix2DosFilename(path);
436#else
437 static const wxChar SEP = wxT('/');
438#endif
439 if (path[0] && path[1]) {
440 /* MATTHEW: special case "/./x" */
441 wxChar *p;
442 if (path[2] == SEP && path[1] == wxT('.'))
443 p = &path[0];
444 else
445 p = &path[2];
446 for (; *p; p++)
447 {
448 if (*p == SEP)
449 {
450 if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
451 {
452 wxChar *q;
453 for (q = p - 1; q >= path && *q != SEP; q--)
454 {
455 // Empty
456 }
457
458 if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
459 && (q - 1 <= path || q[-1] != SEP))
460 {
461 wxStrcpy (q, p + 3);
462 if (path[0] == wxT('\0'))
463 {
464 path[0] = SEP;
465 path[1] = wxT('\0');
466 }
467#ifdef __WXMSW__
468 /* Check that path[2] is NULL! */
469 else if (path[1] == wxT(':') && !path[2])
470 {
471 path[2] = SEP;
472 path[3] = wxT('\0');
473 }
474#endif
475 p = q - 1;
476 }
477 }
478 else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
479 wxStrcpy (p, p + 2);
480 }
481 }
482 }
483 return path;
484}
485
486// Must be destroyed
487wxChar *wxCopyAbsolutePath(const wxString& filename)
488{
489 if (filename == wxT(""))
490 return (wxChar *) NULL;
491
492 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename))) {
493 wxChar buf[_MAXPATHLEN];
494 buf[0] = wxT('\0');
495 wxGetWorkingDirectory(buf, WXSIZEOF(buf));
496 wxChar ch = buf[wxStrlen(buf) - 1];
497#ifdef __WXMSW__
498 if (ch != wxT('\\') && ch != wxT('/'))
499 wxStrcat(buf, wxT("\\"));
500#else
501 if (ch != wxT('/'))
502 wxStrcat(buf, wxT("/"));
503#endif
504 wxStrcat(buf, wxFileFunctionsBuffer);
505 return copystring( wxRealPath(buf) );
506 }
507 return copystring( wxFileFunctionsBuffer );
508}
509
510/*-
511 Handles:
512 ~/ => home dir
513 ~user/ => user's home dir
514 If the environment variable a = "foo" and b = "bar" then:
515 Unix:
516 $a => foo
517 $a$b => foobar
518 $a.c => foo.c
519 xxx$a => xxxfoo
520 ${a}! => foo!
521 $(b)! => bar!
522 \$a => \$a
523 MSDOS:
524 $a ==> $a
525 $(a) ==> foo
526 $(a)$b ==> foo$b
527 $(a)$(b)==> foobar
528 test.$$ ==> test.$$
529 */
530
531/* input name in name, pathname output to buf. */
532
533wxChar *wxExpandPath(wxChar *buf, const wxChar *name)
534{
535 register wxChar *d, *s, *nm;
536 wxChar lnm[_MAXPATHLEN];
537 int q;
538
539 // Some compilers don't like this line.
540// const wxChar trimchars[] = wxT("\n \t");
541
542 wxChar trimchars[4];
543 trimchars[0] = wxT('\n');
544 trimchars[1] = wxT(' ');
545 trimchars[2] = wxT('\t');
546 trimchars[3] = 0;
547
548#ifdef __WXMSW__
549 const wxChar SEP = wxT('\\');
550#else
551 const wxChar SEP = wxT('/');
552#endif
553 buf[0] = wxT('\0');
554 if (name == NULL || *name == wxT('\0'))
555 return buf;
556 nm = copystring(name); // Make a scratch copy
557 wxChar *nm_tmp = nm;
558
559 /* Skip leading whitespace and cr */
560 while (wxStrchr((wxChar *)trimchars, *nm) != NULL)
561 nm++;
562 /* And strip off trailing whitespace and cr */
563 s = nm + (q = wxStrlen(nm)) - 1;
564 while (q-- && wxStrchr((wxChar *)trimchars, *s) != NULL)
565 *s = wxT('\0');
566
567 s = nm;
568 d = lnm;
569#ifdef __WXMSW__
570 q = FALSE;
571#else
572 q = nm[0] == wxT('\\') && nm[1] == wxT('~');
573#endif
574
575 /* Expand inline environment variables */
576#ifdef __VISAGECPP__
577 while (*d)
578 {
579 *d++ = *s;
580 if(*s == wxT('\\'))
581 {
582 *(d - 1) = *++s;
583 if (*d)
584 {
585 s++;
586 continue;
587 }
588 else
589 break;
590 }
591 else
592#else
593 while ((*d++ = *s) != 0) {
594# ifndef __WXMSW__
595 if (*s == wxT('\\')) {
596 if ((*(d - 1) = *++s)) {
597 s++;
598 continue;
599 } else
600 break;
601 } else
602# endif
603#endif
604#ifdef __WXMSW__
605 if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
606#else
607 if (*s++ == wxT('$'))
608#endif
609 {
610 register wxChar *start = d;
611 register int braces = (*s == wxT('{') || *s == wxT('('));
612 register wxChar *value;
613 while ((*d++ = *s) != 0)
614 if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
615 break;
616 else
617 s++;
618 *--d = 0;
619 value = wxGetenv(braces ? start + 1 : start);
620 if (value) {
621 for ((d = start - 1); (*d++ = *value++) != 0;)
622 {
623 // Empty
624 }
625
626 d--;
627 if (braces && *s)
628 s++;
629 }
630 }
631 }
632
633 /* Expand ~ and ~user */
634 nm = lnm;
635 if (nm[0] == wxT('~') && !q)
636 {
637 /* prefix ~ */
638 if (nm[1] == SEP || nm[1] == 0)
639 { /* ~/filename */
640 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
641 if ((s = WXSTRINGCAST wxGetUserHome(wxT(""))) != NULL) {
642 if (*++nm)
643 nm++;
644 }
645 } else
646 { /* ~user/filename */
647 register wxChar *nnm;
648 register wxChar *home;
649 for (s = nm; *s && *s != SEP; s++)
650 {
651 // Empty
652 }
653 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
654 was_sep = (*s == SEP);
655 nnm = *s ? s + 1 : s;
656 *s = 0;
657 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
658 if ((home = WXSTRINGCAST wxGetUserHome(wxString(nm + 1))) == NULL) {
659 if (was_sep) /* replace only if it was there: */
660 *s = SEP;
661 s = NULL;
662 } else {
663 nm = nnm;
664 s = home;
665 }
666 }
667 }
668
669 d = buf;
670 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
671 /* Copy home dir */
672 while (wxT('\0') != (*d++ = *s++))
673 /* loop */;
674 // Handle root home
675 if (d - 1 > buf && *(d - 2) != SEP)
676 *(d - 1) = SEP;
677 }
678 s = nm;
679 while ((*d++ = *s++) != 0)
680 {
681 // Empty
682 }
683 delete[] nm_tmp; // clean up alloc
684 /* Now clean up the buffer */
685 return wxRealPath(buf);
686}
687
688/* Contract Paths to be build upon an environment variable
689 component:
690
691 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
692
693 The call wxExpandPath can convert these back!
694 */
695wxChar *
696wxContractPath (const wxString& filename, const wxString& envname, const wxString& user)
697{
698 static wxChar dest[_MAXPATHLEN];
699
700 if (filename == wxT(""))
701 return (wxChar *) NULL;
702
703 wxStrcpy (dest, WXSTRINGCAST filename);
704#ifdef __WXMSW__
705 wxUnix2DosFilename(dest);
706#endif
707
708 // Handle environment
709 const wxChar *val = (const wxChar *) NULL;
710 wxChar *tcp = (wxChar *) NULL;
711 if (envname != WXSTRINGCAST NULL && (val = wxGetenv (WXSTRINGCAST envname)) != NULL &&
712 (tcp = wxStrstr (dest, val)) != NULL)
713 {
714 wxStrcpy (wxFileFunctionsBuffer, tcp + wxStrlen (val));
715 *tcp++ = wxT('$');
716 *tcp++ = wxT('{');
717 wxStrcpy (tcp, WXSTRINGCAST envname);
718 wxStrcat (tcp, wxT("}"));
719 wxStrcat (tcp, wxFileFunctionsBuffer);
720 }
721
722 // Handle User's home (ignore root homes!)
723 size_t len = 0;
724 if ((val = wxGetUserHome (user)) != NULL &&
725 (len = wxStrlen(val)) > 2 &&
726 wxStrncmp(dest, val, len) == 0)
727 {
728 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
729 if (user != wxT(""))
730 wxStrcat(wxFileFunctionsBuffer, (const wxChar*) user);
731 wxStrcat(wxFileFunctionsBuffer, dest + len);
732 wxStrcpy (dest, wxFileFunctionsBuffer);
733 }
734
735 return dest;
736}
737
738// Return just the filename, not the path (basename)
739wxChar *wxFileNameFromPath (wxChar *path)
740{
741 wxString p = path;
742 wxString n = wxFileNameFromPath(p);
743
744 return path + p.length() - n.length();
745}
746
747wxString wxFileNameFromPath (const wxString& path)
748{
749 wxString name, ext;
750 wxFileName::SplitPath(path, NULL, &name, &ext);
751
752 wxString fullname = name;
753 if ( !ext.empty() )
754 {
755 fullname << wxFILE_SEP_EXT << ext;
756 }
757
758 return fullname;
759}
760
761// Return just the directory, or NULL if no directory
762wxChar *
763wxPathOnly (wxChar *path)
764{
765 if (path && *path)
766 {
767 static wxChar buf[_MAXPATHLEN];
768
769 // Local copy
770 wxStrcpy (buf, path);
771
772 int l = wxStrlen(path);
773 int i = l - 1;
774
775 // Search backward for a backward or forward slash
776 while (i > -1)
777 {
778#if defined(__WXMAC__) && !defined(__DARWIN__)
779 // Classic or Carbon CodeWarrior like
780 // Carbon with Apple DevTools is Unix like
781 if (path[i] == wxT(':') )
782 {
783 buf[i] = 0;
784 return buf;
785 }
786#else
787 // Unix like or Windows
788 if (path[i] == wxT('/') || path[i] == wxT('\\'))
789 {
790 buf[i] = 0;
791 return buf;
792 }
793#endif
794#ifdef __VMS__
795 if (path[i] == wxT(']'))
796 {
797 buf[i+1] = 0;
798 return buf;
799 }
800#endif
801 i --;
802 }
803
804#if defined(__WXMSW__) || defined(__WXPM__)
805 // Try Drive specifier
806 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
807 {
808 // A:junk --> A:. (since A:.\junk Not A:\junk)
809 buf[2] = wxT('.');
810 buf[3] = wxT('\0');
811 return buf;
812 }
813#endif
814 }
815 return (wxChar *) NULL;
816}
817
818// Return just the directory, or NULL if no directory
819wxString wxPathOnly (const wxString& path)
820{
821 if (path != wxT(""))
822 {
823 wxChar buf[_MAXPATHLEN];
824
825 // Local copy
826 wxStrcpy (buf, WXSTRINGCAST path);
827
828 int l = path.Length();
829 int i = l - 1;
830
831 // Search backward for a backward or forward slash
832 while (i > -1)
833 {
834#if defined(__WXMAC__) && !defined(__DARWIN__)
835 // Classic or Carbon CodeWarrior like
836 // Carbon with Apple DevTools is Unix like
837 if (path[i] == wxT(':') )
838 {
839 buf[i] = 0;
840 return wxString(buf);
841 }
842#else
843 // Unix like or Windows
844 if (path[i] == wxT('/') || path[i] == wxT('\\'))
845 {
846 buf[i] = 0;
847 return wxString(buf);
848 }
849#endif
850#ifdef __VMS__
851 if (path[i] == wxT(']'))
852 {
853 buf[i+1] = 0;
854 return wxString(buf);
855 }
856#endif
857 i --;
858 }
859
860#if defined(__WXMSW__) || defined(__WXPM__)
861 // Try Drive specifier
862 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
863 {
864 // A:junk --> A:. (since A:.\junk Not A:\junk)
865 buf[2] = wxT('.');
866 buf[3] = wxT('\0');
867 return wxString(buf);
868 }
869#endif
870 }
871 return wxString(wxT(""));
872}
873
874// Utility for converting delimiters in DOS filenames to UNIX style
875// and back again - or we get nasty problems with delimiters.
876// Also, convert to lower case, since case is significant in UNIX.
877
878#if defined(__WXMAC__)
879wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
880{
881#ifdef __DARWIN__
882 int i;
883 int j;
884 OSErr theErr;
885 OSStatus theStatus;
886 Boolean isDirectory = FALSE;
887 Str255 theParentPath = "\p";
888 FSSpec theParentSpec;
889 FSRef theParentRef;
890 char theFileName[FILENAME_MAX];
891 char thePath[FILENAME_MAX];
892
893 strcpy(thePath, "");
894
895 // GD: Separate file name from path and make a FSRef to the parent
896 // directory. This is necessary since FSRefs cannot reference files
897 // that have not yet been created.
898 // Based on example code from Apple Technical Note TN2022
899 // http://developer.apple.com/technotes/tn/tn2022.html
900
901 // check whether we are converting a directory
902 isDirectory = ((spec->name)[spec->name[0]] == ':');
903 // count length of file name
904 for (i = spec->name[0] - (isDirectory ? 1 : 0); ((spec->name[i] != ':') && (i > 0)); i--);
905 // copy file name
906 // prepend path separator since it will later be appended to the path
907 theFileName[0] = wxFILE_SEP_PATH;
908 for (j = i + 1; j <= spec->name[0] - (isDirectory ? 1 : 0); j++) {
909 theFileName[j - i] = spec->name[j];
910 }
911 theFileName[j - i] = '\0';
912 // copy path if any
913 for (j = 1; j <= i; j++) {
914 theParentPath[++theParentPath[0]] = spec->name[j];
915 }
916 theErr = FSMakeFSSpec(spec->vRefNum, spec->parID, theParentPath, &theParentSpec);
917 if (theErr == noErr) {
918 // convert the FSSpec to an FSRef
919 theErr = FSpMakeFSRef(&theParentSpec, &theParentRef);
920 }
921 if (theErr == noErr) {
922 // get the POSIX path associated with the FSRef
923 theStatus = FSRefMakePath(&theParentRef,
924 (UInt8 *)thePath, sizeof(thePath));
925 }
926 if (theStatus == noErr) {
927 // append file name to path
928 // includes previously prepended path separator
929 strcat(thePath, theFileName);
930 }
931
932 // create path string for return value
933 wxString result( thePath ) ;
934#else
935 Handle myPath ;
936 short length ;
937
938 // get length of path and allocate handle
939 FSpGetFullPath( spec , &length , &myPath ) ;
940 ::SetHandleSize( myPath , length + 1 ) ;
941 ::HLock( myPath ) ;
942 (*myPath)[length] = 0 ;
943 if ((length > 0) && ((*myPath)[length-1] == ':'))
944 (*myPath)[length-1] = 0 ;
945
946 // create path string for return value
947 wxString result = wxMacMakeStringFromCString( *myPath ) ;
948
949 // free allocated handle
950 ::HUnlock( myPath ) ;
951 ::DisposeHandle( myPath ) ;
952#endif
953
954 return result ;
955}
956#ifndef __DARWIN__
957// Mac file names are POSIX (Unix style) under Darwin
958// therefore the conversion functions below are not needed
959
960static wxChar sMacFileNameConversion[ 1000 ] ;
961static char scMacFileNameConversion[ 1000 ] ;
962
963#endif
964void wxMacFilename2FSSpec( const char *path , FSSpec *spec )
965{
966 OSStatus err = noErr ;
967#ifdef __DARWIN__
968 FSRef theRef;
969
970 // get the FSRef associated with the POSIX path
971 err = FSPathMakeRef((const UInt8 *) path, &theRef, NULL);
972 // convert the FSRef to an FSSpec
973 err = FSGetCatalogInfo(&theRef, kFSCatInfoNone, NULL, NULL, spec, NULL);
974#else
975 if ( strchr( path , ':' ) == NULL )
976 {
977 // try whether it is a volume / or a mounted volume
978 strncpy( scMacFileNameConversion , path , 1000 ) ;
979 scMacFileNameConversion[998] = 0 ;
980 strcat( scMacFileNameConversion , ":" ) ;
981 err = FSpLocationFromFullPath( strlen(scMacFileNameConversion) , scMacFileNameConversion , spec ) ;
982 }
983 else
984 {
985 err = FSpLocationFromFullPath( strlen(path) , path , spec ) ;
986 }
987#endif
988}
989
990#if wxUSE_UNICODE
991WXDLLEXPORT void wxMacFilename2FSSpec( const wxChar *path , FSSpec *spec )
992{
993 return wxMacFilename2FSSpec( wxMacStringToCString( wxString( path ) ) , spec ) ;
994}
995#endif
996
997#ifndef __DARWIN__
998
999wxString wxMac2UnixFilename (const wxChar *str)
1000{
1001 wxChar *s = sMacFileNameConversion ;
1002 wxStrcpy( s , str ) ;
1003 if (s)
1004 {
1005 memmove( s+1 , s ,wxStrlen( s ) + 1 * sizeof(wxChar)) ;
1006 if ( *s == ':' )
1007 *s = '.' ;
1008 else
1009 *s = '/' ;
1010
1011 while (*s)
1012 {
1013 if (*s == ':')
1014 *s = '/';
1015 else
1016 *s = wxTolower(*s); // Case INDEPENDENT
1017 s++;
1018 }
1019 }
1020 return wxString(sMacFileNameConversion) ;
1021}
1022
1023wxString wxUnix2MacFilename (const wxChar *str)
1024{
1025 wxChar *s = sMacFileNameConversion ;
1026 wxStrcpy( s , str ) ;
1027 if (s)
1028 {
1029 if ( *s == '.' )
1030 {
1031 // relative path , since it goes on with slash which is translated to a :
1032 memmove( s , s+1 ,wxStrlen( s ) * sizeof(wxChar)) ;
1033 }
1034 else if ( *s == '/' )
1035 {
1036 // absolute path -> on mac just start with the drive name
1037 memmove( s , s+1 ,wxStrlen( s ) * sizeof(wxChar) ) ;
1038 }
1039 else
1040 {
1041 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1042 }
1043 while (*s)
1044 {
1045 if (*s == '/' || *s == '\\')
1046 {
1047 // convert any back-directory situations
1048 if ( *(s+1) == '.' && *(s+2) == '.' && ( (*(s+3) == '/' || *(s+3) == '\\') ) )
1049 {
1050 *s = ':';
1051 memmove( s+1 , s+3 ,(wxStrlen( s+3 ) + 1)*sizeof(wxChar) ) ;
1052 }
1053 else
1054 *s = ':';
1055 }
1056 s++ ;
1057 }
1058 }
1059 return wxString(sMacFileNameConversion) ;
1060}
1061
1062wxString wxMacFSSpec2UnixFilename( const FSSpec *spec )
1063{
1064 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec) ) ;
1065}
1066
1067void wxUnixFilename2FSSpec( const char *path , FSSpec *spec )
1068{
1069 wxString var = wxUnix2MacFilename( path ) ;
1070 wxMacFilename2FSSpec( var , spec ) ;
1071}
1072#endif // ! __DARWIN__
1073
1074#endif // __WXMAC__
1075
1076void
1077wxDos2UnixFilename (char *s)
1078{
1079 if (s)
1080 while (*s)
1081 {
1082 if (*s == '\\')
1083 *s = '/';
1084#ifdef __WXMSW__
1085 else
1086 *s = wxTolower (*s); // Case INDEPENDENT
1087#endif
1088 s++;
1089 }
1090}
1091
1092void
1093#if defined(__WXMSW__) || defined(__WXPM__)
1094wxUnix2DosFilename (wxChar *s)
1095#else
1096wxUnix2DosFilename (wxChar *WXUNUSED(s) )
1097#endif
1098{
1099// Yes, I really mean this to happen under DOS only! JACS
1100#if defined(__WXMSW__) || defined(__WXPM__)
1101 if (s)
1102 while (*s)
1103 {
1104 if (*s == wxT('/'))
1105 *s = wxT('\\');
1106 s++;
1107 }
1108#endif
1109}
1110
1111// Concatenate two files to form third
1112bool
1113wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
1114{
1115 wxString outfile;
1116 if ( !wxGetTempFileName( wxT("cat"), outfile) )
1117 return FALSE;
1118
1119 FILE *fp1 = (FILE *) NULL;
1120 FILE *fp2 = (FILE *) NULL;
1121 FILE *fp3 = (FILE *) NULL;
1122 // Open the inputs and outputs
1123 if ((fp1 = wxFopen ( file1, wxT("rb"))) == NULL ||
1124 (fp2 = wxFopen ( file2, wxT("rb"))) == NULL ||
1125 (fp3 = wxFopen ( outfile, wxT("wb"))) == NULL)
1126 {
1127 if (fp1)
1128 fclose (fp1);
1129 if (fp2)
1130 fclose (fp2);
1131 if (fp3)
1132 fclose (fp3);
1133 return FALSE;
1134 }
1135
1136 int ch;
1137 while ((ch = getc (fp1)) != EOF)
1138 (void) putc (ch, fp3);
1139 fclose (fp1);
1140
1141 while ((ch = getc (fp2)) != EOF)
1142 (void) putc (ch, fp3);
1143 fclose (fp2);
1144
1145 fclose (fp3);
1146 bool result = wxRenameFile(outfile, file3);
1147 return result;
1148}
1149
1150// Copy files
1151bool
1152wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
1153{
1154#if defined(__WIN32__) && !defined(__WXMICROWIN__)
1155 // CopyFile() copies file attributes and modification time too, so use it
1156 // instead of our code if available
1157 //
1158 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1159 if ( !::CopyFile(file1, file2, !overwrite) )
1160 {
1161 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1162 file1.c_str(), file2.c_str());
1163
1164 return FALSE;
1165 }
1166#elif defined(__WXPM__)
1167 if ( ::DosCopy(file2, file2, overwrite ? DCPY_EXISTING : 0) != 0 )
1168 return FALSE;
1169#else // !Win32
1170
1171 wxStructStat fbuf;
1172 // get permissions of file1
1173 if ( wxStat( file1.c_str(), &fbuf) != 0 )
1174 {
1175 // the file probably doesn't exist or we haven't the rights to read
1176 // from it anyhow
1177 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1178 file1.c_str());
1179 return FALSE;
1180 }
1181
1182 // open file1 for reading
1183 wxFile fileIn(file1, wxFile::read);
1184 if ( !fileIn.IsOpened() )
1185 return FALSE;
1186
1187 // remove file2, if it exists. This is needed for creating
1188 // file2 with the correct permissions in the next step
1189 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
1190 {
1191 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1192 file2.c_str());
1193 return FALSE;
1194 }
1195
1196#ifdef __UNIX__
1197 // reset the umask as we want to create the file with exactly the same
1198 // permissions as the original one
1199 mode_t oldUmask = umask( 0 );
1200#endif // __UNIX__
1201
1202 // create file2 with the same permissions than file1 and open it for
1203 // writing
1204
1205 wxFile fileOut;
1206 if ( !fileOut.Create(file2, overwrite, fbuf.st_mode & 0777) )
1207 return FALSE;
1208
1209#ifdef __UNIX__
1210 /// restore the old umask
1211 umask(oldUmask);
1212#endif // __UNIX__
1213
1214 // copy contents of file1 to file2
1215 char buf[4096];
1216 size_t count;
1217 for ( ;; )
1218 {
1219 count = fileIn.Read(buf, WXSIZEOF(buf));
1220 if ( fileIn.Error() )
1221 return FALSE;
1222
1223 // end of file?
1224 if ( !count )
1225 break;
1226
1227 if ( fileOut.Write(buf, count) < count )
1228 return FALSE;
1229 }
1230
1231 // we can expect fileIn to be closed successfully, but we should ensure
1232 // that fileOut was closed as some write errors (disk full) might not be
1233 // detected before doing this
1234 if ( !fileIn.Close() || !fileOut.Close() )
1235 return FALSE;
1236
1237#if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1238 // no chmod in VA. Should be some permission API for HPFS386 partitions
1239 // however
1240 if ( chmod(OS_FILENAME(file2), fbuf.st_mode) != 0 )
1241 {
1242 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1243 file2.c_str());
1244 return FALSE;
1245 }
1246#endif // OS/2 || Mac
1247#endif // __WXMSW__ && __WIN32__
1248
1249 return TRUE;
1250}
1251
1252bool
1253wxRenameFile (const wxString& file1, const wxString& file2)
1254{
1255 // Normal system call
1256 if ( wxRename (file1, file2) == 0 )
1257 return TRUE;
1258
1259 // Try to copy
1260 if (wxCopyFile(file1, file2)) {
1261 wxRemoveFile(file1);
1262 return TRUE;
1263 }
1264 // Give up
1265 return FALSE;
1266}
1267
1268bool wxRemoveFile(const wxString& file)
1269{
1270#if defined(__VISUALC__) \
1271 || defined(__BORLANDC__) \
1272 || defined(__WATCOMC__) \
1273 || defined(__GNUWIN32__)
1274 int res = wxRemove(file);
1275#elif defined(__WXMAC__)
1276 int res = unlink(wxFNCONV(file));
1277#else
1278 int res = unlink(OS_FILENAME(file));
1279#endif
1280
1281 return res == 0;
1282}
1283
1284bool wxMkdir(const wxString& dir, int perm)
1285{
1286#if defined(__WXMAC__) && !defined(__UNIX__)
1287 return (mkdir( wxFNCONV(dir) , 0 ) == 0);
1288#else // !Mac
1289 const wxChar *dirname = dir.c_str();
1290
1291 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1292 // for the GNU compiler
1293#if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1294 #ifndef MSVCRT
1295 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1296 #else
1297 if ( mkdir(wxFNCONV(dirname)) != 0 )
1298 #endif
1299#elif defined(__WXPM__)
1300 if (::DosCreateDir((PSZ)dirname, NULL) != 0) // enhance for EAB's??
1301#elif defined(__DOS__)
1302 #if defined(__WATCOMC__)
1303 (void)perm;
1304 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1305 #elif defined(__DJGPP__)
1306 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1307 #else
1308 #error "Unsupported DOS compiler!"
1309 #endif
1310#else // !MSW, !DOS and !OS/2 VAC++
1311 (void)perm;
1312 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1313#endif // !MSW/MSW
1314 {
1315 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1316
1317 return FALSE;
1318 }
1319
1320 return TRUE;
1321#endif // Mac/!Mac
1322}
1323
1324bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1325{
1326#ifdef __VMS__
1327 return FALSE; //to be changed since rmdir exists in VMS7.x
1328#elif defined(__WXPM__)
1329 return (::DosDeleteDir((PSZ)dir.c_str()) == 0);
1330#else
1331
1332#ifdef __SALFORDC__
1333 return FALSE; // What to do?
1334#else
1335 return (wxRmDir(OS_FILENAME(dir)) == 0);
1336#endif
1337
1338#endif
1339}
1340
1341// does the path exists? (may have or not '/' or '\\' at the end)
1342bool wxPathExists(const wxChar *pszPathName)
1343{
1344 wxString strPath(pszPathName);
1345
1346#ifdef __WINDOWS__
1347 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1348 // so remove all trailing backslashes from the path - but don't do this for
1349 // the pathes "d:\" (which are different from "d:") nor for just "\"
1350 while ( wxEndsWithPathSeparator(strPath) )
1351 {
1352 size_t len = strPath.length();
1353 if ( len == 1 || (len == 3 && strPath[len - 2] == _T(':')) )
1354 break;
1355
1356 strPath.Truncate(len - 1);
1357 }
1358#endif // __WINDOWS__
1359
1360#if defined(__WIN32__) && !defined(__WXMICROWIN__)
1361 // stat() can't cope with network paths
1362 DWORD ret = ::GetFileAttributes(strPath);
1363
1364 return (ret != (DWORD)-1) && (ret & FILE_ATTRIBUTE_DIRECTORY);
1365#else // !__WIN32__
1366
1367 wxStructStat st;
1368#ifndef __VISAGECPP__
1369 return wxStat(pszPathName, &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR);
1370#else
1371 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1372 return wxStat(pszPathName, &st) == 0 && (st.st_mode == S_IFDIR);
1373#endif
1374
1375#endif // __WIN32__/!__WIN32__
1376}
1377
1378// Get a temporary filename, opening and closing the file.
1379wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1380{
1381 wxString filename = wxFileName::CreateTempFileName(prefix);
1382 if ( filename.empty() )
1383 return NULL;
1384
1385 if ( buf )
1386 wxStrcpy(buf, filename);
1387 else
1388 buf = copystring(filename);
1389
1390 return buf;
1391}
1392
1393bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1394{
1395 buf = wxFileName::CreateTempFileName(prefix);
1396
1397 return !buf.empty();
1398}
1399
1400// Get first file name matching given wild card.
1401
1402static wxDir *gs_dir = NULL;
1403static wxString gs_dirPath;
1404
1405wxString wxFindFirstFile(const wxChar *spec, int flags)
1406{
1407 wxSplitPath(spec, &gs_dirPath, NULL, NULL);
1408 if ( gs_dirPath.IsEmpty() )
1409 gs_dirPath = wxT(".");
1410 if ( !wxEndsWithPathSeparator(gs_dirPath ) )
1411 gs_dirPath << wxFILE_SEP_PATH;
1412
1413 if (gs_dir)
1414 delete gs_dir;
1415 gs_dir = new wxDir(gs_dirPath);
1416
1417 if ( !gs_dir->IsOpened() )
1418 {
1419 wxLogSysError(_("Can not enumerate files '%s'"), spec);
1420 return wxEmptyString;
1421 }
1422
1423 int dirFlags = 0;
1424 switch (flags)
1425 {
1426 case wxDIR: dirFlags = wxDIR_DIRS; break;
1427 case wxFILE: dirFlags = wxDIR_FILES; break;
1428 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1429 }
1430
1431 wxString result;
1432 gs_dir->GetFirst(&result, wxFileNameFromPath(wxString(spec)), dirFlags);
1433 if ( result.IsEmpty() )
1434 {
1435 wxDELETE(gs_dir);
1436 return result;
1437 }
1438
1439 return gs_dirPath + result;
1440}
1441
1442wxString wxFindNextFile()
1443{
1444 wxASSERT_MSG( gs_dir, wxT("You must call wxFindFirstFile before!") );
1445
1446 wxString result;
1447 gs_dir->GetNext(&result);
1448
1449 if ( result.IsEmpty() )
1450 {
1451 wxDELETE(gs_dir);
1452 return result;
1453 }
1454
1455 return gs_dirPath + result;
1456}
1457
1458
1459// Get current working directory.
1460// If buf is NULL, allocates space using new, else
1461// copies into buf.
1462wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1463{
1464 if ( !buf )
1465 {
1466 buf = new wxChar[sz + 1];
1467 }
1468
1469 bool ok = FALSE;
1470
1471 // for the compilers which have Unicode version of _getcwd(), call it
1472 // directly, for the others call the ANSI version and do the translation
1473#if !wxUSE_UNICODE
1474 #define cbuf buf
1475#else // wxUSE_UNICODE
1476 bool needsANSI = TRUE;
1477
1478 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1479 // This is not legal code as the compiler
1480 // is allowed destroy the wxCharBuffer.
1481 // wxCharBuffer c_buffer(sz);
1482 // char *cbuf = (char*)(const char*)c_buffer;
1483 char cbuf[_MAXPATHLEN];
1484 #endif
1485
1486 #ifdef HAVE_WGETCWD
1487 #if wxUSE_UNICODE_MSLU
1488 if ( wxGetOsVersion() != wxWIN95 )
1489 #else
1490 char *cbuf = NULL; // never really used because needsANSI will always be FALSE
1491 #endif
1492 {
1493 ok = _wgetcwd(buf, sz) != NULL;
1494 needsANSI = FALSE;
1495 }
1496 #endif
1497
1498 if ( needsANSI )
1499#endif // wxUSE_UNICODE
1500 {
1501 #if defined(_MSC_VER) || defined(__MINGW32__)
1502 ok = _getcwd(cbuf, sz) != NULL;
1503 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1504 FSSpec cwdSpec ;
1505 FCBPBRec pb;
1506 OSErr error;
1507 Str255 fileName ;
1508 pb.ioNamePtr = (StringPtr) &fileName;
1509 pb.ioVRefNum = 0;
1510 pb.ioRefNum = LMGetCurApRefNum();
1511 pb.ioFCBIndx = 0;
1512 error = PBGetFCBInfoSync(&pb);
1513 if ( error == noErr )
1514 {
1515 cwdSpec.vRefNum = pb.ioFCBVRefNum;
1516 cwdSpec.parID = pb.ioFCBParID;
1517 cwdSpec.name[0] = 0 ;
1518 wxString res = wxMacFSSpec2MacFilename( &cwdSpec ) ;
1519 wxStrcpy( buf , res ) ;
1520 ok = TRUE;
1521 }
1522 else
1523 {
1524 ok = FALSE;
1525 }
1526 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1527 APIRET rc;
1528 rc = ::DosQueryCurrentDir( 0 // current drive
1529 ,cbuf
1530 ,(PULONG)&sz
1531 );
1532 ok = rc != 0;
1533 #else // !Win32/VC++ !Mac !OS2
1534 ok = getcwd(cbuf, sz) != NULL;
1535 #endif // platform
1536
1537 #if wxUSE_UNICODE && !defined(__WXMAC__)
1538 // finally convert the result to Unicode if needed
1539 wxConvFile.MB2WC(buf, cbuf, sz);
1540 #endif // wxUSE_UNICODE
1541 }
1542
1543 if ( !ok )
1544 {
1545 wxLogSysError(_("Failed to get the working directory"));
1546
1547 // VZ: the old code used to return "." on error which didn't make any
1548 // sense at all to me - empty string is a better error indicator
1549 // (NULL might be even better but I'm afraid this could lead to
1550 // problems with the old code assuming the return is never NULL)
1551 buf[0] = _T('\0');
1552 }
1553 else // ok, but we might need to massage the path into the right format
1554 {
1555#ifdef __DJGPP__
1556 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1557 // with / deliminers. We don't like that.
1558 for (wxChar *ch = buf; *ch; ch++)
1559 {
1560 if (*ch == wxT('/'))
1561 *ch = wxT('\\');
1562 }
1563#endif // __DJGPP__
1564
1565// MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1566// he needs Unix as opposed to Win32 pathnames
1567#if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1568 // another example of DOS/Unix mix (Cygwin)
1569 wxString pathUnix = buf;
1570 cygwin_conv_to_full_win32_path(pathUnix, buf);
1571#endif // __CYGWIN__
1572 }
1573
1574 return buf;
1575
1576#if !wxUSE_UNICODE
1577 #undef cbuf
1578#endif
1579}
1580
1581wxString wxGetCwd()
1582{
1583 wxChar *buffer = new wxChar[_MAXPATHLEN];
1584 wxGetWorkingDirectory(buffer, _MAXPATHLEN);
1585 wxString str( buffer );
1586 delete [] buffer;
1587
1588 return str;
1589}
1590
1591bool wxSetWorkingDirectory(const wxString& d)
1592{
1593#if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1594 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1595#elif defined(__WXPM__)
1596 return (::DosSetCurrentDir((PSZ)d.c_str()) == 0);
1597#elif defined(__WINDOWS__)
1598
1599#ifdef __WIN32__
1600 return (bool)(SetCurrentDirectory(d) != 0);
1601#else
1602 // Must change drive, too.
1603 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1604 if (isDriveSpec)
1605 {
1606 wxChar firstChar = d[0];
1607
1608 // To upper case
1609 if (firstChar > 90)
1610 firstChar = firstChar - 32;
1611
1612 // To a drive number
1613 unsigned int driveNo = firstChar - 64;
1614 if (driveNo > 0)
1615 {
1616 unsigned int noDrives;
1617 _dos_setdrive(driveNo, &noDrives);
1618 }
1619 }
1620 bool success = (chdir(WXSTRINGCAST d) == 0);
1621
1622 return success;
1623#endif
1624
1625#endif
1626}
1627
1628// Get the OS directory if appropriate (such as the Windows directory).
1629// On non-Windows platform, probably just return the empty string.
1630wxString wxGetOSDirectory()
1631{
1632#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1633 wxChar buf[256];
1634 GetWindowsDirectory(buf, 256);
1635 return wxString(buf);
1636#else
1637 return wxEmptyString;
1638#endif
1639}
1640
1641bool wxEndsWithPathSeparator(const wxChar *pszFileName)
1642{
1643 size_t len = wxStrlen(pszFileName);
1644
1645 return len && wxIsPathSeparator(pszFileName[len - 1]);
1646}
1647
1648// find a file in a list of directories, returns FALSE if not found
1649bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
1650{
1651 // we assume that it's not empty
1652 wxCHECK_MSG( !wxIsEmpty(pszFile), FALSE,
1653 _T("empty file name in wxFindFileInPath"));
1654
1655 // skip path separator in the beginning of the file name if present
1656 if ( wxIsPathSeparator(*pszFile) )
1657 pszFile++;
1658
1659 // copy the path (strtok will modify it)
1660 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1661 wxStrcpy(szPath, pszPath);
1662
1663 wxString strFile;
1664 wxChar *pc, *save_ptr;
1665 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1666 pc != NULL;
1667 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1668 {
1669 // search for the file in this directory
1670 strFile = pc;
1671 if ( !wxEndsWithPathSeparator(pc) )
1672 strFile += wxFILE_SEP_PATH;
1673 strFile += pszFile;
1674
1675 if ( wxFileExists(strFile) ) {
1676 *pStr = strFile;
1677 break;
1678 }
1679 }
1680
1681 // suppress warning about unused variable save_ptr when wxStrtok() is a
1682 // macro which throws away its third argument
1683 save_ptr = pc;
1684
1685 delete [] szPath;
1686
1687 return pc != NULL; // if TRUE => we breaked from the loop
1688}
1689
1690void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
1691 wxString *pstrPath,
1692 wxString *pstrName,
1693 wxString *pstrExt)
1694{
1695 // it can be empty, but it shouldn't be NULL
1696 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
1697
1698 wxFileName::SplitPath(pszFileName, pstrPath, pstrName, pstrExt);
1699}
1700
1701time_t WXDLLEXPORT wxFileModificationTime(const wxString& filename)
1702{
1703 wxStructStat buf;
1704 wxStat( filename, &buf);
1705
1706 return buf.st_mtime;
1707}
1708
1709
1710//------------------------------------------------------------------------
1711// wild character routines
1712//------------------------------------------------------------------------
1713
1714bool wxIsWild( const wxString& pattern )
1715{
1716 wxString tmp = pattern;
1717 wxChar *pat = WXSTRINGCAST(tmp);
1718 while (*pat)
1719 {
1720 switch (*pat++)
1721 {
1722 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1723 return TRUE;
1724 case wxT('\\'):
1725 if (!*pat++)
1726 return FALSE;
1727 }
1728 }
1729 return FALSE;
1730}
1731
1732/*
1733* Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1734*
1735* The match procedure is public domain code (from ircII's reg.c)
1736*/
1737
1738bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1739{
1740 if (text.empty())
1741 {
1742 /* Match if both are empty. */
1743 return pat.empty();
1744 }
1745
1746 const wxChar *m = pat.c_str(),
1747 *n = text.c_str(),
1748 *ma = NULL,
1749 *na = NULL,
1750 *mp = NULL,
1751 *np = NULL;
1752 int just = 0,
1753 pcount = 0,
1754 acount = 0,
1755 count = 0;
1756
1757 if (dot_special && (*n == wxT('.')))
1758 {
1759 /* Never match so that hidden Unix files
1760 * are never found. */
1761 return FALSE;
1762 }
1763
1764 for (;;)
1765 {
1766 if (*m == wxT('*'))
1767 {
1768 ma = ++m;
1769 na = n;
1770 just = 1;
1771 mp = NULL;
1772 acount = count;
1773 }
1774 else if (*m == wxT('?'))
1775 {
1776 m++;
1777 if (!*n++)
1778 return FALSE;
1779 }
1780 else
1781 {
1782 if (*m == wxT('\\'))
1783 {
1784 m++;
1785 /* Quoting "nothing" is a bad thing */
1786 if (!*m)
1787 return FALSE;
1788 }
1789 if (!*m)
1790 {
1791 /*
1792 * If we are out of both strings or we just
1793 * saw a wildcard, then we can say we have a
1794 * match
1795 */
1796 if (!*n)
1797 return TRUE;
1798 if (just)
1799 return TRUE;
1800 just = 0;
1801 goto not_matched;
1802 }
1803 /*
1804 * We could check for *n == NULL at this point, but
1805 * since it's more common to have a character there,
1806 * check to see if they match first (m and n) and
1807 * then if they don't match, THEN we can check for
1808 * the NULL of n
1809 */
1810 just = 0;
1811 if (*m == *n)
1812 {
1813 m++;
1814 if (*n == wxT(' '))
1815 mp = NULL;
1816 count++;
1817 n++;
1818 }
1819 else
1820 {
1821
1822 not_matched:
1823
1824 /*
1825 * If there are no more characters in the
1826 * string, but we still need to find another
1827 * character (*m != NULL), then it will be
1828 * impossible to match it
1829 */
1830 if (!*n)
1831 return FALSE;
1832 if (mp)
1833 {
1834 m = mp;
1835 if (*np == wxT(' '))
1836 {
1837 mp = NULL;
1838 goto check_percent;
1839 }
1840 n = ++np;
1841 count = pcount;
1842 }
1843 else
1844 check_percent:
1845
1846 if (ma)
1847 {
1848 m = ma;
1849 n = ++na;
1850 count = acount;
1851 }
1852 else
1853 return FALSE;
1854 }
1855 }
1856 }
1857}
1858
1859
1860#ifdef __VISUALC__
1861 #pragma warning(default:4706) // assignment within conditional expression
1862#endif // VC++