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