]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/filefn.cpp
* Fixed two memory leaks.
[wxWidgets.git] / src / common / filefn.cpp
... / ...
CommitLineData
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
80IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
81#endif
82
83extern char *wxBuffer;
84
85void 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
91void 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 ((char *) 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.
122void 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
133bool 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
152wxString 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
182wxString 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
209bool
210wxFileExists (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?
222bool 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
231bool
232wxIsAbsolutePath (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
256void 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
271void 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
287char *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
339char *wxCopyAbsolutePath(const wxString& filename)
340{
341 if (filename == "")
342 return (char *) 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
385char *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 int 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 */
520char *
521wxContractPath (const wxString& filename, const wxString& envname, const wxString& user)
522{
523 static char dest[_MAXPATHLEN];
524
525 if (filename == "")
526 return (char *) NULL;
527
528 strcpy (dest, WXSTRINGCAST filename);
529#ifdef __WXMSW__
530 Unix2DosFilename(dest);
531#endif
532
533 // Handle environment
534 char *val = (char *) NULL;
535 char *tcp = (char *) NULL;
536 if (envname != WXSTRINGCAST 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)
570char *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
595wxString 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
623char *
624wxPathOnly (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 (char *) NULL;
669}
670
671// Return just the directory, or NULL if no directory
672wxString 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
723void
724wxDos2UnixFilename (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
739void
740#ifdef __WXMSW__
741wxUnix2DosFilename (char *s)
742#else
743wxUnix2DosFilename (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
759bool
760wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
761{
762 char *outfile = wxGetTempFileName("cat");
763
764 FILE *fp1 = (FILE *) NULL;
765 FILE *fp2 = (FILE *) NULL;
766 FILE *fp3 = (FILE *) 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
797bool
798wxCopyFile (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
820bool
821wxRenameFile (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
835bool 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
845bool wxMkdir(const wxString& dir)
846{
847#if defined(__WXSTUBS__)
848 return FALSE;
849#elif defined(__VMS__)
850 return FALSE;
851#elif (defined(__GNUWIN32__) && !defined(__MINGW32__)) || !defined(__WXMSW__)
852 return (mkdir (WXSTRINGCAST dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0);
853#else
854 return (mkdir(WXSTRINGCAST dir) == 0);
855#endif
856}
857
858bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
859{
860#ifdef __VMS__
861 return FALSE;
862#else
863 return (rmdir(WXSTRINGCAST dir) == 0);
864#endif
865}
866
867#if 0
868bool wxDirExists(const wxString& dir)
869{
870#ifdef __VMS__
871 return FALSE;
872#elif !defined(__WXMSW__)
873 struct stat sbuf;
874 return (stat(dir, &sbuf) != -1) && S_ISDIR(sbuf.st_mode) ? TRUE : FALSE;
875#else
876
877 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
878#if defined(__WIN32__)
879 WIN32_FIND_DATA fileInfo;
880#else
881#ifdef __BORLANDC__
882 struct ffblk fileInfo;
883#else
884 struct find_t fileInfo;
885#endif
886#endif
887
888#if defined(__WIN32__)
889 HANDLE h = FindFirstFile((LPTSTR) WXSTRINGCAST dir,(LPWIN32_FIND_DATA)&fileInfo);
890
891 if (h==INVALID_HANDLE_VALUE)
892 return FALSE;
893 else {
894 FindClose(h);
895 return ((fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
896 }
897#else
898 // In Borland findfirst has a different argument
899 // ordering from _dos_findfirst. But _dos_findfirst
900 // _should_ be ok in both MS and Borland... why not?
901#ifdef __BORLANDC__
902 return ((findfirst(WXSTRINGCAST dir, &fileInfo, _A_SUBDIR) == 0 && (fileInfo.ff_attrib & _A_SUBDIR) != 0));
903#else
904 return (((_dos_findfirst(WXSTRINGCAST dir, _A_SUBDIR, &fileInfo) == 0) && (fileInfo.attrib & _A_SUBDIR)) != 0);
905#endif
906#endif
907
908#endif
909}
910
911#endif
912
913// does the path exists? (may have or not '/' or '\\' at the end)
914bool wxPathExists(const char *pszPathName)
915{
916 // Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
917 // OTOH, we should change "d:" to "d:\" and leave "\" as is.
918 wxString strPath(pszPathName);
919 if ( wxEndsWithPathSeparator(pszPathName) && pszPathName[1] != '\0' )
920 strPath.Last() = '\0';
921
922 struct stat st;
923 return stat(strPath, &st) == 0 && (st.st_mode & S_IFDIR);
924}
925
926// Get a temporary filename, opening and closing the file.
927char *wxGetTempFileName(const wxString& prefix, char *buf)
928{
929#ifdef __WINDOWS__
930
931#ifndef __WIN32__
932 char tmp[144];
933 ::GetTempFileName(0, WXSTRINGCAST prefix, 0, tmp);
934#else
935 char tmp[MAX_PATH];
936 char tmpPath[MAX_PATH];
937 ::GetTempPath(MAX_PATH, tmpPath);
938 ::GetTempFileName(tmpPath, WXSTRINGCAST prefix, 0, tmp);
939#endif
940 if (buf) strcpy(buf, tmp);
941 else buf = copystring(tmp);
942 return buf;
943
944#else
945 static short last_temp = 0; // cache last to speed things a bit
946 // At most 1000 temp files to a process! We use a ring count.
947 char tmp[100];
948
949 for (short suffix = last_temp + 1; suffix != last_temp; ++suffix %= 1000)
950 {
951 sprintf (tmp, "/tmp/%s%d.%03x", WXSTRINGCAST prefix, (int) getpid (), (int) suffix);
952 if (!wxFileExists( tmp ))
953 {
954 // Touch the file to create it (reserve name)
955 FILE *fd = fopen (tmp, "w");
956 if (fd)
957 fclose (fd);
958 last_temp = suffix;
959 if (buf)
960 strcpy( buf, tmp);
961 else
962 buf = copystring( tmp );
963 return buf;
964 }
965 }
966 cerr << _("wxWindows: error finding temporary file name.\n");
967 if (buf) buf[0] = 0;
968 return (char *) NULL;
969#endif
970}
971
972// Get first file name matching given wild card.
973
974#ifdef __UNIX__
975
976// Get first file name matching given wild card.
977// Flags are reserved for future use.
978
979#ifndef __VMS__
980static DIR *wxDirStream = (DIR *) NULL;
981static char *wxFileSpec = (char *) NULL;
982static int wxFindFileFlags = 0;
983#endif
984
985char *wxFindFirstFile(const char *spec, int flags)
986{
987#ifndef __VMS__
988 if (wxDirStream)
989 closedir(wxDirStream); // edz 941103: better housekeping
990
991 wxFindFileFlags = flags;
992
993 if (wxFileSpec)
994 delete[] wxFileSpec;
995 wxFileSpec = copystring(spec);
996
997 // Find path only so we can concatenate
998 // found file onto path
999 char *p = wxPathOnly(wxFileSpec);
1000
1001 /* MATTHEW: special case: path is really "/" */
1002 if (p && !*p && *wxFileSpec == '/')
1003 p = "/";
1004 /* MATTHEW: p is NULL => Local directory */
1005 if (!p)
1006 p = ".";
1007
1008 if ((wxDirStream=opendir(p))==NULL)
1009 return (char *) NULL;
1010
1011 /* MATTHEW: [5] wxFindNextFile can do the rest of the work */
1012 return wxFindNextFile();
1013#endif
1014 // ifndef __VMS__
1015 return (char *) NULL;
1016}
1017
1018char *wxFindNextFile(void)
1019{
1020#ifndef __VMS__
1021 static char buf[400];
1022
1023 /* MATTHEW: [2] Don't crash if we read too many times */
1024 if (!wxDirStream)
1025 return (char *) NULL;
1026
1027 // Find path only so we can concatenate
1028 // found file onto path
1029 char *p = wxPathOnly(wxFileSpec);
1030 char *n = wxFileNameFromPath(wxFileSpec);
1031
1032 /* MATTHEW: special case: path is really "/" */
1033 if (p && !*p && *wxFileSpec == '/')
1034 p = "/";
1035
1036 // Do the reading
1037 struct dirent *nextDir;
1038 for (nextDir = readdir(wxDirStream); nextDir != NULL; nextDir = readdir(wxDirStream))
1039 {
1040
1041 /* MATTHEW: [5] Only return "." and ".." when they match, and only return
1042 directories when flags & wxDIR */
1043 if (wxMatchWild(n, nextDir->d_name)) {
1044 bool isdir;
1045
1046 buf[0] = 0;
1047 if (p && *p) {
1048 strcpy(buf, p);
1049 if (strcmp(p, "/") != 0)
1050 strcat(buf, "/");
1051 }
1052 strcat(buf, nextDir->d_name);
1053
1054 if ((strcmp(nextDir->d_name, ".") == 0) ||
1055 (strcmp(nextDir->d_name, "..") == 0)) {
1056 if (wxFindFileFlags && !(wxFindFileFlags & wxDIR))
1057 continue;
1058 isdir = TRUE;
1059 } else
1060 isdir = wxDirExists(buf);
1061
1062 if (!wxFindFileFlags
1063 || ((wxFindFileFlags & wxDIR) && isdir)
1064 || ((wxFindFileFlags & wxFILE) && !isdir))
1065 return buf;
1066 }
1067 }
1068 closedir(wxDirStream);
1069 wxDirStream = (DIR *) NULL;
1070#endif
1071 // ifndef __VMS__
1072
1073 return (char *) NULL;
1074}
1075
1076#elif defined(__WXMSW__)
1077
1078#ifdef __WIN32__
1079HANDLE wxFileStrucHandle = INVALID_HANDLE_VALUE;
1080WIN32_FIND_DATA wxFileStruc;
1081#else
1082#ifdef __BORLANDC__
1083static struct ffblk wxFileStruc;
1084#else
1085static struct _find_t wxFileStruc;
1086#endif
1087#endif
1088static wxString wxFileSpec = "";
1089static int wxFindFileFlags;
1090
1091char *wxFindFirstFile(const char *spec, int flags)
1092{
1093 wxFileSpec = spec;
1094 wxFindFileFlags = flags; /* MATTHEW: [5] Remember flags */
1095
1096 // Find path only so we can concatenate
1097 // found file onto path
1098 wxString path1(wxFileSpec);
1099 char *p = wxPathOnly(WXSTRINGCAST path1);
1100 if (p && (strlen(p) > 0))
1101 strcpy(wxBuffer, p);
1102 else
1103 wxBuffer[0] = 0;
1104
1105#ifdef __WIN32__
1106 if (wxFileStrucHandle != INVALID_HANDLE_VALUE)
1107 FindClose(wxFileStrucHandle);
1108
1109 wxFileStrucHandle = ::FindFirstFile(WXSTRINGCAST spec, &wxFileStruc);
1110
1111 if (wxFileStrucHandle == INVALID_HANDLE_VALUE)
1112 return NULL;
1113
1114 bool isdir = !!(wxFileStruc.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1115
1116 if (isdir && !(flags & wxDIR))
1117 return wxFindNextFile();
1118 else if (!isdir && flags && !(flags & wxFILE))
1119 return wxFindNextFile();
1120
1121 if (wxBuffer[0] != 0)
1122 strcat(wxBuffer, "\\");
1123 strcat(wxBuffer, wxFileStruc.cFileName);
1124 return wxBuffer;
1125#else
1126
1127 int flag = _A_NORMAL;
1128 if (flags & wxDIR) /* MATTHEW: [5] Use & */
1129 flag = _A_SUBDIR;
1130
1131#ifdef __BORLANDC__
1132 if (findfirst(WXSTRINGCAST spec, &wxFileStruc, flag) == 0)
1133#else
1134 if (_dos_findfirst(WXSTRINGCAST spec, flag, &wxFileStruc) == 0)
1135#endif
1136 {
1137 /* MATTHEW: [5] Check directory flag */
1138 char attrib;
1139
1140#ifdef __BORLANDC__
1141 attrib = wxFileStruc.ff_attrib;
1142#else
1143 attrib = wxFileStruc.attrib;
1144#endif
1145
1146 if (attrib & _A_SUBDIR) {
1147 if (!(wxFindFileFlags & wxDIR))
1148 return wxFindNextFile();
1149 } else if (wxFindFileFlags && !(wxFindFileFlags & wxFILE))
1150 return wxFindNextFile();
1151
1152 if (wxBuffer[0] != 0)
1153 strcat(wxBuffer, "\\");
1154
1155#ifdef __BORLANDC__
1156 strcat(wxBuffer, wxFileStruc.ff_name);
1157#else
1158 strcat(wxBuffer, wxFileStruc.name);
1159#endif
1160 return wxBuffer;
1161 }
1162 else
1163 return NULL;
1164#endif // __WIN32__
1165}
1166
1167char *wxFindNextFile(void)
1168{
1169 // Find path only so we can concatenate
1170 // found file onto path
1171 wxString p2(wxFileSpec);
1172 char *p = wxPathOnly(WXSTRINGCAST p2);
1173 if (p && (strlen(p) > 0))
1174 strcpy(wxBuffer, p);
1175 else
1176 wxBuffer[0] = 0;
1177
1178 try_again:
1179
1180#ifdef __WIN32__
1181 if (wxFileStrucHandle == INVALID_HANDLE_VALUE)
1182 return NULL;
1183
1184 bool success = (FindNextFile(wxFileStrucHandle, &wxFileStruc) != 0);
1185 if (!success) {
1186 FindClose(wxFileStrucHandle);
1187 wxFileStrucHandle = INVALID_HANDLE_VALUE;
1188 return NULL;
1189 }
1190
1191 bool isdir = !!(wxFileStruc.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1192
1193 if (isdir && !(wxFindFileFlags & wxDIR))
1194 goto try_again;
1195 else if (!isdir && wxFindFileFlags && !(wxFindFileFlags & wxFILE))
1196 goto try_again;
1197
1198 if (wxBuffer[0] != 0)
1199 strcat(wxBuffer, "\\");
1200 strcat(wxBuffer, wxFileStruc.cFileName);
1201 return wxBuffer;
1202#else
1203
1204#ifdef __BORLANDC__
1205 if (findnext(&wxFileStruc) == 0)
1206#else
1207 if (_dos_findnext(&wxFileStruc) == 0)
1208#endif
1209 {
1210 /* MATTHEW: [5] Check directory flag */
1211 char attrib;
1212
1213#ifdef __BORLANDC__
1214 attrib = wxFileStruc.ff_attrib;
1215#else
1216 attrib = wxFileStruc.attrib;
1217#endif
1218
1219 if (attrib & _A_SUBDIR) {
1220 if (!(wxFindFileFlags & wxDIR))
1221 goto try_again;
1222 } else if (wxFindFileFlags && !(wxFindFileFlags & wxFILE))
1223 goto try_again;
1224
1225
1226 if (wxBuffer[0] != 0)
1227 strcat(wxBuffer, "\\");
1228#ifdef __BORLANDC__
1229 strcat(wxBuffer, wxFileStruc.ff_name);
1230#else
1231 strcat(wxBuffer, wxFileStruc.name);
1232#endif
1233 return wxBuffer;
1234 }
1235 else
1236 return NULL;
1237#endif
1238}
1239
1240#endif
1241 // __WXMSW__
1242
1243// Get current working directory.
1244// If buf is NULL, allocates space using new, else
1245// copies into buf.
1246char *wxGetWorkingDirectory(char *buf, int sz)
1247{
1248 if (!buf)
1249 buf = new char[sz+1];
1250#ifdef _MSC_VER
1251 if (_getcwd(buf, sz) == NULL) {
1252#else
1253 if (getcwd(buf, sz) == NULL) {
1254#endif
1255 buf[0] = '.';
1256 buf[1] = '\0';
1257 }
1258 return buf;
1259}
1260
1261bool wxSetWorkingDirectory(const wxString& d)
1262{
1263#ifdef __UNIX__
1264 return (chdir(d) == 0);
1265#elif defined(__WINDOWS__)
1266
1267#ifdef __WIN32__
1268 return (bool)(SetCurrentDirectory(d) != 0);
1269#else
1270 // Must change drive, too.
1271 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1272 if (isDriveSpec)
1273 {
1274 char firstChar = d[0];
1275
1276 // To upper case
1277 if (firstChar > 90)
1278 firstChar = firstChar - 32;
1279
1280 // To a drive number
1281 unsigned int driveNo = firstChar - 64;
1282 if (driveNo > 0)
1283 {
1284 unsigned int noDrives;
1285 _dos_setdrive(driveNo, &noDrives);
1286 }
1287 }
1288 bool success = (chdir(WXSTRINGCAST d) == 0);
1289
1290 return success;
1291#endif
1292
1293#endif
1294}
1295
1296bool wxEndsWithPathSeparator(const char *pszFileName)
1297{
1298 size_t len = Strlen(pszFileName);
1299 if ( len == 0 )
1300 return FALSE;
1301 else
1302 return wxIsPathSeparator(pszFileName[len - 1]);
1303}
1304
1305// find a file in a list of directories, returns false if not found
1306bool wxFindFileInPath(wxString *pStr, const char *pszPath, const char *pszFile)
1307{
1308 // we assume that it's not empty
1309 wxCHECK_MSG( !IsEmpty(pszFile), FALSE,
1310 _("empty file name in wxFindFileInPath"));
1311
1312 // skip path separator in the beginning of the file name if present
1313 if ( wxIsPathSeparator(*pszFile) )
1314 pszFile++;
1315
1316 // copy the path (strtok will modify it)
1317 char *szPath = new char[strlen(pszPath) + 1];
1318 strcpy(szPath, pszPath);
1319
1320 wxString strFile;
1321 char *pc;
1322 for ( pc = strtok(szPath, PATH_SEP); pc; pc = strtok((char *) NULL, PATH_SEP) ) {
1323 // search for the file in this directory
1324 strFile = pc;
1325 if ( !wxEndsWithPathSeparator(pc) )
1326 strFile += FILE_SEP_PATH;
1327 strFile += pszFile;
1328
1329 if ( FileExists(strFile) ) {
1330 *pStr = strFile;
1331 break;
1332 }
1333 }
1334
1335 delete [] szPath;
1336
1337 return pc != NULL; // if true => we breaked from the loop
1338}
1339
1340void WXDLLEXPORT wxSplitPath(const char *pszFileName,
1341 wxString *pstrPath,
1342 wxString *pstrName,
1343 wxString *pstrExt)
1344{
1345 wxCHECK_RET( pszFileName, _("NULL file name in wxSplitPath") );
1346
1347 const char *pDot = strrchr(pszFileName, FILE_SEP_EXT);
1348 const char *pSepUnix = strrchr(pszFileName, FILE_SEP_PATH_UNIX);
1349 const char *pSepDos = strrchr(pszFileName, FILE_SEP_PATH_DOS);
1350
1351 // take the last of the two
1352 size_t nPosUnix = pSepUnix ? pSepUnix - pszFileName : 0;
1353 size_t nPosDos = pSepDos ? pSepDos - pszFileName : 0;
1354 if ( nPosDos > nPosUnix )
1355 nPosUnix = nPosDos;
1356// size_t nLen = Strlen(pszFileName);
1357
1358 if ( pstrPath )
1359 *pstrPath = wxString(pszFileName, nPosUnix);
1360 if ( pDot ) {
1361 size_t nPosDot = pDot - pszFileName;
1362 if ( pstrName )
1363 *pstrName = wxString(pszFileName + nPosUnix + 1, nPosDot - nPosUnix);
1364 if ( pstrExt )
1365 *pstrExt = wxString(pszFileName + nPosDot + 1);
1366 }
1367 else {
1368 if ( pstrName )
1369 *pstrName = wxString(pszFileName + nPosUnix + 1);
1370 if ( pstrExt )
1371 pstrExt->Empty();
1372 }
1373}