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