]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
Added dummy DeleteChildren so the sample will at least link.
[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 #ifdef __GNUG__
13 #pragma implementation "filefn.h"
14 #endif
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18 #include "wx/defs.h"
19
20 #ifdef __BORLANDC__
21 #pragma hdrstop
22 #endif
23
24 #ifndef WX_PRECOMP
25 #include "wx/defs.h"
26 #endif
27
28 #include "wx/utils.h"
29 #include <wx/intl.h>
30
31 // there are just too many of those...
32 #ifdef _MSC_VER
33 #pragma warning(disable:4706) // assignment within conditional expression
34 #endif // VC++
35
36 #include <ctype.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #if !defined(__WATCOMC__)
41 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
42 #include <errno.h>
43 #endif
44 #endif
45 #include <time.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48
49 #ifdef __UNIX__
50 #include <unistd.h>
51 #include <dirent.h>
52 #endif
53
54 #ifdef __WINDOWS__
55 #ifndef __GNUWIN32__
56 #include <direct.h>
57 #include <dos.h>
58 #endif
59 #endif
60
61 #ifdef __GNUWIN32__
62 #include <sys/unistd.h>
63 #define stricmp strcasecmp
64 #endif
65
66 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
67 // this (3.1 I believe) and how to test for it.
68 // If this works for Borland 4.0 as well, then no worries.
69 #include <dir.h>
70 #endif
71
72 #include "wx/setup.h"
73
74 #if defined(HAVE_FNMATCH_H) || defined(__GNUWIN32__)
75 #include "fnmatch.h"
76 #endif
77
78 #ifdef __WINDOWS__
79 #include "windows.h"
80 #endif
81
82 #define _MAXPATHLEN 500
83
84 extern char *wxBuffer;
85
86 #if !USE_SHARED_LIBRARIES
87 IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
88 #endif
89
90 void wxPathList::Add (const wxString& path)
91 {
92 wxStringList::Add ((char *)(const char *)path);
93 }
94
95 // Add paths e.g. from the PATH environment variable
96 void wxPathList::AddEnvList (const wxString& envVariable)
97 {
98 static const char PATH_TOKS[] =
99 #ifdef __WINDOWS__
100 " ;"; // Don't seperate with colon in DOS (used for drive)
101 #else
102 " :;";
103 #endif
104
105 char *val = getenv (WXSTRINGCAST envVariable);
106 if (val && *val)
107 {
108 char *s = copystring (val);
109 char *token = strtok (s, PATH_TOKS);
110
111 if (token)
112 {
113 Add (copystring (token));
114 while (token)
115 {
116 if ((token = strtok ((char *) NULL, PATH_TOKS)) != NULL)
117 Add (wxString(token));
118 }
119 }
120 delete[]s;
121 }
122 }
123
124 // Given a full filename (with path), ensure that that file can
125 // be accessed again USING FILENAME ONLY by adding the path
126 // to the list if not already there.
127 void wxPathList::EnsureFileAccessible (const wxString& path)
128 {
129 wxString path1(path);
130 char *path_only = wxPathOnly (WXSTRINGCAST path1);
131 if (path_only)
132 {
133 if (!Member (wxString(path_only)))
134 Add (wxString(path_only));
135 }
136 }
137
138 bool wxPathList::Member (const wxString& path)
139 {
140 for (wxNode * node = First (); node != NULL; node = node->Next ())
141 {
142 wxString path2((char *) node->Data ());
143 if (
144 #if defined(__WINDOWS__) || defined(__VMS__)
145 // Case INDEPENDENT
146 path.CompareTo (path2, wxString::ignoreCase) == 0
147 #else
148 // Case sensitive File System
149 path.CompareTo (path2) == 0
150 #endif
151 )
152 return TRUE;
153 }
154 return FALSE;
155 }
156
157 wxString wxPathList::FindValidPath (const wxString& file)
158 {
159 if (wxFileExists (wxExpandPath(wxBuffer, file)))
160 return wxString(wxBuffer);
161
162 char buf[_MAXPATHLEN];
163 strcpy(buf, wxBuffer);
164
165 char *filename = IsAbsolutePath (buf) ? wxFileNameFromPath (buf) : (char *)buf;
166
167 for (wxNode * node = First (); node; node = node->Next ())
168 {
169 char *path = (char *) node->Data ();
170 strcpy (wxBuffer, path);
171 char ch = wxBuffer[strlen(wxBuffer)-1];
172 if (ch != '\\' && ch != '/')
173 strcat (wxBuffer, "/");
174 strcat (wxBuffer, filename);
175 #ifdef __WINDOWS__
176 Unix2DosFilename (wxBuffer);
177 #endif
178 if (wxFileExists (wxBuffer))
179 {
180 return wxString(wxBuffer); // Found!
181 }
182 } // for()
183
184 return wxString(""); // Not found
185 }
186
187 wxString wxPathList::FindAbsoluteValidPath (const wxString& file)
188 {
189 wxString f = FindValidPath(file);
190 if (wxIsAbsolutePath(f))
191 return f;
192 else
193 {
194 char buf[500];
195 wxGetWorkingDirectory(buf, 499);
196 int len = (int)strlen(buf);
197 char lastCh = 0;
198 if (len > 0)
199 lastCh = buf[len-1];
200 if (lastCh != '/' && lastCh != '\\')
201 {
202 #ifdef __WINDOWS__
203 strcat(buf, "\\");
204 #else
205 strcat(buf, "/");
206 #endif
207 }
208 strcat(buf, (const char *)f);
209 strcpy(wxBuffer, buf);
210 return wxString(wxBuffer);
211 }
212 }
213
214 bool
215 wxFileExists (const wxString& filename)
216 {
217 #ifdef __GNUWIN32__ // (fix a B20 bug)
218 if (GetFileAttributes(filename) == 0xFFFFFFFF)
219 return FALSE;
220 else
221 return TRUE;
222 #else
223 struct stat stbuf;
224
225 if (filename && stat ((char *)(const char *)filename, &stbuf) == 0)
226 return TRUE;
227 return FALSE;
228 #endif
229 }
230
231 /* Vadim's alternative implementation
232
233 // does the file exist?
234 bool wxFileExists(const char *pszFileName)
235 {
236 struct stat st;
237 return !access(pszFileName, 0) &&
238 !stat(pszFileName, &st) &&
239 (st.st_mode & S_IFREG);
240 }
241 */
242
243 bool
244 wxIsAbsolutePath (const wxString& filename)
245 {
246 if (filename != "")
247 {
248 if (filename[0] == '/'
249 #ifdef __VMS__
250 || (filename[0] == '[' && filename[1] != '.')
251 #endif
252 #ifdef __WINDOWS__
253 /* MSDOS */
254 || filename[0] == '\\' || (isalpha (filename[0]) && filename[1] == ':')
255 #endif
256 )
257 return TRUE;
258 }
259 return FALSE;
260 }
261
262 /*
263 * Strip off any extension (dot something) from end of file,
264 * IF one exists. Inserts zero into buffer.
265 *
266 */
267
268 void wxStripExtension(char *buffer)
269 {
270 int len = strlen(buffer);
271 int i = len-1;
272 while (i > 0)
273 {
274 if (buffer[i] == '.')
275 {
276 buffer[i] = 0;
277 break;
278 }
279 i --;
280 }
281 }
282
283 void wxStripExtension(wxString& buffer)
284 {
285 size_t len = buffer.Length();
286 size_t i = len-1;
287 while (i > 0)
288 {
289 if (buffer.GetChar(i) == '.')
290 {
291 buffer = buffer.Left(i);
292 break;
293 }
294 i --;
295 }
296 }
297
298 // Destructive removal of /./ and /../ stuff
299 char *wxRealPath (char *path)
300 {
301 #ifdef __WXMSW__
302 static const char SEP = '\\';
303 Unix2DosFilename(path);
304 #else
305 static const char SEP = '/';
306 #endif
307 if (path[0] && path[1]) {
308 /* MATTHEW: special case "/./x" */
309 char *p;
310 if (path[2] == SEP && path[1] == '.')
311 p = &path[0];
312 else
313 p = &path[2];
314 for (; *p; p++)
315 {
316 if (*p == SEP)
317 {
318 if (p[1] == '.' && p[2] == '.' && (p[3] == SEP || p[3] == '\0'))
319 {
320 char *q;
321 for (q = p - 1; q >= path && *q != SEP; q--);
322 if (q[0] == SEP && (q[1] != '.' || q[2] != '.' || q[3] != SEP)
323 && (q - 1 <= path || q[-1] != SEP))
324 {
325 strcpy (q, p + 3);
326 if (path[0] == '\0')
327 {
328 path[0] = SEP;
329 path[1] = '\0';
330 }
331 #ifdef __WXMSW__
332 /* Check that path[2] is NULL! */
333 else if (path[1] == ':' && !path[2])
334 {
335 path[2] = SEP;
336 path[3] = '\0';
337 }
338 #endif
339 p = q - 1;
340 }
341 }
342 else if (p[1] == '.' && (p[2] == SEP || p[2] == '\0'))
343 strcpy (p, p + 2);
344 }
345 }
346 }
347 return path;
348 }
349
350 // Must be destroyed
351 char *wxCopyAbsolutePath(const wxString& filename)
352 {
353 if (filename == "")
354 return (char *) NULL;
355
356 if (! IsAbsolutePath(wxExpandPath(wxBuffer, filename))) {
357 char buf[_MAXPATHLEN];
358 buf[0] = '\0';
359 wxGetWorkingDirectory(buf, sizeof(buf)/sizeof(char));
360 char ch = buf[strlen(buf) - 1];
361 #ifdef __WXMSW__
362 if (ch != '\\' && ch != '/')
363 strcat(buf, "\\");
364 #else
365 if (ch != '/')
366 strcat(buf, "/");
367 #endif
368 strcat(buf, wxBuffer);
369 return copystring( wxRealPath(buf) );
370 }
371 return copystring( wxBuffer );
372 }
373
374 /*-
375 Handles:
376 ~/ => home dir
377 ~user/ => user's home dir
378 If the environment variable a = "foo" and b = "bar" then:
379 Unix:
380 $a => foo
381 $a$b => foobar
382 $a.c => foo.c
383 xxx$a => xxxfoo
384 ${a}! => foo!
385 $(b)! => bar!
386 \$a => \$a
387 MSDOS:
388 $a ==> $a
389 $(a) ==> foo
390 $(a)$b ==> foo$b
391 $(a)$(b)==> foobar
392 test.$$ ==> test.$$
393 */
394
395 /* input name in name, pathname output to buf. */
396
397 char *wxExpandPath(char *buf, const char *name)
398 {
399 register char *d, *s, *nm;
400 char lnm[_MAXPATHLEN];
401 int q;
402
403 // Some compilers don't like this line.
404 // const char trimchars[] = "\n \t";
405
406 char trimchars[4];
407 trimchars[0] = '\n';
408 trimchars[1] = ' ';
409 trimchars[2] = '\t';
410 trimchars[3] = 0;
411
412 #ifdef __WXMSW__
413 const char SEP = '\\';
414 #else
415 const char SEP = '/';
416 #endif
417 buf[0] = '\0';
418 if (name == NULL || *name == '\0')
419 return buf;
420 nm = copystring(name); // Make a scratch copy
421 char *nm_tmp = nm;
422
423 /* Skip leading whitespace and cr */
424 while (strchr((char *)trimchars, *nm) != NULL)
425 nm++;
426 /* And strip off trailing whitespace and cr */
427 s = nm + (q = strlen(nm)) - 1;
428 while (q-- && strchr((char *)trimchars, *s) != NULL)
429 *s = '\0';
430
431 s = nm;
432 d = lnm;
433 #ifdef __WXMSW__
434 q = FALSE;
435 #else
436 q = nm[0] == '\\' && nm[1] == '~';
437 #endif
438
439 /* Expand inline environment variables */
440 while ((*d++ = *s)) {
441 #ifndef __WXMSW__
442 if (*s == '\\') {
443 if ((*(d - 1) = *++s)) {
444 s++;
445 continue;
446 } else
447 break;
448 } else
449 #endif
450 #ifdef __WXMSW__
451 if (*s++ == '$' && (*s == '{' || *s == ')'))
452 #else
453 if (*s++ == '$')
454 #endif
455 {
456 register char *start = d;
457 register int braces = (*s == '{' || *s == '(');
458 register char *value;
459 while ((*d++ = *s))
460 if (braces ? (*s == '}' || *s == ')') : !(isalnum(*s) || *s == '_') )
461 break;
462 else
463 s++;
464 *--d = 0;
465 value = getenv(braces ? start + 1 : start);
466 if (value) {
467 for ((d = start - 1); (*d++ = *value++););
468 d--;
469 if (braces && *s)
470 s++;
471 }
472 }
473 }
474
475 /* Expand ~ and ~user */
476 nm = lnm;
477 s = "";
478 if (nm[0] == '~' && !q)
479 {
480 /* prefix ~ */
481 if (nm[1] == SEP || nm[1] == 0)
482 { /* ~/filename */
483 if ((s = wxGetUserHome("")) != NULL) {
484 if (*++nm)
485 nm++;
486 }
487 } else
488 { /* ~user/filename */
489 register char *nnm;
490 register char *home;
491 for (s = nm; *s && *s != SEP; s++);
492 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
493 was_sep = (*s == SEP);
494 nnm = *s ? s + 1 : s;
495 *s = 0;
496 if ((home = wxGetUserHome(wxString(nm + 1))) == NULL) {
497 if (was_sep) /* replace only if it was there: */
498 *s = SEP;
499 s = "";
500 } else {
501 nm = nnm;
502 s = home;
503 }
504 }
505 }
506
507 d = buf;
508 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
509 /* Copy home dir */
510 while ('\0' != (*d++ = *s++))
511 /* loop */;
512 // Handle root home
513 if (d - 1 > buf && *(d - 2) != SEP)
514 *(d - 1) = SEP;
515 }
516 s = nm;
517 while ((*d++ = *s++));
518
519 delete[] nm_tmp; // clean up alloc
520 /* Now clean up the buffer */
521 return wxRealPath(buf);
522 }
523
524
525 /* Contract Paths to be build upon an environment variable
526 component:
527
528 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
529
530 The call wxExpandPath can convert these back!
531 */
532 char *
533 wxContractPath (const wxString& filename, const wxString& envname, const wxString& user)
534 {
535 static char dest[_MAXPATHLEN];
536
537 if (filename == "")
538 return (char *) NULL;
539
540 strcpy (dest, WXSTRINGCAST filename);
541 #ifdef __WXMSW__
542 Unix2DosFilename(dest);
543 #endif
544
545 // Handle environment
546 char *val = (char *) NULL;
547 char *tcp = (char *) NULL;
548 if (envname != WXSTRINGCAST NULL && (val = getenv (WXSTRINGCAST envname)) != NULL &&
549 (tcp = strstr (dest, val)) != NULL)
550 {
551 strcpy (wxBuffer, tcp + strlen (val));
552 *tcp++ = '$';
553 *tcp++ = '{';
554 strcpy (tcp, WXSTRINGCAST envname);
555 strcat (tcp, "}");
556 strcat (tcp, wxBuffer);
557 }
558
559 // Handle User's home (ignore root homes!)
560 size_t len = 0;
561 if ((val = wxGetUserHome (user)) != NULL &&
562 (len = strlen(val)) > 2 &&
563 strncmp(dest, val, len) == 0)
564 {
565 strcpy(wxBuffer, "~");
566 if (user && *user)
567 strcat(wxBuffer, user);
568 #ifdef __WXMSW__
569 // strcat(wxBuffer, "\\");
570 #else
571 // strcat(wxBuffer, "/");
572 #endif
573 strcat(wxBuffer, dest + len);
574 strcpy (dest, wxBuffer);
575 }
576
577 return dest;
578 }
579
580 // Return just the filename, not the path
581 // (basename)
582 char *wxFileNameFromPath (char *path)
583 {
584 if (path)
585 {
586 register char *tcp;
587
588 tcp = path + strlen (path);
589 while (--tcp >= path)
590 {
591 if (*tcp == '/' || *tcp == '\\'
592 #ifdef __VMS__
593 || *tcp == ':' || *tcp == ']')
594 #else
595 )
596 #endif
597 return tcp + 1;
598 } /* while */
599 #ifdef __WXMSW__
600 if (isalpha (*path) && *(path + 1) == ':')
601 return path + 2;
602 #endif
603 }
604 return path;
605 }
606
607 wxString wxFileNameFromPath (const wxString& path1)
608 {
609 if (path1 != "")
610 {
611
612 char *path = WXSTRINGCAST path1 ;
613 register char *tcp;
614
615 tcp = path + strlen (path);
616 while (--tcp >= path)
617 {
618 if (*tcp == '/' || *tcp == '\\'
619 #ifdef __VMS__
620 || *tcp == ':' || *tcp == ']')
621 #else
622 )
623 #endif
624 return wxString(tcp + 1);
625 } /* while */
626 #ifdef __WXMSW__
627 if (isalpha (*path) && *(path + 1) == ':')
628 return wxString(path + 2);
629 #endif
630 }
631 return wxString("");
632 }
633
634 // Return just the directory, or NULL if no directory
635 char *
636 wxPathOnly (char *path)
637 {
638 if (path && *path)
639 {
640 static char buf[_MAXPATHLEN];
641
642 // Local copy
643 strcpy (buf, path);
644
645 int l = strlen(path);
646 bool done = FALSE;
647
648 int i = l - 1;
649
650 // Search backward for a backward or forward slash
651 while (!done && i > -1)
652 {
653 // ] is for VMS
654 if (path[i] == '/' || path[i] == '\\' || path[i] == ']')
655 {
656 done = TRUE;
657 #ifdef __VMS__
658 buf[i+1] = 0;
659 #else
660 buf[i] = 0;
661 #endif
662
663 return buf;
664 }
665 else i --;
666 }
667
668 #ifdef __WXMSW__
669 // Try Drive specifier
670 if (isalpha (buf[0]) && buf[1] == ':')
671 {
672 // A:junk --> A:. (since A:.\junk Not A:\junk)
673 buf[2] = '.';
674 buf[3] = '\0';
675 return buf;
676 }
677 #endif
678 }
679
680 return (char *) NULL;
681 }
682
683 // Return just the directory, or NULL if no directory
684 wxString wxPathOnly (const wxString& path)
685 {
686 if (path != "")
687 {
688 char buf[_MAXPATHLEN];
689
690 // Local copy
691 strcpy (buf, WXSTRINGCAST path);
692
693 int l = path.Length();
694 bool done = FALSE;
695
696 int i = l - 1;
697
698 // Search backward for a backward or forward slash
699 while (!done && i > -1)
700 {
701 // ] is for VMS
702 if (path[i] == '/' || path[i] == '\\' || path[i] == ']')
703 {
704 done = TRUE;
705 #ifdef __VMS__
706 buf[i+1] = 0;
707 #else
708 buf[i] = 0;
709 #endif
710
711 return wxString(buf);
712 }
713 else i --;
714 }
715
716 #ifdef __WXMSW__
717 // Try Drive specifier
718 if (isalpha (buf[0]) && buf[1] == ':')
719 {
720 // A:junk --> A:. (since A:.\junk Not A:\junk)
721 buf[2] = '.';
722 buf[3] = '\0';
723 return wxString(buf);
724 }
725 #endif
726 }
727
728 return wxString("");
729 }
730
731 // Utility for converting delimiters in DOS filenames to UNIX style
732 // and back again - or we get nasty problems with delimiters.
733 // Also, convert to lower case, since case is significant in UNIX.
734
735 void
736 wxDos2UnixFilename (char *s)
737 {
738 if (s)
739 while (*s)
740 {
741 if (*s == '\\')
742 *s = '/';
743 #ifdef __WXMSW__
744 else
745 *s = wxToLower (*s); // Case INDEPENDENT
746 #endif
747 s++;
748 }
749 }
750
751 void
752 #ifdef __WXMSW__
753 wxUnix2DosFilename (char *s)
754 #else
755 wxUnix2DosFilename (char *WXUNUSED(s))
756 #endif
757 {
758 // Yes, I really mean this to happen under DOS only! JACS
759 #ifdef __WXMSW__
760 if (s)
761 while (*s)
762 {
763 if (*s == '/')
764 *s = '\\';
765 s++;
766 }
767 #endif
768 }
769
770 // Concatenate two files to form third
771 bool
772 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
773 {
774 char *outfile = wxGetTempFileName("cat");
775
776 FILE *fp1 = (FILE *) NULL;
777 FILE *fp2 = (FILE *) NULL;
778 FILE *fp3 = (FILE *) NULL;
779 // Open the inputs and outputs
780 if ((fp1 = fopen (WXSTRINGCAST file1, "rb")) == NULL ||
781 (fp2 = fopen (WXSTRINGCAST file2, "rb")) == NULL ||
782 (fp3 = fopen (outfile, "wb")) == NULL)
783 {
784 if (fp1)
785 fclose (fp1);
786 if (fp2)
787 fclose (fp2);
788 if (fp3)
789 fclose (fp3);
790 return FALSE;
791 }
792
793 int ch;
794 while ((ch = getc (fp1)) != EOF)
795 (void) putc (ch, fp3);
796 fclose (fp1);
797
798 while ((ch = getc (fp2)) != EOF)
799 (void) putc (ch, fp3);
800 fclose (fp2);
801
802 fclose (fp3);
803 bool result = wxRenameFile(outfile, file3);
804 delete[] outfile;
805 return result;
806 }
807
808 // Copy files
809 bool
810 wxCopyFile (const wxString& file1, const wxString& file2)
811 {
812 FILE *fd1;
813 FILE *fd2;
814 int ch;
815
816 if ((fd1 = fopen (WXSTRINGCAST file1, "rb")) == NULL)
817 return FALSE;
818 if ((fd2 = fopen (WXSTRINGCAST file2, "wb")) == NULL)
819 {
820 fclose (fd1);
821 return FALSE;
822 }
823
824 while ((ch = getc (fd1)) != EOF)
825 (void) putc (ch, fd2);
826
827 fclose (fd1);
828 fclose (fd2);
829 return TRUE;
830 }
831
832 bool
833 wxRenameFile (const wxString& file1, const wxString& file2)
834 {
835 // Normal system call
836 if (0 == rename (WXSTRINGCAST file1, WXSTRINGCAST file2))
837 return TRUE;
838 // Try to copy
839 if (wxCopyFile(file1, file2)) {
840 wxRemoveFile(file1);
841 return TRUE;
842 }
843 // Give up
844 return FALSE;
845 }
846
847 bool wxRemoveFile(const wxString& file)
848 {
849 #if defined(_MSC_VER) || defined(__BORLANDC__)
850 int flag = remove(WXSTRINGCAST file);
851 #else
852 int flag = unlink(WXSTRINGCAST file);
853 #endif
854 return (flag == 0) ;
855 }
856
857 bool wxMkdir(const wxString& dir)
858 {
859 #if defined(__WXSTUBS__)
860 return FALSE;
861 #elif defined(__VMS__)
862 return FALSE;
863 #elif (defined(__GNUWIN32__) && !defined(__MINGW32__)) || !defined(__WXMSW__)
864 return (mkdir (WXSTRINGCAST dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0);
865 #else
866 return (mkdir(WXSTRINGCAST dir) == 0);
867 #endif
868 }
869
870 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
871 {
872 #ifdef __VMS__
873 return FALSE;
874 #else
875 return (rmdir(WXSTRINGCAST dir) == 0);
876 #endif
877 }
878
879 #if 0
880 bool wxDirExists(const wxString& dir)
881 {
882 #ifdef __VMS__
883 return FALSE;
884 #elif !defined(__WXMSW__)
885 struct stat sbuf;
886 return (stat(dir, &sbuf) != -1) && S_ISDIR(sbuf.st_mode) ? TRUE : FALSE;
887 #else
888
889 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
890 #if defined(__WIN32__)
891 WIN32_FIND_DATA fileInfo;
892 #else
893 #ifdef __BORLANDC__
894 struct ffblk fileInfo;
895 #else
896 struct find_t fileInfo;
897 #endif
898 #endif
899
900 #if defined(__WIN32__)
901 HANDLE h = FindFirstFile((LPTSTR) WXSTRINGCAST dir,(LPWIN32_FIND_DATA)&fileInfo);
902
903 if (h==INVALID_HANDLE_VALUE)
904 return FALSE;
905 else {
906 FindClose(h);
907 return ((fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
908 }
909 #else
910 // In Borland findfirst has a different argument
911 // ordering from _dos_findfirst. But _dos_findfirst
912 // _should_ be ok in both MS and Borland... why not?
913 #ifdef __BORLANDC__
914 return ((findfirst(WXSTRINGCAST dir, &fileInfo, _A_SUBDIR) == 0 && (fileInfo.ff_attrib & _A_SUBDIR) != 0));
915 #else
916 return (((_dos_findfirst(WXSTRINGCAST dir, _A_SUBDIR, &fileInfo) == 0) && (fileInfo.attrib & _A_SUBDIR)) != 0);
917 #endif
918 #endif
919
920 #endif
921 }
922
923 #endif
924
925 // does the path exists? (may have or not '/' or '\\' at the end)
926 bool wxPathExists(const char *pszPathName)
927 {
928 // Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
929 // OTOH, we should change "d:" to "d:\" and leave "\" as is.
930 wxString strPath(pszPathName);
931 if ( wxEndsWithPathSeparator(pszPathName) && pszPathName[1] != '\0' )
932 strPath.Last() = '\0';
933
934 struct stat st;
935 return stat(strPath, &st) == 0 && (st.st_mode & S_IFDIR);
936 }
937
938 // Get a temporary filename, opening and closing the file.
939 char *wxGetTempFileName(const wxString& prefix, char *buf)
940 {
941 #ifdef __WINDOWS__
942
943 #ifndef __WIN32__
944 char tmp[144];
945 ::GetTempFileName(0, WXSTRINGCAST prefix, 0, tmp);
946 #else
947 char tmp[MAX_PATH];
948 char tmpPath[MAX_PATH];
949 ::GetTempPath(MAX_PATH, tmpPath);
950 ::GetTempFileName(tmpPath, WXSTRINGCAST prefix, 0, tmp);
951 #endif
952 if (buf) strcpy(buf, tmp);
953 else buf = copystring(tmp);
954 return buf;
955
956 #else
957 static short last_temp = 0; // cache last to speed things a bit
958 // At most 1000 temp files to a process! We use a ring count.
959 char tmp[100]; // FIXME static buffer
960
961 for (short suffix = last_temp + 1; suffix != last_temp; ++suffix %= 1000)
962 {
963 sprintf (tmp, "/tmp/%s%d.%03x", WXSTRINGCAST prefix, (int) getpid (), (int) suffix);
964 if (!wxFileExists( tmp ))
965 {
966 // Touch the file to create it (reserve name)
967 FILE *fd = fopen (tmp, "w");
968 if (fd)
969 fclose (fd);
970 last_temp = suffix;
971 if (buf)
972 strcpy( buf, tmp);
973 else
974 buf = copystring( tmp );
975 return buf;
976 }
977 }
978 cerr << _("wxWindows: error finding temporary file name.\n");
979 if (buf) buf[0] = 0;
980 return (char *) NULL;
981 #endif
982 }
983
984 // Get first file name matching given wild card.
985
986 #ifdef __UNIX__
987
988 // Get first file name matching given wild card.
989 // Flags are reserved for future use.
990
991 #ifndef __VMS__
992 static DIR *wxDirStream = (DIR *) NULL;
993 static char *wxFileSpec = (char *) NULL;
994 static int wxFindFileFlags = 0;
995 #endif
996
997 char *wxFindFirstFile(const char *spec, int flags)
998 {
999 #ifndef __VMS__
1000 if (wxDirStream)
1001 closedir(wxDirStream); // edz 941103: better housekeping
1002
1003 wxFindFileFlags = flags;
1004
1005 if (wxFileSpec)
1006 delete[] wxFileSpec;
1007 wxFileSpec = copystring(spec);
1008
1009 // Find path only so we can concatenate
1010 // found file onto path
1011 char *p = wxPathOnly(wxFileSpec);
1012
1013 /* MATTHEW: special case: path is really "/" */
1014 if (p && !*p && *wxFileSpec == '/')
1015 p = "/";
1016 /* MATTHEW: p is NULL => Local directory */
1017 if (!p)
1018 p = ".";
1019
1020 if ((wxDirStream=opendir(p))==NULL)
1021 return (char *) NULL;
1022
1023 /* MATTHEW: [5] wxFindNextFile can do the rest of the work */
1024 return wxFindNextFile();
1025 #endif
1026 // ifndef __VMS__
1027 return (char *) NULL;
1028 }
1029
1030 char *wxFindNextFile(void)
1031 {
1032 #ifndef __VMS__
1033 static char buf[400]; // FIXME static buffer
1034
1035 /* MATTHEW: [2] Don't crash if we read too many times */
1036 if (!wxDirStream)
1037 return (char *) NULL;
1038
1039 // Find path only so we can concatenate
1040 // found file onto path
1041 char *p = wxPathOnly(wxFileSpec);
1042 char *n = wxFileNameFromPath(wxFileSpec);
1043
1044 /* MATTHEW: special case: path is really "/" */
1045 if (p && !*p && *wxFileSpec == '/')
1046 p = "/";
1047
1048 // Do the reading
1049 struct dirent *nextDir;
1050 for (nextDir = readdir(wxDirStream); nextDir != NULL; nextDir = readdir(wxDirStream))
1051 {
1052
1053 /* MATTHEW: [5] Only return "." and ".." when they match, and only return
1054 directories when flags & wxDIR */
1055 if (wxMatchWild(n, nextDir->d_name)) {
1056 bool isdir;
1057
1058 buf[0] = 0;
1059 if (p && *p) {
1060 strcpy(buf, p);
1061 if (strcmp(p, "/") != 0)
1062 strcat(buf, "/");
1063 }
1064 strcat(buf, nextDir->d_name);
1065
1066 if ((strcmp(nextDir->d_name, ".") == 0) ||
1067 (strcmp(nextDir->d_name, "..") == 0)) {
1068 if (wxFindFileFlags && !(wxFindFileFlags & wxDIR))
1069 continue;
1070 isdir = TRUE;
1071 } else
1072 isdir = wxDirExists(buf);
1073
1074 if (!wxFindFileFlags
1075 || ((wxFindFileFlags & wxDIR) && isdir)
1076 || ((wxFindFileFlags & wxFILE) && !isdir))
1077 return buf;
1078 }
1079 }
1080 closedir(wxDirStream);
1081 wxDirStream = (DIR *) NULL;
1082 #endif
1083 // ifndef __VMS__
1084
1085 return (char *) NULL;
1086 }
1087
1088 #elif defined(__WXMSW__)
1089
1090 #ifdef __WIN32__
1091 HANDLE wxFileStrucHandle = INVALID_HANDLE_VALUE;
1092 WIN32_FIND_DATA wxFileStruc;
1093 #else
1094 #ifdef __BORLANDC__
1095 static struct ffblk wxFileStruc;
1096 #else
1097 static struct _find_t wxFileStruc;
1098 #endif
1099 #endif
1100 static wxString wxFileSpec = "";
1101 static int wxFindFileFlags;
1102
1103 char *wxFindFirstFile(const char *spec, int flags)
1104 {
1105 wxFileSpec = spec;
1106 wxFindFileFlags = flags; /* MATTHEW: [5] Remember flags */
1107
1108 // Find path only so we can concatenate
1109 // found file onto path
1110 wxString path1(wxFileSpec);
1111 char *p = wxPathOnly(WXSTRINGCAST path1);
1112 if (p && (strlen(p) > 0))
1113 strcpy(wxBuffer, p);
1114 else
1115 wxBuffer[0] = 0;
1116
1117 #ifdef __WIN32__
1118 if (wxFileStrucHandle != INVALID_HANDLE_VALUE)
1119 FindClose(wxFileStrucHandle);
1120
1121 wxFileStrucHandle = ::FindFirstFile(WXSTRINGCAST spec, &wxFileStruc);
1122
1123 if (wxFileStrucHandle == INVALID_HANDLE_VALUE)
1124 return NULL;
1125
1126 bool isdir = !!(wxFileStruc.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1127
1128 if (isdir && !(flags & wxDIR))
1129 return wxFindNextFile();
1130 else if (!isdir && flags && !(flags & wxFILE))
1131 return wxFindNextFile();
1132
1133 if (wxBuffer[0] != 0)
1134 strcat(wxBuffer, "\\");
1135 strcat(wxBuffer, wxFileStruc.cFileName);
1136 return wxBuffer;
1137 #else
1138
1139 int flag = _A_NORMAL;
1140 if (flags & wxDIR) /* MATTHEW: [5] Use & */
1141 flag = _A_SUBDIR;
1142
1143 #ifdef __BORLANDC__
1144 if (findfirst(WXSTRINGCAST spec, &wxFileStruc, flag) == 0)
1145 #else
1146 if (_dos_findfirst(WXSTRINGCAST spec, flag, &wxFileStruc) == 0)
1147 #endif
1148 {
1149 /* MATTHEW: [5] Check directory flag */
1150 char attrib;
1151
1152 #ifdef __BORLANDC__
1153 attrib = wxFileStruc.ff_attrib;
1154 #else
1155 attrib = wxFileStruc.attrib;
1156 #endif
1157
1158 if (attrib & _A_SUBDIR) {
1159 if (!(wxFindFileFlags & wxDIR))
1160 return wxFindNextFile();
1161 } else if (wxFindFileFlags && !(wxFindFileFlags & wxFILE))
1162 return wxFindNextFile();
1163
1164 if (wxBuffer[0] != 0)
1165 strcat(wxBuffer, "\\");
1166
1167 #ifdef __BORLANDC__
1168 strcat(wxBuffer, wxFileStruc.ff_name);
1169 #else
1170 strcat(wxBuffer, wxFileStruc.name);
1171 #endif
1172 return wxBuffer;
1173 }
1174 else
1175 return NULL;
1176 #endif // __WIN32__
1177 }
1178
1179 char *wxFindNextFile(void)
1180 {
1181 // Find path only so we can concatenate
1182 // found file onto path
1183 wxString p2(wxFileSpec);
1184 char *p = wxPathOnly(WXSTRINGCAST p2);
1185 if (p && (strlen(p) > 0))
1186 strcpy(wxBuffer, p);
1187 else
1188 wxBuffer[0] = 0;
1189
1190 try_again:
1191
1192 #ifdef __WIN32__
1193 if (wxFileStrucHandle == INVALID_HANDLE_VALUE)
1194 return NULL;
1195
1196 bool success = (FindNextFile(wxFileStrucHandle, &wxFileStruc) != 0);
1197 if (!success) {
1198 FindClose(wxFileStrucHandle);
1199 wxFileStrucHandle = INVALID_HANDLE_VALUE;
1200 return NULL;
1201 }
1202
1203 bool isdir = !!(wxFileStruc.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1204
1205 if (isdir && !(wxFindFileFlags & wxDIR))
1206 goto try_again;
1207 else if (!isdir && wxFindFileFlags && !(wxFindFileFlags & wxFILE))
1208 goto try_again;
1209
1210 if (wxBuffer[0] != 0)
1211 strcat(wxBuffer, "\\");
1212 strcat(wxBuffer, wxFileStruc.cFileName);
1213 return wxBuffer;
1214 #else
1215
1216 #ifdef __BORLANDC__
1217 if (findnext(&wxFileStruc) == 0)
1218 #else
1219 if (_dos_findnext(&wxFileStruc) == 0)
1220 #endif
1221 {
1222 /* MATTHEW: [5] Check directory flag */
1223 char attrib;
1224
1225 #ifdef __BORLANDC__
1226 attrib = wxFileStruc.ff_attrib;
1227 #else
1228 attrib = wxFileStruc.attrib;
1229 #endif
1230
1231 if (attrib & _A_SUBDIR) {
1232 if (!(wxFindFileFlags & wxDIR))
1233 goto try_again;
1234 } else if (wxFindFileFlags && !(wxFindFileFlags & wxFILE))
1235 goto try_again;
1236
1237
1238 if (wxBuffer[0] != 0)
1239 strcat(wxBuffer, "\\");
1240 #ifdef __BORLANDC__
1241 strcat(wxBuffer, wxFileStruc.ff_name);
1242 #else
1243 strcat(wxBuffer, wxFileStruc.name);
1244 #endif
1245 return wxBuffer;
1246 }
1247 else
1248 return NULL;
1249 #endif
1250 }
1251
1252 #endif
1253 // __WXMSW__
1254
1255 // Get current working directory.
1256 // If buf is NULL, allocates space using new, else
1257 // copies into buf.
1258 char *wxGetWorkingDirectory(char *buf, int sz)
1259 {
1260 if (!buf)
1261 buf = new char[sz+1];
1262 #ifdef _MSC_VER
1263 if (_getcwd(buf, sz) == NULL) {
1264 #else
1265 if (getcwd(buf, sz) == NULL) {
1266 #endif
1267 buf[0] = '.';
1268 buf[1] = '\0';
1269 }
1270 return buf;
1271 }
1272
1273 bool wxSetWorkingDirectory(const wxString& d)
1274 {
1275 #ifdef __UNIX__
1276 return (chdir(d) == 0);
1277 #elif defined(__WINDOWS__)
1278
1279 #ifdef __WIN32__
1280 return (bool)(SetCurrentDirectory(d) != 0);
1281 #else
1282 // Must change drive, too.
1283 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1284 if (isDriveSpec)
1285 {
1286 char firstChar = d[0];
1287
1288 // To upper case
1289 if (firstChar > 90)
1290 firstChar = firstChar - 32;
1291
1292 // To a drive number
1293 unsigned int driveNo = firstChar - 64;
1294 if (driveNo > 0)
1295 {
1296 unsigned int noDrives;
1297 _dos_setdrive(driveNo, &noDrives);
1298 }
1299 }
1300 bool success = (chdir(WXSTRINGCAST d) == 0);
1301
1302 return success;
1303 #endif
1304
1305 #endif
1306 }
1307
1308 bool wxEndsWithPathSeparator(const char *pszFileName)
1309 {
1310 size_t len = Strlen(pszFileName);
1311 if ( len == 0 )
1312 return FALSE;
1313 else
1314 return wxIsPathSeparator(pszFileName[len - 1]);
1315 }
1316
1317 // find a file in a list of directories, returns false if not found
1318 bool wxFindFileInPath(wxString *pStr, const char *pszPath, const char *pszFile)
1319 {
1320 // we assume that it's not empty
1321 wxCHECK_MSG( !IsEmpty(pszFile), FALSE,
1322 _("empty file name in wxFindFileInPath"));
1323
1324 // skip path separator in the beginning of the file name if present
1325 if ( wxIsPathSeparator(*pszFile) )
1326 pszFile++;
1327
1328 // copy the path (strtok will modify it)
1329 char *szPath = new char[strlen(pszPath) + 1];
1330 strcpy(szPath, pszPath);
1331
1332 wxString strFile;
1333 char *pc;
1334 for ( pc = strtok(szPath, PATH_SEP); pc; pc = strtok((char *) NULL, PATH_SEP) ) {
1335 // search for the file in this directory
1336 strFile = pc;
1337 if ( !wxEndsWithPathSeparator(pc) )
1338 strFile += FILE_SEP_PATH;
1339 strFile += pszFile;
1340
1341 if ( FileExists(strFile) ) {
1342 *pStr = strFile;
1343 break;
1344 }
1345 }
1346
1347 delete [] szPath;
1348
1349 return pc != NULL; // if true => we breaked from the loop
1350 }
1351
1352 void WXDLLEXPORT wxSplitPath(const char *pszFileName,
1353 wxString *pstrPath,
1354 wxString *pstrName,
1355 wxString *pstrExt)
1356 {
1357 wxCHECK_RET( pszFileName, _("NULL file name in wxSplitPath") );
1358
1359 const char *pDot = strrchr(pszFileName, FILE_SEP_EXT);
1360 const char *pSepUnix = strrchr(pszFileName, FILE_SEP_PATH_UNIX);
1361 const char *pSepDos = strrchr(pszFileName, FILE_SEP_PATH_DOS);
1362
1363 // take the last of the two
1364 size_t nPosUnix = pSepUnix ? pSepUnix - pszFileName : 0;
1365 size_t nPosDos = pSepDos ? pSepDos - pszFileName : 0;
1366 if ( nPosDos > nPosUnix )
1367 nPosUnix = nPosDos;
1368 // size_t nLen = Strlen(pszFileName);
1369
1370 if ( pstrPath )
1371 *pstrPath = wxString(pszFileName, nPosUnix);
1372 if ( pDot ) {
1373 size_t nPosDot = pDot - pszFileName;
1374 if ( pstrName )
1375 *pstrName = wxString(pszFileName + nPosUnix + 1, nPosDot - nPosUnix);
1376 if ( pstrExt )
1377 *pstrExt = wxString(pszFileName + nPosDot + 1);
1378 }
1379 else {
1380 if ( pstrName )
1381 *pstrName = wxString(pszFileName + nPosUnix + 1);
1382 if ( pstrExt )
1383 pstrExt->Empty();
1384 }
1385 }
1386
1387 //------------------------------------------------------------------------
1388 // wild character routines
1389 //------------------------------------------------------------------------
1390
1391 bool wxIsWild( const wxString& pattern )
1392 {
1393 wxString tmp = pattern;
1394 char *pat = WXSTRINGCAST(tmp);
1395 while (*pat) {
1396 switch (*pat++) {
1397 case '?': case '*': case '[': case '{':
1398 return TRUE;
1399 case '\\':
1400 if (!*pat++)
1401 return FALSE;
1402 }
1403 }
1404 return FALSE;
1405 };
1406
1407 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1408
1409 #if defined(HAVE_FNMATCH_H) || defined(__GNUWIN32__)
1410 {
1411 if(dot_special)
1412 return fnmatch(pat.c_str(), text.c_str(), FNM_PERIOD) == 0;
1413 else
1414 return fnmatch(pat.c_str(), text.c_str(), 0) == 0;
1415 }
1416 #else
1417
1418 #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1419 /*
1420 * WARNING: this code is broken!
1421 */
1422 {
1423 wxString tmp1 = pat;
1424 char *pattern = WXSTRINGCAST(tmp1);
1425 wxString tmp2 = text;
1426 char *str = WXSTRINGCAST(tmp2);
1427 char c;
1428 char *cp;
1429 bool done = FALSE, ret_code, ok;
1430 // Below is for vi fans
1431 const char OB = '{', CB = '}';
1432
1433 // dot_special means '.' only matches '.'
1434 if (dot_special && *str == '.' && *pattern != *str)
1435 return FALSE;
1436
1437 while ((*pattern != '\0') && (!done)
1438 && (((*str=='\0')&&((*pattern==OB)||(*pattern=='*')))||(*str!='\0'))) {
1439 switch (*pattern) {
1440 case '\\':
1441 pattern++;
1442 if (*pattern != '\0')
1443 pattern++;
1444 break;
1445 case '*':
1446 pattern++;
1447 ret_code = FALSE;
1448 while ((*str!='\0')
1449 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1450 /*loop*/;
1451 if (ret_code) {
1452 while (*str != '\0')
1453 str++;
1454 while (*pattern != '\0')
1455 pattern++;
1456 }
1457 break;
1458 case '[':
1459 pattern++;
1460 repeat:
1461 if ((*pattern == '\0') || (*pattern == ']')) {
1462 done = TRUE;
1463 break;
1464 }
1465 if (*pattern == '\\') {
1466 pattern++;
1467 if (*pattern == '\0') {
1468 done = TRUE;
1469 break;
1470 }
1471 }
1472 if (*(pattern + 1) == '-') {
1473 c = *pattern;
1474 pattern += 2;
1475 if (*pattern == ']') {
1476 done = TRUE;
1477 break;
1478 }
1479 if (*pattern == '\\') {
1480 pattern++;
1481 if (*pattern == '\0') {
1482 done = TRUE;
1483 break;
1484 }
1485 }
1486 if ((*str < c) || (*str > *pattern)) {
1487 pattern++;
1488 goto repeat;
1489 }
1490 } else if (*pattern != *str) {
1491 pattern++;
1492 goto repeat;
1493 }
1494 pattern++;
1495 while ((*pattern != ']') && (*pattern != '\0')) {
1496 if ((*pattern == '\\') && (*(pattern + 1) != '\0'))
1497 pattern++;
1498 pattern++;
1499 }
1500 if (*pattern != '\0') {
1501 pattern++, str++;
1502 }
1503 break;
1504 case '?':
1505 pattern++;
1506 str++;
1507 break;
1508 case OB:
1509 pattern++;
1510 while ((*pattern != CB) && (*pattern != '\0')) {
1511 cp = str;
1512 ok = TRUE;
1513 while (ok && (*cp != '\0') && (*pattern != '\0')
1514 && (*pattern != ',') && (*pattern != CB)) {
1515 if (*pattern == '\\')
1516 pattern++;
1517 ok = (*pattern++ == *cp++);
1518 }
1519 if (*pattern == '\0') {
1520 ok = FALSE;
1521 done = TRUE;
1522 break;
1523 } else if (ok) {
1524 str = cp;
1525 while ((*pattern != CB) && (*pattern != '\0')) {
1526 if (*++pattern == '\\') {
1527 if (*++pattern == CB)
1528 pattern++;
1529 }
1530 }
1531 } else {
1532 while (*pattern!=CB && *pattern!=',' && *pattern!='\0') {
1533 if (*++pattern == '\\') {
1534 if (*++pattern == CB || *pattern == ',')
1535 pattern++;
1536 }
1537 }
1538 }
1539 if (*pattern != '\0')
1540 pattern++;
1541 }
1542 break;
1543 default:
1544 if (*str == *pattern) {
1545 str++, pattern++;
1546 } else {
1547 done = TRUE;
1548 }
1549 }
1550 }
1551 while (*pattern == '*')
1552 pattern++;
1553 return ((*str == '\0') && (*pattern == '\0'));
1554 };
1555
1556 #endif
1557
1558 #ifdef _MSC_VER
1559 #pragma warning(default:4706) // assignment within conditional expression
1560 #endif // VC++