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