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