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