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