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