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