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