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