]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
82b6636c6e3ed4d647727a94ce6fd167cfdad709
[wxWidgets.git] / src / common / filefn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: filefn.cpp
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "filefn.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26 #include "wx/defs.h"
27
28 #ifdef __BORLANDC__
29 #pragma hdrstop
30 #endif
31
32 #include "wx/utils.h"
33 #include "wx/intl.h"
34 #include "wx/file.h"
35 #include "wx/filename.h"
36 #include "wx/dir.h"
37
38 // there are just too many of those...
39 #ifdef __VISUALC__
40 #pragma warning(disable:4706) // assignment within conditional expression
41 #endif // VC++
42
43 #include <ctype.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #if !defined(__WATCOMC__)
48 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
49 #include <errno.h>
50 #endif
51 #endif
52
53 #if defined(__WXMAC__)
54 #include "wx/mac/private.h" // includes mac headers
55 #endif
56
57 #include <time.h>
58
59 #ifndef __MWERKS__
60 #include <sys/types.h>
61 #include <sys/stat.h>
62 #else
63 #include <stat.h>
64 #include <unistd.h>
65 #include <unix.h>
66 #endif
67
68 #ifdef __UNIX__
69 #include <unistd.h>
70 #include <dirent.h>
71 #include <fcntl.h>
72 #endif
73
74 #ifdef __WXPM__
75 #include <process.h>
76 #include "wx/os2/private.h"
77 #endif
78 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
79 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
80 #include <direct.h>
81 #include <dos.h>
82 #include <io.h>
83 #endif // __WINDOWS__
84 #endif // native Win compiler
85
86 #if defined(__DOS__)
87 #ifdef __WATCOMC__
88 #include <direct.h>
89 #include <dos.h>
90 #include <io.h>
91 #endif
92 #ifdef __DJGPP__
93 #include <unistd.h>
94 #endif
95 #endif
96
97 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
98 // this (3.1 I believe) and how to test for it.
99 // If this works for Borland 4.0 as well, then no worries.
100 #include <dir.h>
101 #endif
102
103 #ifdef __SALFORDC__
104 #include <dir.h>
105 #include <unix.h>
106 #endif
107
108 #include "wx/log.h"
109
110 // No, Cygwin doesn't appear to have fnmatch.h after all.
111 #if defined(HAVE_FNMATCH_H)
112 #include "fnmatch.h"
113 #endif
114
115 #ifdef __WINDOWS__
116 #include <windows.h>
117 #include "wx/msw/mslu.h"
118
119 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
120 //
121 // note that it must be included after <windows.h>
122 #ifdef __GNUWIN32__
123 #ifdef __CYGWIN__
124 #include <sys/cygwin.h>
125 #endif
126
127 #ifndef __TWIN32__
128 #include <sys/unistd.h>
129 #endif
130 #endif // __GNUWIN32__
131 #endif // __WINDOWS__
132
133 // TODO: Borland probably has _wgetcwd as well?
134 #ifdef _MSC_VER
135 #define HAVE_WGETCWD
136 #endif
137
138 // ----------------------------------------------------------------------------
139 // constants
140 // ----------------------------------------------------------------------------
141
142 #ifndef _MAXPATHLEN
143 #define _MAXPATHLEN 1024
144 #endif
145
146 #ifdef __WXMAC__
147 # ifdef __DARWIN__
148 # include "MoreFilesX.h"
149 # else
150 # include "MoreFiles.h"
151 # include "MoreFilesExtras.h"
152 # include "FullPath.h"
153 # include "FSpCompat.h"
154 # endif
155 #endif
156
157 // ----------------------------------------------------------------------------
158 // private globals
159 // ----------------------------------------------------------------------------
160
161 // MT-FIXME: get rid of this horror and all code using it
162 static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
163
164 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
165 //
166 // VisualAge C++ V4.0 cannot have any external linkage const decs
167 // in headers included by more than one primary source
168 //
169 const off_t wxInvalidOffset = (off_t)-1;
170 #endif
171
172 // ----------------------------------------------------------------------------
173 // macros
174 // ----------------------------------------------------------------------------
175
176 // we need to translate Mac filenames before passing them to OS functions
177 #define OS_FILENAME(s) (s.fn_str())
178
179 // ============================================================================
180 // implementation
181 // ============================================================================
182
183 #ifdef wxNEED_WX_UNISTD_H
184
185 WXDLLEXPORT int wxStat( const wxChar *file_name, wxStructStat *buf )
186 {
187 return stat( wxConvFile.cWX2MB( file_name ), buf );
188 }
189
190 WXDLLEXPORT int wxAccess( const wxChar *pathname, int mode )
191 {
192 return access( wxConvFile.cWX2MB( pathname ), mode );
193 }
194
195 WXDLLEXPORT int wxOpen( const wxChar *pathname, int flags, mode_t mode )
196 {
197 return open( wxConvFile.cWX2MB( pathname ), flags, mode );
198 }
199
200 #endif
201 // wxNEED_WX_UNISTD_H
202
203 // ----------------------------------------------------------------------------
204 // wxPathList
205 // ----------------------------------------------------------------------------
206
207 IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
208
209 void wxPathList::Add (const wxString& path)
210 {
211 wxStringList::Add (WXSTRINGCAST path);
212 }
213
214 // Add paths e.g. from the PATH environment variable
215 void wxPathList::AddEnvList (const wxString& envVariable)
216 {
217 static const wxChar PATH_TOKS[] =
218 #ifdef __WINDOWS__
219 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
220 #else
221 wxT(" :;");
222 #endif
223
224 wxChar *val = wxGetenv (WXSTRINGCAST envVariable);
225 if (val && *val)
226 {
227 wxChar *s = copystring (val);
228 wxChar *save_ptr, *token = wxStrtok (s, PATH_TOKS, &save_ptr);
229
230 if (token)
231 {
232 Add (copystring (token));
233 while (token)
234 {
235 if ((token = wxStrtok ((wxChar *) NULL, PATH_TOKS, &save_ptr)) != NULL)
236 Add (wxString(token));
237 }
238 }
239
240 // suppress warning about unused variable save_ptr when wxStrtok() is a
241 // macro which throws away its third argument
242 save_ptr = token;
243
244 delete [] s;
245 }
246 }
247
248 // Given a full filename (with path), ensure that that file can
249 // be accessed again USING FILENAME ONLY by adding the path
250 // to the list if not already there.
251 void wxPathList::EnsureFileAccessible (const wxString& path)
252 {
253 wxString path_only(wxPathOnly(path));
254 if ( !path_only.IsEmpty() )
255 {
256 if ( !Member(path_only) )
257 Add(path_only);
258 }
259 }
260
261 bool wxPathList::Member (const wxString& path)
262 {
263 for (wxNode * node = First (); node != NULL; node = node->Next ())
264 {
265 wxString path2((wxChar *) node->Data ());
266 if (
267 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
268 // Case INDEPENDENT
269 path.CompareTo (path2, wxString::ignoreCase) == 0
270 #else
271 // Case sensitive File System
272 path.CompareTo (path2) == 0
273 #endif
274 )
275 return TRUE;
276 }
277 return FALSE;
278 }
279
280 wxString wxPathList::FindValidPath (const wxString& file)
281 {
282 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer, file)))
283 return wxString(wxFileFunctionsBuffer);
284
285 wxChar buf[_MAXPATHLEN];
286 wxStrcpy(buf, wxFileFunctionsBuffer);
287
288 wxChar *filename = (wxChar*) NULL; /* shut up buggy egcs warning */
289 filename = wxIsAbsolutePath (buf) ? wxFileNameFromPath (buf) : (wxChar *)buf;
290
291 for (wxNode * node = First (); node; node = node->Next ())
292 {
293 wxChar *path = (wxChar *) node->Data ();
294 wxStrcpy (wxFileFunctionsBuffer, path);
295 wxChar ch = wxFileFunctionsBuffer[wxStrlen(wxFileFunctionsBuffer)-1];
296 if (ch != wxT('\\') && ch != wxT('/'))
297 wxStrcat (wxFileFunctionsBuffer, wxT("/"));
298 wxStrcat (wxFileFunctionsBuffer, filename);
299 #ifdef __WINDOWS__
300 wxUnix2DosFilename (wxFileFunctionsBuffer);
301 #endif
302 if (wxFileExists (wxFileFunctionsBuffer))
303 {
304 return wxString(wxFileFunctionsBuffer); // Found!
305 }
306 } // for()
307
308 return wxString(wxT("")); // Not found
309 }
310
311 wxString wxPathList::FindAbsoluteValidPath (const wxString& file)
312 {
313 wxString f = FindValidPath(file);
314 if ( wxIsAbsolutePath(f) )
315 return f;
316
317 wxString buf;
318 wxGetWorkingDirectory(wxStringBuffer(buf, _MAXPATHLEN), _MAXPATHLEN);
319
320 if ( !wxEndsWithPathSeparator(buf) )
321 {
322 buf += wxFILE_SEP_PATH;
323 }
324 buf += f;
325
326 return buf;
327 }
328
329 bool
330 wxFileExists (const wxString& filename)
331 {
332 // we must use GetFileAttributes() instead of the ANSI C functions because
333 // it can cope with network (UNC) paths unlike them
334 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
335 DWORD ret = ::GetFileAttributes(filename);
336
337 return (ret != (DWORD)-1) && !(ret & FILE_ATTRIBUTE_DIRECTORY);
338 #else // !__WIN32__
339 wxStructStat st;
340 return wxStat(filename, &st) == 0 && (st.st_mode & S_IFREG);
341 #endif // __WIN32__/!__WIN32__
342 }
343
344 bool
345 wxIsAbsolutePath (const wxString& filename)
346 {
347 if (filename != wxT(""))
348 {
349 #if defined(__WXMAC__) && !defined(__DARWIN__)
350 // Classic or Carbon CodeWarrior like
351 // Carbon with Apple DevTools is Unix like
352
353 // This seems wrong to me, but there is no fix. since
354 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
355 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
356 if (filename.Find(':') != wxNOT_FOUND && filename[0] != ':')
357 return TRUE ;
358 #else
359 // Unix like or Windows
360 if (filename[0] == wxT('/'))
361 return TRUE;
362 #endif
363 #ifdef __VMS__
364 if ((filename[0] == wxT('[') && filename[1] != wxT('.')))
365 return TRUE;
366 #endif
367 #ifdef __WINDOWS__
368 // MSDOS like
369 if (filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':')))
370 return TRUE;
371 #endif
372 }
373 return FALSE ;
374 }
375
376 /*
377 * Strip off any extension (dot something) from end of file,
378 * IF one exists. Inserts zero into buffer.
379 *
380 */
381
382 void wxStripExtension(wxChar *buffer)
383 {
384 int len = wxStrlen(buffer);
385 int i = len-1;
386 while (i > 0)
387 {
388 if (buffer[i] == wxT('.'))
389 {
390 buffer[i] = 0;
391 break;
392 }
393 i --;
394 }
395 }
396
397 void wxStripExtension(wxString& buffer)
398 {
399 size_t len = buffer.Length();
400 size_t i = len-1;
401 while (i > 0)
402 {
403 if (buffer.GetChar(i) == wxT('.'))
404 {
405 buffer = buffer.Left(i);
406 break;
407 }
408 i --;
409 }
410 }
411
412 // Destructive removal of /./ and /../ stuff
413 wxChar *wxRealPath (wxChar *path)
414 {
415 #ifdef __WXMSW__
416 static const wxChar SEP = wxT('\\');
417 wxUnix2DosFilename(path);
418 #else
419 static const wxChar SEP = wxT('/');
420 #endif
421 if (path[0] && path[1]) {
422 /* MATTHEW: special case "/./x" */
423 wxChar *p;
424 if (path[2] == SEP && path[1] == wxT('.'))
425 p = &path[0];
426 else
427 p = &path[2];
428 for (; *p; p++)
429 {
430 if (*p == SEP)
431 {
432 if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
433 {
434 wxChar *q;
435 for (q = p - 1; q >= path && *q != SEP; q--)
436 {
437 // Empty
438 }
439
440 if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
441 && (q - 1 <= path || q[-1] != SEP))
442 {
443 wxStrcpy (q, p + 3);
444 if (path[0] == wxT('\0'))
445 {
446 path[0] = SEP;
447 path[1] = wxT('\0');
448 }
449 #ifdef __WXMSW__
450 /* Check that path[2] is NULL! */
451 else if (path[1] == wxT(':') && !path[2])
452 {
453 path[2] = SEP;
454 path[3] = wxT('\0');
455 }
456 #endif
457 p = q - 1;
458 }
459 }
460 else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
461 wxStrcpy (p, p + 2);
462 }
463 }
464 }
465 return path;
466 }
467
468 // Must be destroyed
469 wxChar *wxCopyAbsolutePath(const wxString& filename)
470 {
471 if (filename == wxT(""))
472 return (wxChar *) NULL;
473
474 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename))) {
475 wxChar buf[_MAXPATHLEN];
476 buf[0] = wxT('\0');
477 wxGetWorkingDirectory(buf, WXSIZEOF(buf));
478 wxChar ch = buf[wxStrlen(buf) - 1];
479 #ifdef __WXMSW__
480 if (ch != wxT('\\') && ch != wxT('/'))
481 wxStrcat(buf, wxT("\\"));
482 #else
483 if (ch != wxT('/'))
484 wxStrcat(buf, wxT("/"));
485 #endif
486 wxStrcat(buf, wxFileFunctionsBuffer);
487 return copystring( wxRealPath(buf) );
488 }
489 return copystring( wxFileFunctionsBuffer );
490 }
491
492 /*-
493 Handles:
494 ~/ => home dir
495 ~user/ => user's home dir
496 If the environment variable a = "foo" and b = "bar" then:
497 Unix:
498 $a => foo
499 $a$b => foobar
500 $a.c => foo.c
501 xxx$a => xxxfoo
502 ${a}! => foo!
503 $(b)! => bar!
504 \$a => \$a
505 MSDOS:
506 $a ==> $a
507 $(a) ==> foo
508 $(a)$b ==> foo$b
509 $(a)$(b)==> foobar
510 test.$$ ==> test.$$
511 */
512
513 /* input name in name, pathname output to buf. */
514
515 wxChar *wxExpandPath(wxChar *buf, const wxChar *name)
516 {
517 register wxChar *d, *s, *nm;
518 wxChar lnm[_MAXPATHLEN];
519 int q;
520
521 // Some compilers don't like this line.
522 // const wxChar trimchars[] = wxT("\n \t");
523
524 wxChar trimchars[4];
525 trimchars[0] = wxT('\n');
526 trimchars[1] = wxT(' ');
527 trimchars[2] = wxT('\t');
528 trimchars[3] = 0;
529
530 #ifdef __WXMSW__
531 const wxChar SEP = wxT('\\');
532 #else
533 const wxChar SEP = wxT('/');
534 #endif
535 buf[0] = wxT('\0');
536 if (name == NULL || *name == wxT('\0'))
537 return buf;
538 nm = copystring(name); // Make a scratch copy
539 wxChar *nm_tmp = nm;
540
541 /* Skip leading whitespace and cr */
542 while (wxStrchr((wxChar *)trimchars, *nm) != NULL)
543 nm++;
544 /* And strip off trailing whitespace and cr */
545 s = nm + (q = wxStrlen(nm)) - 1;
546 while (q-- && wxStrchr((wxChar *)trimchars, *s) != NULL)
547 *s = wxT('\0');
548
549 s = nm;
550 d = lnm;
551 #ifdef __WXMSW__
552 q = FALSE;
553 #else
554 q = nm[0] == wxT('\\') && nm[1] == wxT('~');
555 #endif
556
557 /* Expand inline environment variables */
558 #ifdef __VISAGECPP__
559 while (*d)
560 {
561 *d++ = *s;
562 if(*s == wxT('\\'))
563 {
564 *(d - 1) = *++s;
565 if (*d)
566 {
567 s++;
568 continue;
569 }
570 else
571 break;
572 }
573 else
574 #else
575 while ((*d++ = *s) != 0) {
576 # ifndef __WXMSW__
577 if (*s == wxT('\\')) {
578 if ((*(d - 1) = *++s)) {
579 s++;
580 continue;
581 } else
582 break;
583 } else
584 # endif
585 #endif
586 #ifdef __WXMSW__
587 if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
588 #else
589 if (*s++ == wxT('$'))
590 #endif
591 {
592 register wxChar *start = d;
593 register int braces = (*s == wxT('{') || *s == wxT('('));
594 register wxChar *value;
595 while ((*d++ = *s) != 0)
596 if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
597 break;
598 else
599 s++;
600 *--d = 0;
601 value = wxGetenv(braces ? start + 1 : start);
602 if (value) {
603 for ((d = start - 1); (*d++ = *value++) != 0;)
604 {
605 // Empty
606 }
607
608 d--;
609 if (braces && *s)
610 s++;
611 }
612 }
613 }
614
615 /* Expand ~ and ~user */
616 nm = lnm;
617 if (nm[0] == wxT('~') && !q)
618 {
619 /* prefix ~ */
620 if (nm[1] == SEP || nm[1] == 0)
621 { /* ~/filename */
622 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
623 if ((s = WXSTRINGCAST wxGetUserHome(wxT(""))) != NULL) {
624 if (*++nm)
625 nm++;
626 }
627 } else
628 { /* ~user/filename */
629 register wxChar *nnm;
630 register wxChar *home;
631 for (s = nm; *s && *s != SEP; s++)
632 {
633 // Empty
634 }
635 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
636 was_sep = (*s == SEP);
637 nnm = *s ? s + 1 : s;
638 *s = 0;
639 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
640 if ((home = WXSTRINGCAST wxGetUserHome(wxString(nm + 1))) == NULL) {
641 if (was_sep) /* replace only if it was there: */
642 *s = SEP;
643 s = NULL;
644 } else {
645 nm = nnm;
646 s = home;
647 }
648 }
649 }
650
651 d = buf;
652 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
653 /* Copy home dir */
654 while (wxT('\0') != (*d++ = *s++))
655 /* loop */;
656 // Handle root home
657 if (d - 1 > buf && *(d - 2) != SEP)
658 *(d - 1) = SEP;
659 }
660 s = nm;
661 while ((*d++ = *s++) != 0)
662 {
663 // Empty
664 }
665 delete[] nm_tmp; // clean up alloc
666 /* Now clean up the buffer */
667 return wxRealPath(buf);
668 }
669
670 /* Contract Paths to be build upon an environment variable
671 component:
672
673 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
674
675 The call wxExpandPath can convert these back!
676 */
677 wxChar *
678 wxContractPath (const wxString& filename, const wxString& envname, const wxString& user)
679 {
680 static wxChar dest[_MAXPATHLEN];
681
682 if (filename == wxT(""))
683 return (wxChar *) NULL;
684
685 wxStrcpy (dest, WXSTRINGCAST filename);
686 #ifdef __WXMSW__
687 wxUnix2DosFilename(dest);
688 #endif
689
690 // Handle environment
691 const wxChar *val = (const wxChar *) NULL;
692 wxChar *tcp = (wxChar *) NULL;
693 if (envname != WXSTRINGCAST NULL && (val = wxGetenv (WXSTRINGCAST envname)) != NULL &&
694 (tcp = wxStrstr (dest, val)) != NULL)
695 {
696 wxStrcpy (wxFileFunctionsBuffer, tcp + wxStrlen (val));
697 *tcp++ = wxT('$');
698 *tcp++ = wxT('{');
699 wxStrcpy (tcp, WXSTRINGCAST envname);
700 wxStrcat (tcp, wxT("}"));
701 wxStrcat (tcp, wxFileFunctionsBuffer);
702 }
703
704 // Handle User's home (ignore root homes!)
705 size_t len = 0;
706 if ((val = wxGetUserHome (user)) != NULL &&
707 (len = wxStrlen(val)) > 2 &&
708 wxStrncmp(dest, val, len) == 0)
709 {
710 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
711 if (user != wxT(""))
712 wxStrcat(wxFileFunctionsBuffer, (const wxChar*) user);
713 wxStrcat(wxFileFunctionsBuffer, dest + len);
714 wxStrcpy (dest, wxFileFunctionsBuffer);
715 }
716
717 return dest;
718 }
719
720 // Return just the filename, not the path (basename)
721 wxChar *wxFileNameFromPath (wxChar *path)
722 {
723 wxString p = path;
724 wxString n = wxFileNameFromPath(p);
725
726 return path + p.length() - n.length();
727 }
728
729 wxString wxFileNameFromPath (const wxString& path)
730 {
731 wxString name, ext;
732 wxFileName::SplitPath(path, NULL, &name, &ext);
733
734 wxString fullname = name;
735 if ( !ext.empty() )
736 {
737 fullname << wxFILE_SEP_EXT << ext;
738 }
739
740 return fullname;
741 }
742
743 // Return just the directory, or NULL if no directory
744 wxChar *
745 wxPathOnly (wxChar *path)
746 {
747 if (path && *path)
748 {
749 static wxChar buf[_MAXPATHLEN];
750
751 // Local copy
752 wxStrcpy (buf, path);
753
754 int l = wxStrlen(path);
755 int i = l - 1;
756
757 // Search backward for a backward or forward slash
758 while (i > -1)
759 {
760 #if defined(__WXMAC__) && !defined(__DARWIN__)
761 // Classic or Carbon CodeWarrior like
762 // Carbon with Apple DevTools is Unix like
763 if (path[i] == wxT(':') )
764 {
765 buf[i] = 0;
766 return buf;
767 }
768 #else
769 // Unix like or Windows
770 if (path[i] == wxT('/') || path[i] == wxT('\\'))
771 {
772 buf[i] = 0;
773 return buf;
774 }
775 #endif
776 #ifdef __VMS__
777 if (path[i] == wxT(']'))
778 {
779 buf[i+1] = 0;
780 return buf;
781 }
782 #endif
783 i --;
784 }
785
786 #if defined(__WXMSW__) || defined(__WXPM__)
787 // Try Drive specifier
788 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
789 {
790 // A:junk --> A:. (since A:.\junk Not A:\junk)
791 buf[2] = wxT('.');
792 buf[3] = wxT('\0');
793 return buf;
794 }
795 #endif
796 }
797 return (wxChar *) NULL;
798 }
799
800 // Return just the directory, or NULL if no directory
801 wxString wxPathOnly (const wxString& path)
802 {
803 if (path != wxT(""))
804 {
805 wxChar buf[_MAXPATHLEN];
806
807 // Local copy
808 wxStrcpy (buf, WXSTRINGCAST path);
809
810 int l = path.Length();
811 int i = l - 1;
812
813 // Search backward for a backward or forward slash
814 while (i > -1)
815 {
816 #if defined(__WXMAC__) && !defined(__DARWIN__)
817 // Classic or Carbon CodeWarrior like
818 // Carbon with Apple DevTools is Unix like
819 if (path[i] == wxT(':') )
820 {
821 buf[i] = 0;
822 return wxString(buf);
823 }
824 #else
825 // Unix like or Windows
826 if (path[i] == wxT('/') || path[i] == wxT('\\'))
827 {
828 buf[i] = 0;
829 return wxString(buf);
830 }
831 #endif
832 #ifdef __VMS__
833 if (path[i] == wxT(']'))
834 {
835 buf[i+1] = 0;
836 return wxString(buf);
837 }
838 #endif
839 i --;
840 }
841
842 #if defined(__WXMSW__) || defined(__WXPM__)
843 // Try Drive specifier
844 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
845 {
846 // A:junk --> A:. (since A:.\junk Not A:\junk)
847 buf[2] = wxT('.');
848 buf[3] = wxT('\0');
849 return wxString(buf);
850 }
851 #endif
852 }
853 return wxString(wxT(""));
854 }
855
856 // Utility for converting delimiters in DOS filenames to UNIX style
857 // and back again - or we get nasty problems with delimiters.
858 // Also, convert to lower case, since case is significant in UNIX.
859
860 #if defined(__WXMAC__)
861 wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
862 {
863 #ifdef __DARWIN__
864 int i;
865 int j;
866 OSErr theErr;
867 OSStatus theStatus;
868 Boolean isDirectory = false;
869 Str255 theParentPath = "\p";
870 FSSpec theParentSpec;
871 FSRef theParentRef;
872 char theFileName[FILENAME_MAX];
873 char thePath[FILENAME_MAX];
874
875 strcpy(thePath, "");
876
877 // GD: Separate file name from path and make a FSRef to the parent
878 // directory. This is necessary since FSRefs cannot reference files
879 // that have not yet been created.
880 // Based on example code from Apple Technical Note TN2022
881 // http://developer.apple.com/technotes/tn/tn2022.html
882
883 // check whether we are converting a directory
884 isDirectory = ((spec->name)[spec->name[0]] == ':');
885 // count length of file name
886 for (i = spec->name[0] - (isDirectory ? 1 : 0); ((spec->name[i] != ':') && (i > 0)); i--);
887 // copy file name
888 // prepend path separator since it will later be appended to the path
889 theFileName[0] = wxFILE_SEP_PATH;
890 for (j = i + 1; j <= spec->name[0] - (isDirectory ? 1 : 0); j++) {
891 theFileName[j - i] = spec->name[j];
892 }
893 theFileName[j - i] = '\0';
894 // copy path if any
895 for (j = 1; j <= i; j++) {
896 theParentPath[++theParentPath[0]] = spec->name[j];
897 }
898 theErr = FSMakeFSSpec(spec->vRefNum, spec->parID, theParentPath, &theParentSpec);
899 if (theErr == noErr) {
900 // convert the FSSpec to an FSRef
901 theErr = FSpMakeFSRef(&theParentSpec, &theParentRef);
902 }
903 if (theErr == noErr) {
904 // get the POSIX path associated with the FSRef
905 theStatus = FSRefMakePath(&theParentRef,
906 (UInt8 *)thePath, sizeof(thePath));
907 }
908 if (theStatus == noErr) {
909 // append file name to path
910 // includes previously prepended path separator
911 strcat(thePath, theFileName);
912 }
913
914 // create path string for return value
915 wxString result( thePath ) ;
916 #else
917 Handle myPath ;
918 short length ;
919
920 // get length of path and allocate handle
921 FSpGetFullPath( spec , &length , &myPath ) ;
922 ::SetHandleSize( myPath , length + 1 ) ;
923 ::HLock( myPath ) ;
924 (*myPath)[length] = 0 ;
925 if ((length > 0) && ((*myPath)[length-1] == ':'))
926 (*myPath)[length-1] = 0 ;
927
928 // create path string for return value
929 wxString result( (char*) *myPath ) ;
930
931 // free allocated handle
932 ::HUnlock( myPath ) ;
933 ::DisposeHandle( myPath ) ;
934 #endif
935
936 return result ;
937 }
938 #ifndef __DARWIN__
939 // Mac file names are POSIX (Unix style) under Darwin
940 // therefore the conversion functions below are not needed
941
942 static char sMacFileNameConversion[ 1000 ] ;
943
944 #endif
945 void wxMacFilename2FSSpec( const char *path , FSSpec *spec )
946 {
947 OSStatus err = noErr ;
948 #ifdef __DARWIN__
949 FSRef theRef;
950
951 // get the FSRef associated with the POSIX path
952 err = FSPathMakeRef((const UInt8 *) path, &theRef, NULL);
953 // convert the FSRef to an FSSpec
954 err = FSGetCatalogInfo(&theRef, kFSCatInfoNone, NULL, NULL, spec, NULL);
955 #else
956 if ( strchr( path , ':' ) == NULL )
957 {
958 // try whether it is a volume / or a mounted volume
959 strncpy( sMacFileNameConversion , path , 1000 ) ;
960 sMacFileNameConversion[998] = 0 ;
961 strcat( sMacFileNameConversion , ":" ) ;
962 err = FSpLocationFromFullPath( strlen(sMacFileNameConversion) , sMacFileNameConversion , spec ) ;
963 }
964 else
965 {
966 err = FSpLocationFromFullPath( strlen(path) , path , spec ) ;
967 }
968 #endif
969 }
970
971 #ifndef __DARWIN__
972
973 wxString wxMac2UnixFilename (const char *str)
974 {
975 char *s = sMacFileNameConversion ;
976 strcpy( s , str ) ;
977 if (s)
978 {
979 memmove( s+1 , s ,strlen( s ) + 1) ;
980 if ( *s == ':' )
981 *s = '.' ;
982 else
983 *s = '/' ;
984
985 while (*s)
986 {
987 if (*s == ':')
988 *s = '/';
989 else
990 *s = wxTolower(*s); // Case INDEPENDENT
991 s++;
992 }
993 }
994 return wxString(sMacFileNameConversion) ;
995 }
996
997 wxString wxUnix2MacFilename (const char *str)
998 {
999 char *s = sMacFileNameConversion ;
1000 strcpy( s , str ) ;
1001 if (s)
1002 {
1003 if ( *s == '.' )
1004 {
1005 // relative path , since it goes on with slash which is translated to a :
1006 memmove( s , s+1 ,strlen( s ) ) ;
1007 }
1008 else if ( *s == '/' )
1009 {
1010 // absolute path -> on mac just start with the drive name
1011 memmove( s , s+1 ,strlen( s ) ) ;
1012 }
1013 else
1014 {
1015 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
1016 }
1017 while (*s)
1018 {
1019 if (*s == '/' || *s == '\\')
1020 {
1021 // convert any back-directory situations
1022 if ( *(s+1) == '.' && *(s+2) == '.' && ( (*(s+3) == '/' || *(s+3) == '\\') ) )
1023 {
1024 *s = ':';
1025 memmove( s+1 , s+3 ,strlen( s+3 ) + 1 ) ;
1026 }
1027 else
1028 *s = ':';
1029 }
1030 s++ ;
1031 }
1032 }
1033 return wxString (sMacFileNameConversion) ;
1034 }
1035
1036 wxString wxMacFSSpec2UnixFilename( const FSSpec *spec )
1037 {
1038 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec) ) ;
1039 }
1040
1041 void wxUnixFilename2FSSpec( const char *path , FSSpec *spec )
1042 {
1043 wxString var = wxUnix2MacFilename( path ) ;
1044 wxMacFilename2FSSpec( var , spec ) ;
1045 }
1046 #endif // ! __DARWIN__
1047
1048 #endif // __WXMAC__
1049
1050 void
1051 wxDos2UnixFilename (char *s)
1052 {
1053 if (s)
1054 while (*s)
1055 {
1056 if (*s == '\\')
1057 *s = '/';
1058 #ifdef __WXMSW__
1059 else
1060 *s = wxTolower (*s); // Case INDEPENDENT
1061 #endif
1062 s++;
1063 }
1064 }
1065
1066 void
1067 #if defined(__WXMSW__) || defined(__WXPM__)
1068 wxUnix2DosFilename (wxChar *s)
1069 #else
1070 wxUnix2DosFilename (wxChar *WXUNUSED(s) )
1071 #endif
1072 {
1073 // Yes, I really mean this to happen under DOS only! JACS
1074 #if defined(__WXMSW__) || defined(__WXPM__)
1075 if (s)
1076 while (*s)
1077 {
1078 if (*s == wxT('/'))
1079 *s = wxT('\\');
1080 s++;
1081 }
1082 #endif
1083 }
1084
1085 // Concatenate two files to form third
1086 bool
1087 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
1088 {
1089 wxString outfile;
1090 if ( !wxGetTempFileName( wxT("cat"), outfile) )
1091 return FALSE;
1092
1093 FILE *fp1 = (FILE *) NULL;
1094 FILE *fp2 = (FILE *) NULL;
1095 FILE *fp3 = (FILE *) NULL;
1096 // Open the inputs and outputs
1097 if ((fp1 = wxFopen ( file1, wxT("rb"))) == NULL ||
1098 (fp2 = wxFopen ( file2, wxT("rb"))) == NULL ||
1099 (fp3 = wxFopen ( outfile, wxT("wb"))) == NULL)
1100 {
1101 if (fp1)
1102 fclose (fp1);
1103 if (fp2)
1104 fclose (fp2);
1105 if (fp3)
1106 fclose (fp3);
1107 return FALSE;
1108 }
1109
1110 int ch;
1111 while ((ch = getc (fp1)) != EOF)
1112 (void) putc (ch, fp3);
1113 fclose (fp1);
1114
1115 while ((ch = getc (fp2)) != EOF)
1116 (void) putc (ch, fp3);
1117 fclose (fp2);
1118
1119 fclose (fp3);
1120 bool result = wxRenameFile(outfile, file3);
1121 return result;
1122 }
1123
1124 // Copy files
1125 bool
1126 wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
1127 {
1128 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1129 // CopyFile() copies file attributes and modification time too, so use it
1130 // instead of our code if available
1131 //
1132 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1133 if ( !::CopyFile(file1, file2, !overwrite) )
1134 {
1135 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1136 file1.c_str(), file2.c_str());
1137
1138 return FALSE;
1139 }
1140 #elif defined(__WXPM__)
1141 if ( ::DosCopy(file2, file2, overwrite ? DCPY_EXISTING : 0) != 0 )
1142 return FALSE;
1143 #else // !Win32
1144
1145 wxStructStat fbuf;
1146 // get permissions of file1
1147 if ( wxStat( file1.c_str(), &fbuf) != 0 )
1148 {
1149 // the file probably doesn't exist or we haven't the rights to read
1150 // from it anyhow
1151 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1152 file1.c_str());
1153 return FALSE;
1154 }
1155
1156 // open file1 for reading
1157 wxFile fileIn(file1, wxFile::read);
1158 if ( !fileIn.IsOpened() )
1159 return FALSE;
1160
1161 // remove file2, if it exists. This is needed for creating
1162 // file2 with the correct permissions in the next step
1163 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
1164 {
1165 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1166 file2.c_str());
1167 return FALSE;
1168 }
1169
1170 #ifdef __UNIX__
1171 // reset the umask as we want to create the file with exactly the same
1172 // permissions as the original one
1173 mode_t oldUmask = umask( 0 );
1174 #endif // __UNIX__
1175
1176 // create file2 with the same permissions than file1 and open it for
1177 // writing
1178
1179 wxFile fileOut;
1180 if ( !fileOut.Create(file2, overwrite, fbuf.st_mode & 0777) )
1181 return FALSE;
1182
1183 #ifdef __UNIX__
1184 /// restore the old umask
1185 umask(oldUmask);
1186 #endif // __UNIX__
1187
1188 // copy contents of file1 to file2
1189 char buf[4096];
1190 size_t count;
1191 for ( ;; )
1192 {
1193 count = fileIn.Read(buf, WXSIZEOF(buf));
1194 if ( fileIn.Error() )
1195 return FALSE;
1196
1197 // end of file?
1198 if ( !count )
1199 break;
1200
1201 if ( fileOut.Write(buf, count) < count )
1202 return FALSE;
1203 }
1204
1205 // we can expect fileIn to be closed successfully, but we should ensure
1206 // that fileOut was closed as some write errors (disk full) might not be
1207 // detected before doing this
1208 if ( !fileIn.Close() || !fileOut.Close() )
1209 return FALSE;
1210
1211 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1212 // no chmod in VA. Should be some permission API for HPFS386 partitions
1213 // however
1214 if ( chmod(OS_FILENAME(file2), fbuf.st_mode) != 0 )
1215 {
1216 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1217 file2.c_str());
1218 return FALSE;
1219 }
1220 #endif // OS/2 || Mac
1221 #endif // __WXMSW__ && __WIN32__
1222
1223 return TRUE;
1224 }
1225
1226 bool
1227 wxRenameFile (const wxString& file1, const wxString& file2)
1228 {
1229 // Normal system call
1230 if ( wxRename (file1, file2) == 0 )
1231 return TRUE;
1232
1233 // Try to copy
1234 if (wxCopyFile(file1, file2)) {
1235 wxRemoveFile(file1);
1236 return TRUE;
1237 }
1238 // Give up
1239 return FALSE;
1240 }
1241
1242 bool wxRemoveFile(const wxString& file)
1243 {
1244 #if defined(__VISUALC__) \
1245 || defined(__BORLANDC__) \
1246 || defined(__WATCOMC__) \
1247 || defined(__GNUWIN32__)
1248 int res = wxRemove(file);
1249 #else
1250 int res = unlink(OS_FILENAME(file));
1251 #endif
1252
1253 return res == 0;
1254 }
1255
1256 bool wxMkdir(const wxString& dir, int perm)
1257 {
1258 #if defined(__WXMAC__) && !defined(__UNIX__)
1259 return (mkdir( dir , 0 ) == 0);
1260 #else // !Mac
1261 const wxChar *dirname = dir.c_str();
1262
1263 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1264 // for the GNU compiler
1265 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1266 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1267 #elif defined(__WXPM__)
1268 if (::DosCreateDir((PSZ)dirname, NULL) != 0) // enhance for EAB's??
1269 #elif defined(__DOS__)
1270 #if defined(__WATCOMC__)
1271 (void)perm;
1272 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1273 #elif defined(__DJGPP__)
1274 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1275 #else
1276 #error "Unsupported DOS compiler!"
1277 #endif
1278 #else // !MSW, !DOS and !OS/2 VAC++
1279 (void)perm;
1280 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1281 #endif // !MSW/MSW
1282 {
1283 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1284
1285 return FALSE;
1286 }
1287
1288 return TRUE;
1289 #endif // Mac/!Mac
1290 }
1291
1292 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1293 {
1294 #ifdef __VMS__
1295 return FALSE; //to be changed since rmdir exists in VMS7.x
1296 #elif defined(__WXPM__)
1297 return (::DosDeleteDir((PSZ)dir.c_str()) == 0);
1298 #else
1299
1300 #ifdef __SALFORDC__
1301 return FALSE; // What to do?
1302 #else
1303 return (wxRmDir(OS_FILENAME(dir)) == 0);
1304 #endif
1305
1306 #endif
1307 }
1308
1309 // does the path exists? (may have or not '/' or '\\' at the end)
1310 bool wxPathExists(const wxChar *pszPathName)
1311 {
1312 wxString strPath(pszPathName);
1313
1314 #ifdef __WINDOWS__
1315 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1316 // so remove all trailing backslashes from the path - but don't do this for
1317 // the pathes "d:\" (which are different from "d:") nor for just "\"
1318 while ( wxEndsWithPathSeparator(strPath) )
1319 {
1320 size_t len = strPath.length();
1321 if ( len == 1 || (len == 3 && strPath[len - 2] == _T(':')) )
1322 break;
1323
1324 strPath.Truncate(len - 1);
1325 }
1326 #endif // __WINDOWS__
1327
1328 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1329 // stat() can't cope with network paths
1330 DWORD ret = ::GetFileAttributes(strPath);
1331
1332 return (ret != (DWORD)-1) && (ret & FILE_ATTRIBUTE_DIRECTORY);
1333 #else // !__WIN32__
1334
1335 wxStructStat st;
1336 #ifndef __VISAGECPP__
1337 return wxStat(pszPathName, &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR);
1338 #else
1339 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1340 return wxStat(pszPathName, &st) == 0 && (st.st_mode == S_IFDIR);
1341 #endif
1342
1343 #endif // __WIN32__/!__WIN32__
1344 }
1345
1346 // Get a temporary filename, opening and closing the file.
1347 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1348 {
1349 wxString filename = wxFileName::CreateTempFileName(prefix);
1350 if ( filename.empty() )
1351 return NULL;
1352
1353 if ( buf )
1354 wxStrcpy(buf, filename);
1355 else
1356 buf = copystring(filename);
1357
1358 return buf;
1359 }
1360
1361 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1362 {
1363 buf = wxFileName::CreateTempFileName(prefix);
1364
1365 return !buf.empty();
1366 }
1367
1368 // Get first file name matching given wild card.
1369
1370 static wxDir *gs_dir = NULL;
1371 static wxString gs_dirPath;
1372
1373 wxString wxFindFirstFile(const wxChar *spec, int flags)
1374 {
1375 wxSplitPath(spec, &gs_dirPath, NULL, NULL);
1376 if ( gs_dirPath.IsEmpty() )
1377 gs_dirPath = wxT(".");
1378 if ( gs_dirPath.Last() != wxFILE_SEP_PATH )
1379 gs_dirPath << wxFILE_SEP_PATH;
1380
1381 if (gs_dir)
1382 delete gs_dir;
1383 gs_dir = new wxDir(gs_dirPath);
1384
1385 if ( !gs_dir->IsOpened() )
1386 {
1387 wxLogSysError(_("Can not enumerate files '%s'"), spec);
1388 return wxEmptyString;
1389 }
1390
1391 int dirFlags = 0;
1392 switch (flags)
1393 {
1394 case wxDIR: dirFlags = wxDIR_DIRS; break;
1395 case wxFILE: dirFlags = wxDIR_FILES; break;
1396 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1397 }
1398
1399 wxString result;
1400 gs_dir->GetFirst(&result, wxFileNameFromPath(wxString(spec)), dirFlags);
1401 if ( result.IsEmpty() )
1402 {
1403 wxDELETE(gs_dir);
1404 return result;
1405 }
1406
1407 return gs_dirPath + result;
1408 }
1409
1410 wxString wxFindNextFile()
1411 {
1412 wxASSERT_MSG( gs_dir, wxT("You must call wxFindFirstFile before!") );
1413
1414 wxString result;
1415 gs_dir->GetNext(&result);
1416
1417 if ( result.IsEmpty() )
1418 {
1419 wxDELETE(gs_dir);
1420 return result;
1421 }
1422
1423 return gs_dirPath + result;
1424 }
1425
1426
1427 // Get current working directory.
1428 // If buf is NULL, allocates space using new, else
1429 // copies into buf.
1430 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1431 {
1432 if ( !buf )
1433 {
1434 buf = new wxChar[sz + 1];
1435 }
1436
1437 bool ok = FALSE;
1438
1439 // for the compilers which have Unicode version of _getcwd(), call it
1440 // directly, for the others call the ANSI version and do the translation
1441 #if !wxUSE_UNICODE
1442 #define cbuf buf
1443 #else // wxUSE_UNICODE
1444 bool needsANSI = TRUE;
1445
1446 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1447 // This is not legal code as the compiler
1448 // is allowed destroy the wxCharBuffer.
1449 // wxCharBuffer c_buffer(sz);
1450 // char *cbuf = (char*)(const char*)c_buffer;
1451 char cbuf[_MAXPATHLEN];
1452 #endif
1453
1454 #ifdef HAVE_WGETCWD
1455 #if wxUSE_UNICODE_MSLU
1456 if ( wxGetOsVersion() != wxWIN95 )
1457 #else
1458 char *cbuf = NULL; // never really used because needsANSI will always be FALSE
1459 #endif
1460 {
1461 ok = _wgetcwd(buf, sz) != NULL;
1462 needsANSI = FALSE;
1463 }
1464 #endif
1465
1466 if ( needsANSI )
1467 #endif // wxUSE_UNICODE
1468 {
1469 #ifdef _MSC_VER
1470 ok = _getcwd(cbuf, sz) != NULL;
1471 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1472 FSSpec cwdSpec ;
1473 FCBPBRec pb;
1474 OSErr error;
1475 Str255 fileName ;
1476 pb.ioNamePtr = (StringPtr) &fileName;
1477 pb.ioVRefNum = 0;
1478 pb.ioRefNum = LMGetCurApRefNum();
1479 pb.ioFCBIndx = 0;
1480 error = PBGetFCBInfoSync(&pb);
1481 if ( error == noErr )
1482 {
1483 cwdSpec.vRefNum = pb.ioFCBVRefNum;
1484 cwdSpec.parID = pb.ioFCBParID;
1485 cwdSpec.name[0] = 0 ;
1486 wxString res = wxMacFSSpec2MacFilename( &cwdSpec ) ;
1487
1488 strcpy( cbuf , res ) ;
1489 cbuf[res.length()]=0 ;
1490
1491 ok = TRUE;
1492 }
1493 else
1494 {
1495 ok = FALSE;
1496 }
1497 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1498 APIRET rc;
1499 rc = ::DosQueryCurrentDir( 0 // current drive
1500 ,cbuf
1501 ,(PULONG)&sz
1502 );
1503 ok = rc != 0;
1504 #else // !Win32/VC++ !Mac !OS2
1505 ok = getcwd(cbuf, sz) != NULL;
1506 #endif // platform
1507
1508 #if wxUSE_UNICODE
1509 // finally convert the result to Unicode if needed
1510 wxConvFile.MB2WC(buf, cbuf, sz);
1511 #endif // wxUSE_UNICODE
1512 }
1513
1514 if ( !ok )
1515 {
1516 wxLogSysError(_("Failed to get the working directory"));
1517
1518 // VZ: the old code used to return "." on error which didn't make any
1519 // sense at all to me - empty string is a better error indicator
1520 // (NULL might be even better but I'm afraid this could lead to
1521 // problems with the old code assuming the return is never NULL)
1522 buf[0] = _T('\0');
1523 }
1524 else // ok, but we might need to massage the path into the right format
1525 {
1526 #ifdef __DJGPP__
1527 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1528 // with / deliminers. We don't like that.
1529 for (wxChar *ch = buf; *ch; ch++)
1530 {
1531 if (*ch == wxT('/'))
1532 *ch = wxT('\\');
1533 }
1534 #endif // __DJGPP__
1535
1536 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1537 // he needs Unix as opposed to Win32 pathnames
1538 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1539 // another example of DOS/Unix mix (Cygwin)
1540 wxString pathUnix = buf;
1541 cygwin_conv_to_full_win32_path(pathUnix, buf);
1542 #endif // __CYGWIN__
1543 }
1544
1545 return buf;
1546
1547 #if !wxUSE_UNICODE
1548 #undef cbuf
1549 #endif
1550 }
1551
1552 wxString wxGetCwd()
1553 {
1554 wxChar *buffer = new wxChar[_MAXPATHLEN];
1555 wxGetWorkingDirectory(buffer, _MAXPATHLEN);
1556 wxString str( buffer );
1557 delete [] buffer;
1558
1559 return str;
1560 }
1561
1562 bool wxSetWorkingDirectory(const wxString& d)
1563 {
1564 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1565 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1566 #elif defined(__WXPM__)
1567 return (::DosSetCurrentDir((PSZ)d.c_str()) == 0);
1568 #elif defined(__WINDOWS__)
1569
1570 #ifdef __WIN32__
1571 return (bool)(SetCurrentDirectory(d) != 0);
1572 #else
1573 // Must change drive, too.
1574 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1575 if (isDriveSpec)
1576 {
1577 wxChar firstChar = d[0];
1578
1579 // To upper case
1580 if (firstChar > 90)
1581 firstChar = firstChar - 32;
1582
1583 // To a drive number
1584 unsigned int driveNo = firstChar - 64;
1585 if (driveNo > 0)
1586 {
1587 unsigned int noDrives;
1588 _dos_setdrive(driveNo, &noDrives);
1589 }
1590 }
1591 bool success = (chdir(WXSTRINGCAST d) == 0);
1592
1593 return success;
1594 #endif
1595
1596 #endif
1597 }
1598
1599 // Get the OS directory if appropriate (such as the Windows directory).
1600 // On non-Windows platform, probably just return the empty string.
1601 wxString wxGetOSDirectory()
1602 {
1603 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1604 wxChar buf[256];
1605 GetWindowsDirectory(buf, 256);
1606 return wxString(buf);
1607 #else
1608 return wxEmptyString;
1609 #endif
1610 }
1611
1612 bool wxEndsWithPathSeparator(const wxChar *pszFileName)
1613 {
1614 size_t len = wxStrlen(pszFileName);
1615
1616 return len && wxIsPathSeparator(pszFileName[len - 1]);
1617 }
1618
1619 // find a file in a list of directories, returns false if not found
1620 bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
1621 {
1622 // we assume that it's not empty
1623 wxCHECK_MSG( !wxIsEmpty(pszFile), FALSE,
1624 _T("empty file name in wxFindFileInPath"));
1625
1626 // skip path separator in the beginning of the file name if present
1627 if ( wxIsPathSeparator(*pszFile) )
1628 pszFile++;
1629
1630 // copy the path (strtok will modify it)
1631 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1632 wxStrcpy(szPath, pszPath);
1633
1634 wxString strFile;
1635 wxChar *pc, *save_ptr;
1636 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1637 pc != NULL;
1638 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1639 {
1640 // search for the file in this directory
1641 strFile = pc;
1642 if ( !wxEndsWithPathSeparator(pc) )
1643 strFile += wxFILE_SEP_PATH;
1644 strFile += pszFile;
1645
1646 if ( wxFileExists(strFile) ) {
1647 *pStr = strFile;
1648 break;
1649 }
1650 }
1651
1652 // suppress warning about unused variable save_ptr when wxStrtok() is a
1653 // macro which throws away its third argument
1654 save_ptr = pc;
1655
1656 delete [] szPath;
1657
1658 return pc != NULL; // if true => we breaked from the loop
1659 }
1660
1661 void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
1662 wxString *pstrPath,
1663 wxString *pstrName,
1664 wxString *pstrExt)
1665 {
1666 // it can be empty, but it shouldn't be NULL
1667 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
1668
1669 wxFileName::SplitPath(pszFileName, pstrPath, pstrName, pstrExt);
1670 }
1671
1672 time_t WXDLLEXPORT wxFileModificationTime(const wxString& filename)
1673 {
1674 wxStructStat buf;
1675 wxStat( filename, &buf);
1676
1677 return buf.st_mtime;
1678 }
1679
1680
1681 //------------------------------------------------------------------------
1682 // wild character routines
1683 //------------------------------------------------------------------------
1684
1685 bool wxIsWild( const wxString& pattern )
1686 {
1687 wxString tmp = pattern;
1688 wxChar *pat = WXSTRINGCAST(tmp);
1689 while (*pat)
1690 {
1691 switch (*pat++)
1692 {
1693 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1694 return TRUE;
1695 case wxT('\\'):
1696 if (!*pat++)
1697 return FALSE;
1698 }
1699 }
1700 return FALSE;
1701 }
1702
1703 /*
1704 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1705 *
1706 * The match procedure is public domain code (from ircII's reg.c)
1707 */
1708
1709 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1710 {
1711 if (text.empty())
1712 {
1713 /* Match if both are empty. */
1714 return pat.empty();
1715 }
1716
1717 const wxChar *m = pat.c_str(),
1718 *n = text.c_str(),
1719 *ma = NULL,
1720 *na = NULL,
1721 *mp = NULL,
1722 *np = NULL;
1723 int just = 0,
1724 pcount = 0,
1725 acount = 0,
1726 count = 0;
1727
1728 if (dot_special && (*n == wxT('.')))
1729 {
1730 /* Never match so that hidden Unix files
1731 * are never found. */
1732 return FALSE;
1733 }
1734
1735 for (;;)
1736 {
1737 if (*m == wxT('*'))
1738 {
1739 ma = ++m;
1740 na = n;
1741 just = 1;
1742 mp = NULL;
1743 acount = count;
1744 }
1745 else if (*m == wxT('?'))
1746 {
1747 m++;
1748 if (!*n++)
1749 return FALSE;
1750 }
1751 else
1752 {
1753 if (*m == wxT('\\'))
1754 {
1755 m++;
1756 /* Quoting "nothing" is a bad thing */
1757 if (!*m)
1758 return FALSE;
1759 }
1760 if (!*m)
1761 {
1762 /*
1763 * If we are out of both strings or we just
1764 * saw a wildcard, then we can say we have a
1765 * match
1766 */
1767 if (!*n)
1768 return TRUE;
1769 if (just)
1770 return TRUE;
1771 just = 0;
1772 goto not_matched;
1773 }
1774 /*
1775 * We could check for *n == NULL at this point, but
1776 * since it's more common to have a character there,
1777 * check to see if they match first (m and n) and
1778 * then if they don't match, THEN we can check for
1779 * the NULL of n
1780 */
1781 just = 0;
1782 if (*m == *n)
1783 {
1784 m++;
1785 if (*n == wxT(' '))
1786 mp = NULL;
1787 count++;
1788 n++;
1789 }
1790 else
1791 {
1792
1793 not_matched:
1794
1795 /*
1796 * If there are no more characters in the
1797 * string, but we still need to find another
1798 * character (*m != NULL), then it will be
1799 * impossible to match it
1800 */
1801 if (!*n)
1802 return FALSE;
1803 if (mp)
1804 {
1805 m = mp;
1806 if (*np == wxT(' '))
1807 {
1808 mp = NULL;
1809 goto check_percent;
1810 }
1811 n = ++np;
1812 count = pcount;
1813 }
1814 else
1815 check_percent:
1816
1817 if (ma)
1818 {
1819 m = ma;
1820 n = ++na;
1821 count = acount;
1822 }
1823 else
1824 return FALSE;
1825 }
1826 }
1827 }
1828 }
1829
1830
1831 #ifdef __VISUALC__
1832 #pragma warning(default:4706) // assignment within conditional expression
1833 #endif // VC++