]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
patch to fix various filename-related functions for cygwin
[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 #include <sys/cygwin.h>
123 #include <wchar.h>
124 #ifndef __TWIN32__
125 #include <sys/unistd.h>
126 #endif
127 #endif // __GNUWIN32__
128 #endif // __WINDOWS__
129
130 // TODO: Borland probably has _wgetcwd as well?
131 #ifdef _MSC_VER
132 #define HAVE_WGETCWD
133 #endif
134
135 // ----------------------------------------------------------------------------
136 // constants
137 // ----------------------------------------------------------------------------
138
139 #ifndef _MAXPATHLEN
140 #define _MAXPATHLEN 1024
141 #endif
142
143 extern wxChar *wxBuffer;
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(__WINDOWS__) && !defined(__WXMICROWIN__)
303 // GetFileAttributes can copy with network paths
304 DWORD ret = GetFileAttributes(filename);
305 DWORD isDir = (ret & FILE_ATTRIBUTE_DIRECTORY);
306 return ((ret != 0xffffffff) && (isDir == 0));
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 #ifdef __WINDOWS__
1264 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1265 // so remove all trailing backslashes from the path - but don't do this for
1266 // the pathes "d:\" (which are different from "d:") nor for just "\"
1267 while ( wxEndsWithPathSeparator(strPath) )
1268 {
1269 size_t len = strPath.length();
1270 if ( len == 1 || (len == 3 && strPath[len - 2] == _T(':')) )
1271 break;
1272
1273 strPath.Truncate(len - 1);
1274 }
1275 #endif // __WINDOWS__
1276
1277 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1278 // Stat can't cope with network paths
1279 DWORD ret = GetFileAttributes(strPath.c_str());
1280 DWORD isDir = (ret & FILE_ATTRIBUTE_DIRECTORY);
1281 return ((ret != 0xffffffff) && (isDir != 0));
1282 #else
1283
1284 wxStructStat st;
1285 #ifndef __VISAGECPP__
1286 return wxStat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 &&
1287 ((st.st_mode & S_IFMT) == S_IFDIR);
1288 #else
1289 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1290 return wxStat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 &&
1291 (st.st_mode == S_IFDIR);
1292 #endif
1293
1294 #endif
1295 }
1296
1297 // Get a temporary filename, opening and closing the file.
1298 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1299 {
1300 wxString filename = wxFileName::CreateTempFileName(prefix);
1301 if ( filename.empty() )
1302 return NULL;
1303
1304 if ( buf )
1305 wxStrcpy(buf, filename);
1306 else
1307 buf = copystring(filename);
1308
1309 return buf;
1310 }
1311
1312 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1313 {
1314 buf = wxFileName::CreateTempFileName(prefix);
1315
1316 return !buf.empty();
1317 }
1318
1319 // Get first file name matching given wild card.
1320
1321 static wxDir *gs_dir = NULL;
1322 static wxString gs_dirPath;
1323
1324 wxString wxFindFirstFile(const wxChar *spec, int flags)
1325 {
1326 gs_dirPath = wxPathOnly(spec);
1327 if ( gs_dirPath.IsEmpty() )
1328 gs_dirPath = wxT(".");
1329 if ( gs_dirPath.Last() != wxFILE_SEP_PATH )
1330 gs_dirPath << wxFILE_SEP_PATH;
1331
1332 if (gs_dir)
1333 delete gs_dir;
1334 gs_dir = new wxDir(gs_dirPath);
1335
1336 if ( !gs_dir->IsOpened() )
1337 {
1338 wxLogSysError(_("Can not enumerate files '%s'"), spec);
1339 return wxEmptyString;
1340 }
1341
1342 int dirFlags = 0;
1343 switch (flags)
1344 {
1345 case wxDIR: dirFlags = wxDIR_DIRS; break;
1346 case wxFILE: dirFlags = wxDIR_FILES; break;
1347 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1348 }
1349
1350 wxString result;
1351 gs_dir->GetFirst(&result, wxFileNameFromPath(spec), dirFlags);
1352 if ( result.IsEmpty() )
1353 {
1354 wxDELETE(gs_dir);
1355 return result;
1356 }
1357
1358 return gs_dirPath + result;
1359 }
1360
1361 wxString wxFindNextFile()
1362 {
1363 wxASSERT_MSG( gs_dir, wxT("You must call wxFindFirstFile before!") );
1364
1365 wxString result;
1366 gs_dir->GetNext(&result);
1367
1368 if ( result.IsEmpty() )
1369 {
1370 wxDELETE(gs_dir);
1371 return result;
1372 }
1373
1374 return gs_dirPath + result;
1375 }
1376
1377
1378 // Get current working directory.
1379 // If buf is NULL, allocates space using new, else
1380 // copies into buf.
1381 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1382 {
1383 if ( !buf )
1384 {
1385 buf = new wxChar[sz + 1];
1386 }
1387
1388 bool ok;
1389
1390 // for the compilers which have Unicode version of _getcwd(), call it
1391 // directly, for the others call the ANSI version and do the translation
1392 #if wxUSE_UNICODE
1393 #ifdef HAVE_WGETCWD
1394 ok = _wgetcwd(buf, sz) != NULL;
1395 #else // !HAVE_WGETCWD
1396 wxCharBuffer cbuf(sz);
1397 #endif
1398 #endif //
1399
1400 #if !wxUSE_UNICODE || !defined(HAVE_WGETCWD)
1401 #ifdef _MSC_VER
1402 ok = _getcwd(buf, sz) != NULL;
1403 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1404 FSSpec cwdSpec ;
1405 FCBPBRec pb;
1406 OSErr error;
1407 Str255 fileName ;
1408 pb.ioNamePtr = (StringPtr) &fileName;
1409 pb.ioVRefNum = 0;
1410 pb.ioRefNum = LMGetCurApRefNum();
1411 pb.ioFCBIndx = 0;
1412 error = PBGetFCBInfoSync(&pb);
1413 if ( error == noErr )
1414 {
1415 cwdSpec.vRefNum = pb.ioFCBVRefNum;
1416 cwdSpec.parID = pb.ioFCBParID;
1417 cwdSpec.name[0] = 0 ;
1418 wxString res = wxMacFSSpec2MacFilename( &cwdSpec ) ;
1419
1420 strcpy( buf , res ) ;
1421 buf[res.length()]=0 ;
1422
1423 ok = TRUE;
1424 }
1425 else
1426 {
1427 ok = FALSE;
1428 }
1429 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1430 APIRET rc;
1431 rc = ::DosQueryCurrentDir( 0 // current drive
1432 ,buf
1433 ,(PULONG)&sz
1434 );
1435 ok = rc != 0;
1436 #else // !Win32/VC++ !Mac !OS2
1437 ok = getcwd(buf, sz) != NULL;
1438 #endif // platform
1439 #endif // !wxUSE_UNICODE || !HAVE_WGETCWD
1440
1441 if ( !ok )
1442 {
1443 wxLogSysError(_("Failed to get the working directory"));
1444
1445 // VZ: the old code used to return "." on error which didn't make any
1446 // sense at all to me - empty string is a better error indicator
1447 // (NULL might be even better but I'm afraid this could lead to
1448 // problems with the old code assuming the return is never NULL)
1449 buf[0] = _T('\0');
1450 }
1451 else // ok, but we might need to massage the path into the right format
1452 {
1453 #ifdef __DJGPP__
1454 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1455 // with / deliminers. We don't like that.
1456 for (wxChar *ch = buf; *ch; ch++)
1457 {
1458 if (*ch == wxT('/'))
1459 *ch = wxT('\\');
1460 }
1461 #endif // __DJGPP__
1462
1463 #ifdef __GNUWIN32__
1464 // another example of DOS/Unix mix (Cygwin)
1465 wxString pathUnix = buf;
1466 cygwin_conv_to_full_win32_path(pathUnix, buf);
1467 #endif // __GNUWIN32__
1468
1469 // finally convert the result to Unicode if needed
1470 #if wxUSE_UNICODE && !defined(HAVE_WGETCWD)
1471 wxConvFile.MB2WC(buf, cbuf, sz);
1472 #endif // wxUSE_UNICODE
1473 }
1474
1475 return buf;
1476 }
1477
1478 wxString wxGetCwd()
1479 {
1480 wxString str;
1481
1482 // we can't create wxStringBuffer object inline: Sun CC generates buggy
1483 // code in this case!
1484 {
1485 wxStringBuffer buf(str, _MAXPATHLEN);
1486 wxGetWorkingDirectory(buf, _MAXPATHLEN);
1487 }
1488
1489 return str;
1490 }
1491
1492 bool wxSetWorkingDirectory(const wxString& d)
1493 {
1494 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1495 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1496 #elif defined(__WXPM__)
1497 return (::DosSetCurrentDir((PSZ)d.c_str()) == 0);
1498 #elif defined(__WINDOWS__)
1499
1500 #ifdef __WIN32__
1501 return (bool)(SetCurrentDirectory(d) != 0);
1502 #else
1503 // Must change drive, too.
1504 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1505 if (isDriveSpec)
1506 {
1507 wxChar firstChar = d[0];
1508
1509 // To upper case
1510 if (firstChar > 90)
1511 firstChar = firstChar - 32;
1512
1513 // To a drive number
1514 unsigned int driveNo = firstChar - 64;
1515 if (driveNo > 0)
1516 {
1517 unsigned int noDrives;
1518 _dos_setdrive(driveNo, &noDrives);
1519 }
1520 }
1521 bool success = (chdir(WXSTRINGCAST d) == 0);
1522
1523 return success;
1524 #endif
1525
1526 #endif
1527 }
1528
1529 // Get the OS directory if appropriate (such as the Windows directory).
1530 // On non-Windows platform, probably just return the empty string.
1531 wxString wxGetOSDirectory()
1532 {
1533 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1534 wxChar buf[256];
1535 GetWindowsDirectory(buf, 256);
1536 return wxString(buf);
1537 #else
1538 return wxEmptyString;
1539 #endif
1540 }
1541
1542 bool wxEndsWithPathSeparator(const wxChar *pszFileName)
1543 {
1544 size_t len = wxStrlen(pszFileName);
1545
1546 return len && wxIsPathSeparator(pszFileName[len - 1]);
1547 }
1548
1549 // find a file in a list of directories, returns false if not found
1550 bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
1551 {
1552 // we assume that it's not empty
1553 wxCHECK_MSG( !wxIsEmpty(pszFile), FALSE,
1554 _T("empty file name in wxFindFileInPath"));
1555
1556 // skip path separator in the beginning of the file name if present
1557 if ( wxIsPathSeparator(*pszFile) )
1558 pszFile++;
1559
1560 // copy the path (strtok will modify it)
1561 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1562 wxStrcpy(szPath, pszPath);
1563
1564 wxString strFile;
1565 wxChar *pc, *save_ptr;
1566 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1567 pc != NULL;
1568 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1569 {
1570 // search for the file in this directory
1571 strFile = pc;
1572 if ( !wxEndsWithPathSeparator(pc) )
1573 strFile += wxFILE_SEP_PATH;
1574 strFile += pszFile;
1575
1576 if ( FileExists(strFile) ) {
1577 *pStr = strFile;
1578 break;
1579 }
1580 }
1581
1582 // suppress warning about unused variable save_ptr when wxStrtok() is a
1583 // macro which throws away its third argument
1584 save_ptr = pc;
1585
1586 delete [] szPath;
1587
1588 return pc != NULL; // if true => we breaked from the loop
1589 }
1590
1591 void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
1592 wxString *pstrPath,
1593 wxString *pstrName,
1594 wxString *pstrExt)
1595 {
1596 // it can be empty, but it shouldn't be NULL
1597 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
1598
1599 wxFileName::SplitPath(pszFileName, pstrPath, pstrName, pstrExt);
1600 }
1601
1602 time_t WXDLLEXPORT wxFileModificationTime(const wxString& filename)
1603 {
1604 wxStructStat buf;
1605
1606 wxStat(filename.fn_str(), &buf);
1607 return buf.st_mtime;
1608 }
1609
1610
1611 //------------------------------------------------------------------------
1612 // wild character routines
1613 //------------------------------------------------------------------------
1614
1615 bool wxIsWild( const wxString& pattern )
1616 {
1617 wxString tmp = pattern;
1618 wxChar *pat = WXSTRINGCAST(tmp);
1619 while (*pat) {
1620 switch (*pat++) {
1621 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1622 return TRUE;
1623 case wxT('\\'):
1624 if (!*pat++)
1625 return FALSE;
1626 }
1627 }
1628 return FALSE;
1629 };
1630
1631 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1632
1633 #if defined(HAVE_FNMATCH_H)
1634 {
1635 // this probably won't work well for multibyte chars in Unicode mode?
1636 if(dot_special)
1637 return fnmatch(pat.fn_str(), text.fn_str(), FNM_PERIOD) == 0;
1638 else
1639 return fnmatch(pat.fn_str(), text.fn_str(), 0) == 0;
1640 }
1641 #else
1642
1643 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1644
1645 /*
1646 * WARNING: this code is broken!
1647 */
1648 {
1649 wxString tmp1 = pat;
1650 wxChar *pattern = WXSTRINGCAST(tmp1);
1651 wxString tmp2 = text;
1652 wxChar *str = WXSTRINGCAST(tmp2);
1653 wxChar c;
1654 wxChar *cp;
1655 bool done = FALSE, ret_code, ok;
1656 // Below is for vi fans
1657 const wxChar OB = wxT('{'), CB = wxT('}');
1658
1659 // dot_special means '.' only matches '.'
1660 if (dot_special && *str == wxT('.') && *pattern != *str)
1661 return FALSE;
1662
1663 while ((*pattern != wxT('\0')) && (!done)
1664 && (((*str==wxT('\0'))&&((*pattern==OB)||(*pattern==wxT('*'))))||(*str!=wxT('\0')))) {
1665 switch (*pattern) {
1666 case wxT('\\'):
1667 pattern++;
1668 if (*pattern != wxT('\0'))
1669 pattern++;
1670 break;
1671 case wxT('*'):
1672 pattern++;
1673 ret_code = FALSE;
1674 while ((*str!=wxT('\0'))
1675 && ((ret_code=wxMatchWild(pattern, str++, FALSE)) == 0))
1676 /*loop*/;
1677 if (ret_code) {
1678 while (*str != wxT('\0'))
1679 str++;
1680 while (*pattern != wxT('\0'))
1681 pattern++;
1682 }
1683 break;
1684 case wxT('['):
1685 pattern++;
1686 repeat:
1687 if ((*pattern == wxT('\0')) || (*pattern == wxT(']'))) {
1688 done = TRUE;
1689 break;
1690 }
1691 if (*pattern == wxT('\\')) {
1692 pattern++;
1693 if (*pattern == wxT('\0')) {
1694 done = TRUE;
1695 break;
1696 }
1697 }
1698 if (*(pattern + 1) == wxT('-')) {
1699 c = *pattern;
1700 pattern += 2;
1701 if (*pattern == wxT(']')) {
1702 done = TRUE;
1703 break;
1704 }
1705 if (*pattern == wxT('\\')) {
1706 pattern++;
1707 if (*pattern == wxT('\0')) {
1708 done = TRUE;
1709 break;
1710 }
1711 }
1712 if ((*str < c) || (*str > *pattern)) {
1713 pattern++;
1714 goto repeat;
1715 }
1716 } else if (*pattern != *str) {
1717 pattern++;
1718 goto repeat;
1719 }
1720 pattern++;
1721 while ((*pattern != wxT(']')) && (*pattern != wxT('\0'))) {
1722 if ((*pattern == wxT('\\')) && (*(pattern + 1) != wxT('\0')))
1723 pattern++;
1724 pattern++;
1725 }
1726 if (*pattern != wxT('\0')) {
1727 pattern++, str++;
1728 }
1729 break;
1730 case wxT('?'):
1731 pattern++;
1732 str++;
1733 break;
1734 case OB:
1735 pattern++;
1736 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
1737 cp = str;
1738 ok = TRUE;
1739 while (ok && (*cp != wxT('\0')) && (*pattern != wxT('\0'))
1740 && (*pattern != wxT(',')) && (*pattern != CB)) {
1741 if (*pattern == wxT('\\'))
1742 pattern++;
1743 ok = (*pattern++ == *cp++);
1744 }
1745 if (*pattern == wxT('\0')) {
1746 ok = FALSE;
1747 done = TRUE;
1748 break;
1749 } else if (ok) {
1750 str = cp;
1751 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
1752 if (*++pattern == wxT('\\')) {
1753 if (*++pattern == CB)
1754 pattern++;
1755 }
1756 }
1757 } else {
1758 while (*pattern!=CB && *pattern!=wxT(',') && *pattern!=wxT('\0')) {
1759 if (*++pattern == wxT('\\')) {
1760 if (*++pattern == CB || *pattern == wxT(','))
1761 pattern++;
1762 }
1763 }
1764 }
1765 if (*pattern != wxT('\0'))
1766 pattern++;
1767 }
1768 break;
1769 default:
1770 if (*str == *pattern) {
1771 str++, pattern++;
1772 } else {
1773 done = TRUE;
1774 }
1775 }
1776 }
1777 while (*pattern == wxT('*'))
1778 pattern++;
1779 return ((*str == wxT('\0')) && (*pattern == wxT('\0')));
1780 };
1781
1782 #endif
1783
1784 #ifdef __VISUALC__
1785 #pragma warning(default:4706) // assignment within conditional expression
1786 #endif // VC++
1787
1788 //------------------------------------------------------------------------
1789 // Missing functions in Unicode for Win9x
1790 //------------------------------------------------------------------------
1791
1792 // NB: MSLU only covers Win32 API, it doesn't provide Unicode implementation of
1793 // libc functions. Unfortunately, some of MSVCRT wchar_t functions
1794 // (e.g. _wopen) don't work on Windows 9x, so we have to workaround it
1795 // by calling the char version. We still want to use wchar_t version on
1796 // NT/2000/XP, though, because they allow for Unicode file names.
1797 #if wxUSE_UNICODE_MSLU
1798
1799 #if defined( __VISUALC__ ) \
1800 || ( defined(__MINGW32__) && wxCHECK_W32API_VERSION( 0, 5 ) ) \
1801 || ( defined(__MWERKS__) && defined(__WXMSW__) )
1802 WXDLLEXPORT int wxOpen(const wxChar *name, int flags, int mode)
1803 {
1804 if ( wxGetOsVersion() == wxWINDOWS_NT )
1805 return _wopen(name, flags, mode);
1806 else
1807 return _open(wxConvFile.cWX2MB(name), flags, mode);
1808 }
1809 #endif
1810
1811 #endif // wxUSE_UNICODE_MSLU