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