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