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