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