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