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