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