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