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