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