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