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