1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "filefn.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
35 #include "wx/filename.h"
38 // there are just too many of those...
40 #pragma warning(disable:4706) // assignment within conditional expression
47 #if !defined(__WATCOMC__)
48 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
53 #if defined(__WXMAC__)
54 #include "wx/mac/private.h" // includes mac headers
60 #include <sys/types.h>
64 #include <sys/types.h>
84 #include "wx/os2/private.h"
86 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
87 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
92 #endif // native Win compiler
105 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
106 // this (3.1 I believe) and how to test for it.
107 // If this works for Borland 4.0 as well, then no worries.
118 // No, Cygwin doesn't appear to have fnmatch.h after all.
119 #if defined(HAVE_FNMATCH_H)
125 #include "wx/msw/mslu.h"
132 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
134 // note that it must be included after <windows.h>
137 #include <sys/cygwin.h>
139 #endif // __GNUWIN32__
140 #endif // __WINDOWS__
142 // TODO: Borland probably has _wgetcwd as well?
147 // ----------------------------------------------------------------------------
149 // ----------------------------------------------------------------------------
152 #define _MAXPATHLEN 1024
157 # include "MoreFilesX.h"
159 # include "MoreFiles.h"
160 # include "MoreFilesExtras.h"
161 # include "FullPath.h"
162 # include "FSpCompat.h"
166 // ----------------------------------------------------------------------------
168 // ----------------------------------------------------------------------------
170 // MT-FIXME: get rid of this horror and all code using it
171 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
173 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
175 // VisualAge C++ V4.0 cannot have any external linkage const decs
176 // in headers included by more than one primary source
178 const off_t wxInvalidOffset
= (off_t
)-1;
181 // ----------------------------------------------------------------------------
183 // ----------------------------------------------------------------------------
185 // we need to translate Mac filenames before passing them to OS functions
186 #define OS_FILENAME(s) (s.fn_str())
188 // ============================================================================
190 // ============================================================================
192 #if defined(__WXMAC__) && !defined(__DARWIN__)
194 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
196 return stat( wxMacStringToCString( file_name
), buf
);
199 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
201 return access( wxMacStringToCString( pathname
), mode
);
204 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
206 return open( wxMacStringToCString( pathname
), flags
, mode
);
211 #ifdef wxNEED_WX_UNISTD_H
213 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
215 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
218 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
220 return access( wxConvFile
.cWX2MB( pathname
), mode
);
223 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
225 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
229 // wxNEED_WX_UNISTD_H
231 // ----------------------------------------------------------------------------
233 // ----------------------------------------------------------------------------
235 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
237 static inline wxChar
* MYcopystring(const wxString
& s
)
239 wxChar
* copy
= new wxChar
[s
.length() + 1];
240 return wxStrcpy(copy
, s
.c_str());
243 static inline wxChar
* MYcopystring(const wxChar
* s
)
245 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
246 return wxStrcpy(copy
, s
);
249 void wxPathList::Add (const wxString
& path
)
251 wxStringList::Append (WXSTRINGCAST path
);
254 // Add paths e.g. from the PATH environment variable
255 void wxPathList::AddEnvList (const wxString
& envVariable
)
257 static const wxChar PATH_TOKS
[] =
260 The space has been removed from the tokenizers, otherwise a
261 path such as "C:\Program Files" would be split into 2 paths:
262 "C:\Program" and "Files"
264 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
265 wxT(";"); // Don't seperate with colon in DOS (used for drive)
270 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
273 wxChar
*s
= MYcopystring (val
);
274 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
281 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
289 // suppress warning about unused variable save_ptr when wxStrtok() is a
290 // macro which throws away its third argument
297 // Given a full filename (with path), ensure that that file can
298 // be accessed again USING FILENAME ONLY by adding the path
299 // to the list if not already there.
300 void wxPathList::EnsureFileAccessible (const wxString
& path
)
302 wxString
path_only(wxPathOnly(path
));
303 if ( !path_only
.IsEmpty() )
305 if ( !Member(path_only
) )
310 bool wxPathList::Member (const wxString
& path
)
312 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
314 wxString
path2( node
->GetData() );
316 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
318 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
320 // Case sensitive File System
321 path
.CompareTo (path2
) == 0
329 wxString
wxPathList::FindValidPath (const wxString
& file
)
331 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
332 return wxString(wxFileFunctionsBuffer
);
334 wxChar buf
[_MAXPATHLEN
];
335 wxStrcpy(buf
, wxFileFunctionsBuffer
);
337 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
338 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
340 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
342 const wxChar
*path
= node
->GetData();
343 wxStrcpy (wxFileFunctionsBuffer
, path
);
344 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
345 if (ch
!= wxT('\\') && ch
!= wxT('/'))
346 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
347 wxStrcat (wxFileFunctionsBuffer
, filename
);
349 wxUnix2DosFilename (wxFileFunctionsBuffer
);
351 if (wxFileExists (wxFileFunctionsBuffer
))
353 return wxString(wxFileFunctionsBuffer
); // Found!
357 return wxEmptyString
; // Not found
360 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
362 wxString f
= FindValidPath(file
);
363 if ( wxIsAbsolutePath(f
) )
367 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
369 if ( !wxEndsWithPathSeparator(buf
) )
371 buf
+= wxFILE_SEP_PATH
;
379 wxFileExists (const wxString
& filename
)
381 // we must use GetFileAttributes() instead of the ANSI C functions because
382 // it can cope with network (UNC) paths unlike them
383 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
384 DWORD ret
= ::GetFileAttributes(filename
);
386 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
389 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
390 #endif // __WIN32__/!__WIN32__
394 wxIsAbsolutePath (const wxString
& filename
)
396 if (filename
!= wxT(""))
398 #if defined(__WXMAC__) && !defined(__DARWIN__)
399 // Classic or Carbon CodeWarrior like
400 // Carbon with Apple DevTools is Unix like
402 // This seems wrong to me, but there is no fix. since
403 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
404 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
405 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
408 // Unix like or Windows
409 if (filename
[0] == wxT('/'))
413 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
418 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
426 * Strip off any extension (dot something) from end of file,
427 * IF one exists. Inserts zero into buffer.
431 void wxStripExtension(wxChar
*buffer
)
433 int len
= wxStrlen(buffer
);
437 if (buffer
[i
] == wxT('.'))
446 void wxStripExtension(wxString
& buffer
)
448 size_t len
= buffer
.Length();
452 if (buffer
.GetChar(i
) == wxT('.'))
454 buffer
= buffer
.Left(i
);
461 // Destructive removal of /./ and /../ stuff
462 wxChar
*wxRealPath (wxChar
*path
)
465 static const wxChar SEP
= wxT('\\');
466 wxUnix2DosFilename(path
);
468 static const wxChar SEP
= wxT('/');
470 if (path
[0] && path
[1]) {
471 /* MATTHEW: special case "/./x" */
473 if (path
[2] == SEP
&& path
[1] == wxT('.'))
481 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
484 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
489 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
490 && (q
- 1 <= path
|| q
[-1] != SEP
))
493 if (path
[0] == wxT('\0'))
499 /* Check that path[2] is NULL! */
500 else if (path
[1] == wxT(':') && !path
[2])
509 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
518 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
520 if (filename
== wxT(""))
521 return (wxChar
*) NULL
;
523 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
524 wxChar buf
[_MAXPATHLEN
];
526 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
527 wxChar ch
= buf
[wxStrlen(buf
) - 1];
529 if (ch
!= wxT('\\') && ch
!= wxT('/'))
530 wxStrcat(buf
, wxT("\\"));
533 wxStrcat(buf
, wxT("/"));
535 wxStrcat(buf
, wxFileFunctionsBuffer
);
536 return MYcopystring( wxRealPath(buf
) );
538 return MYcopystring( wxFileFunctionsBuffer
);
544 ~user/ => user's home dir
545 If the environment variable a = "foo" and b = "bar" then:
562 /* input name in name, pathname output to buf. */
564 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
566 register wxChar
*d
, *s
, *nm
;
567 wxChar lnm
[_MAXPATHLEN
];
570 // Some compilers don't like this line.
571 // const wxChar trimchars[] = wxT("\n \t");
574 trimchars
[0] = wxT('\n');
575 trimchars
[1] = wxT(' ');
576 trimchars
[2] = wxT('\t');
580 const wxChar SEP
= wxT('\\');
582 const wxChar SEP
= wxT('/');
585 if (name
== NULL
|| *name
== wxT('\0'))
587 nm
= MYcopystring(name
); // Make a scratch copy
590 /* Skip leading whitespace and cr */
591 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
593 /* And strip off trailing whitespace and cr */
594 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
595 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
603 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
606 /* Expand inline environment variables */
624 while ((*d
++ = *s
) != 0) {
626 if (*s
== wxT('\\')) {
627 if ((*(d
- 1) = *++s
)) {
636 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
638 if (*s
++ == wxT('$'))
641 register wxChar
*start
= d
;
642 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
643 register wxChar
*value
;
644 while ((*d
++ = *s
) != 0)
645 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
650 value
= wxGetenv(braces
? start
+ 1 : start
);
652 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
664 /* Expand ~ and ~user */
666 if (nm
[0] == wxT('~') && !q
)
669 if (nm
[1] == SEP
|| nm
[1] == 0)
671 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
672 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
677 { /* ~user/filename */
678 register wxChar
*nnm
;
679 register wxChar
*home
;
680 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
684 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
685 was_sep
= (*s
== SEP
);
686 nnm
= *s
? s
+ 1 : s
;
688 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
689 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
690 if (was_sep
) /* replace only if it was there: */
701 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
703 while (wxT('\0') != (*d
++ = *s
++))
706 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
710 while ((*d
++ = *s
++) != 0)
714 delete[] nm_tmp
; // clean up alloc
715 /* Now clean up the buffer */
716 return wxRealPath(buf
);
719 /* Contract Paths to be build upon an environment variable
722 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
724 The call wxExpandPath can convert these back!
727 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
729 static wxChar dest
[_MAXPATHLEN
];
731 if (filename
== wxT(""))
732 return (wxChar
*) NULL
;
734 wxStrcpy (dest
, WXSTRINGCAST filename
);
736 wxUnix2DosFilename(dest
);
739 // Handle environment
740 const wxChar
*val
= (const wxChar
*) NULL
;
741 wxChar
*tcp
= (wxChar
*) NULL
;
742 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
743 (tcp
= wxStrstr (dest
, val
)) != NULL
)
745 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
748 wxStrcpy (tcp
, WXSTRINGCAST envname
);
749 wxStrcat (tcp
, wxT("}"));
750 wxStrcat (tcp
, wxFileFunctionsBuffer
);
753 // Handle User's home (ignore root homes!)
755 if ((val
= wxGetUserHome (user
)) != NULL
&&
756 (len
= wxStrlen(val
)) > 2 &&
757 wxStrncmp(dest
, val
, len
) == 0)
759 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
761 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
762 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
763 wxStrcpy (dest
, wxFileFunctionsBuffer
);
769 // Return just the filename, not the path (basename)
770 wxChar
*wxFileNameFromPath (wxChar
*path
)
773 wxString n
= wxFileNameFromPath(p
);
775 return path
+ p
.length() - n
.length();
778 wxString
wxFileNameFromPath (const wxString
& path
)
781 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
783 wxString fullname
= name
;
786 fullname
<< wxFILE_SEP_EXT
<< ext
;
792 // Return just the directory, or NULL if no directory
794 wxPathOnly (wxChar
*path
)
798 static wxChar buf
[_MAXPATHLEN
];
801 wxStrcpy (buf
, path
);
803 int l
= wxStrlen(path
);
806 // Search backward for a backward or forward slash
809 #if defined(__WXMAC__) && !defined(__DARWIN__)
810 // Classic or Carbon CodeWarrior like
811 // Carbon with Apple DevTools is Unix like
812 if (path
[i
] == wxT(':') )
818 // Unix like or Windows
819 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
826 if (path
[i
] == wxT(']'))
835 #if defined(__WXMSW__) || defined(__WXPM__)
836 // Try Drive specifier
837 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
839 // A:junk --> A:. (since A:.\junk Not A:\junk)
846 return (wxChar
*) NULL
;
849 // Return just the directory, or NULL if no directory
850 wxString
wxPathOnly (const wxString
& path
)
854 wxChar buf
[_MAXPATHLEN
];
857 wxStrcpy (buf
, WXSTRINGCAST path
);
859 int l
= path
.Length();
862 // Search backward for a backward or forward slash
865 #if defined(__WXMAC__) && !defined(__DARWIN__)
866 // Classic or Carbon CodeWarrior like
867 // Carbon with Apple DevTools is Unix like
868 if (path
[i
] == wxT(':') )
871 return wxString(buf
);
874 // Unix like or Windows
875 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
878 return wxString(buf
);
882 if (path
[i
] == wxT(']'))
885 return wxString(buf
);
891 #if defined(__WXMSW__) || defined(__WXPM__)
892 // Try Drive specifier
893 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
895 // A:junk --> A:. (since A:.\junk Not A:\junk)
898 return wxString(buf
);
902 return wxString(wxT(""));
905 // Utility for converting delimiters in DOS filenames to UNIX style
906 // and back again - or we get nasty problems with delimiters.
907 // Also, convert to lower case, since case is significant in UNIX.
909 #if defined(__WXMAC__)
910 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
917 Boolean isDirectory
= FALSE
;
918 Str255 theParentPath
= "\p";
919 FSSpec theParentSpec
;
921 char theFileName
[FILENAME_MAX
];
922 char thePath
[FILENAME_MAX
];
926 // GD: Separate file name from path and make a FSRef to the parent
927 // directory. This is necessary since FSRefs cannot reference files
928 // that have not yet been created.
929 // Based on example code from Apple Technical Note TN2022
930 // http://developer.apple.com/technotes/tn/tn2022.html
932 // check whether we are converting a directory
933 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
934 // count length of file name
935 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
937 // prepend path separator since it will later be appended to the path
938 theFileName
[0] = wxFILE_SEP_PATH
;
939 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
940 theFileName
[j
- i
] = spec
->name
[j
];
942 theFileName
[j
- i
] = '\0';
944 for (j
= 1; j
<= i
; j
++) {
945 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
947 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
948 if (theErr
== noErr
) {
949 // convert the FSSpec to an FSRef
950 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
952 if (theErr
== noErr
) {
953 // get the POSIX path associated with the FSRef
954 theStatus
= FSRefMakePath(&theParentRef
,
955 (UInt8
*)thePath
, sizeof(thePath
));
957 if (theStatus
== noErr
) {
958 // append file name to path
959 // includes previously prepended path separator
960 strcat(thePath
, theFileName
);
963 // create path string for return value
964 wxString
result( thePath
) ;
969 // get length of path and allocate handle
970 FSpGetFullPath( spec
, &length
, &myPath
) ;
971 ::SetHandleSize( myPath
, length
+ 1 ) ;
973 (*myPath
)[length
] = 0 ;
974 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
975 (*myPath
)[length
-1] = 0 ;
977 // create path string for return value
978 wxString result
= wxMacMakeStringFromCString( *myPath
) ;
980 // free allocated handle
981 ::HUnlock( myPath
) ;
982 ::DisposeHandle( myPath
) ;
988 // Mac file names are POSIX (Unix style) under Darwin
989 // therefore the conversion functions below are not needed
991 static wxChar sMacFileNameConversion
[ 1000 ] ;
992 static char scMacFileNameConversion
[ 1000 ] ;
995 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
997 OSStatus err
= noErr
;
1001 // get the FSRef associated with the POSIX path
1002 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
1003 // convert the FSRef to an FSSpec
1004 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
1006 if ( strchr( path
, ':' ) == NULL
)
1008 // try whether it is a volume / or a mounted volume
1009 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
1010 scMacFileNameConversion
[998] = 0 ;
1011 strcat( scMacFileNameConversion
, ":" ) ;
1012 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
1016 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
1022 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
1024 return wxMacFilename2FSSpec( wxMacStringToCString( wxString( path
) ) , spec
) ;
1030 wxString
wxMac2UnixFilename (const wxChar
*str
)
1032 wxChar
*s
= sMacFileNameConversion
;
1033 wxStrcpy( s
, str
) ;
1036 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1047 *s
= wxTolower(*s
); // Case INDEPENDENT
1051 return wxString(sMacFileNameConversion
) ;
1054 wxString
wxUnix2MacFilename (const wxChar
*str
)
1056 wxChar
*s
= sMacFileNameConversion
;
1057 wxStrcpy( s
, str
) ;
1062 // relative path , since it goes on with slash which is translated to a :
1063 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1065 else if ( *s
== '/' )
1067 // absolute path -> on mac just start with the drive name
1068 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1072 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1076 if (*s
== '/' || *s
== '\\')
1078 // convert any back-directory situations
1079 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1082 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1090 return wxString(sMacFileNameConversion
) ;
1093 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1095 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1098 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1100 wxString var
= wxUnix2MacFilename( path
) ;
1101 wxMacFilename2FSSpec( var
, spec
) ;
1103 #endif // ! __DARWIN__
1108 wxDos2UnixFilename (wxChar
*s
)
1117 *s
= wxTolower (*s
); // Case INDEPENDENT
1124 #if defined(__WXMSW__) || defined(__WXPM__)
1125 wxUnix2DosFilename (wxChar
*s
)
1127 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1130 // Yes, I really mean this to happen under DOS only! JACS
1131 #if defined(__WXMSW__) || defined(__WXPM__)
1142 // Concatenate two files to form third
1144 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1147 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1150 FILE *fp1
= (FILE *) NULL
;
1151 FILE *fp2
= (FILE *) NULL
;
1152 FILE *fp3
= (FILE *) NULL
;
1153 // Open the inputs and outputs
1154 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1155 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1156 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1168 while ((ch
= getc (fp1
)) != EOF
)
1169 (void) putc (ch
, fp3
);
1172 while ((ch
= getc (fp2
)) != EOF
)
1173 (void) putc (ch
, fp3
);
1177 bool result
= wxRenameFile(outfile
, file3
);
1183 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1185 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1186 // CopyFile() copies file attributes and modification time too, so use it
1187 // instead of our code if available
1189 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1190 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1192 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1193 file1
.c_str(), file2
.c_str());
1197 #elif defined(__WXPM__)
1198 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1203 // get permissions of file1
1204 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1206 // the file probably doesn't exist or we haven't the rights to read
1208 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1213 // open file1 for reading
1214 wxFile
fileIn(file1
, wxFile::read
);
1215 if ( !fileIn
.IsOpened() )
1218 // remove file2, if it exists. This is needed for creating
1219 // file2 with the correct permissions in the next step
1220 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1222 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1228 // reset the umask as we want to create the file with exactly the same
1229 // permissions as the original one
1230 mode_t oldUmask
= umask( 0 );
1233 // create file2 with the same permissions than file1 and open it for
1237 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1241 /// restore the old umask
1245 // copy contents of file1 to file2
1250 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1251 if ( fileIn
.Error() )
1258 if ( fileOut
.Write(buf
, count
) < count
)
1262 // we can expect fileIn to be closed successfully, but we should ensure
1263 // that fileOut was closed as some write errors (disk full) might not be
1264 // detected before doing this
1265 if ( !fileIn
.Close() || !fileOut
.Close() )
1268 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1269 // no chmod in VA. Should be some permission API for HPFS386 partitions
1271 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1273 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1277 #endif // OS/2 || Mac
1278 #endif // __WXMSW__ && __WIN32__
1284 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1286 // Normal system call
1287 if ( wxRename (file1
, file2
) == 0 )
1291 if (wxCopyFile(file1
, file2
)) {
1292 wxRemoveFile(file1
);
1299 bool wxRemoveFile(const wxString
& file
)
1301 #if defined(__VISUALC__) \
1302 || defined(__BORLANDC__) \
1303 || defined(__WATCOMC__) \
1304 || defined(__GNUWIN32__)
1305 int res
= wxRemove(file
);
1306 #elif defined(__WXMAC__)
1307 int res
= unlink(wxFNCONV(file
));
1309 int res
= unlink(OS_FILENAME(file
));
1315 bool wxMkdir(const wxString
& dir
, int perm
)
1317 #if defined(__WXMAC__) && !defined(__UNIX__)
1318 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1320 const wxChar
*dirname
= dir
.c_str();
1322 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1323 // for the GNU compiler
1324 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1326 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1328 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1330 #elif defined(__WXPM__)
1331 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1332 #elif defined(__DOS__)
1333 #if defined(__WATCOMC__)
1335 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1336 #elif defined(__DJGPP__)
1337 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1339 #error "Unsupported DOS compiler!"
1341 #else // !MSW, !DOS and !OS/2 VAC++
1343 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1346 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1355 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1358 return FALSE
; //to be changed since rmdir exists in VMS7.x
1359 #elif defined(__WXPM__)
1360 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1364 return FALSE
; // What to do?
1366 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1372 // does the path exists? (may have or not '/' or '\\' at the end)
1373 bool wxPathExists(const wxChar
*pszPathName
)
1375 wxString
strPath(pszPathName
);
1378 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1379 // so remove all trailing backslashes from the path - but don't do this for
1380 // the pathes "d:\" (which are different from "d:") nor for just "\"
1381 while ( wxEndsWithPathSeparator(strPath
) )
1383 size_t len
= strPath
.length();
1384 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1387 strPath
.Truncate(len
- 1);
1389 #endif // __WINDOWS__
1391 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1392 // stat() can't cope with network paths
1393 DWORD ret
= ::GetFileAttributes(strPath
);
1395 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1399 #ifndef __VISAGECPP__
1400 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1402 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1403 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1406 #endif // __WIN32__/!__WIN32__
1409 // Get a temporary filename, opening and closing the file.
1410 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1412 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1413 if ( filename
.empty() )
1417 wxStrcpy(buf
, filename
);
1419 buf
= MYcopystring(filename
);
1424 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1426 buf
= wxFileName::CreateTempFileName(prefix
);
1428 return !buf
.empty();
1431 // Get first file name matching given wild card.
1433 static wxDir
*gs_dir
= NULL
;
1434 static wxString gs_dirPath
;
1436 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1438 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1439 if ( gs_dirPath
.IsEmpty() )
1440 gs_dirPath
= wxT(".");
1441 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1442 gs_dirPath
<< wxFILE_SEP_PATH
;
1446 gs_dir
= new wxDir(gs_dirPath
);
1448 if ( !gs_dir
->IsOpened() )
1450 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1451 return wxEmptyString
;
1457 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1458 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1459 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1463 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1464 if ( result
.IsEmpty() )
1470 return gs_dirPath
+ result
;
1473 wxString
wxFindNextFile()
1475 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1478 gs_dir
->GetNext(&result
);
1480 if ( result
.IsEmpty() )
1486 return gs_dirPath
+ result
;
1490 // Get current working directory.
1491 // If buf is NULL, allocates space using new, else
1493 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1497 buf
= new wxChar
[sz
+ 1];
1502 // for the compilers which have Unicode version of _getcwd(), call it
1503 // directly, for the others call the ANSI version and do the translation
1506 #else // wxUSE_UNICODE
1507 bool needsANSI
= TRUE
;
1509 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1510 // This is not legal code as the compiler
1511 // is allowed destroy the wxCharBuffer.
1512 // wxCharBuffer c_buffer(sz);
1513 // char *cbuf = (char*)(const char*)c_buffer;
1514 char cbuf
[_MAXPATHLEN
];
1518 #if wxUSE_UNICODE_MSLU
1519 if ( wxGetOsVersion() != wxWIN95
)
1521 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1524 ok
= _wgetcwd(buf
, sz
) != NULL
;
1530 #endif // wxUSE_UNICODE
1532 #if defined(_MSC_VER) || defined(__MINGW32__)
1533 ok
= _getcwd(cbuf
, sz
) != NULL
;
1534 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1539 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1541 pb
.ioRefNum
= LMGetCurApRefNum();
1543 error
= PBGetFCBInfoSync(&pb
);
1544 if ( error
== noErr
)
1546 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1547 cwdSpec
.parID
= pb
.ioFCBParID
;
1548 cwdSpec
.name
[0] = 0 ;
1549 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1550 wxStrcpy( buf
, res
) ;
1557 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1559 rc
= ::DosQueryCurrentDir( 0 // current drive
1564 #else // !Win32/VC++ !Mac !OS2
1565 ok
= getcwd(cbuf
, sz
) != NULL
;
1568 #if wxUSE_UNICODE && !defined(__WXMAC__)
1569 // finally convert the result to Unicode if needed
1570 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1571 #endif // wxUSE_UNICODE
1576 wxLogSysError(_("Failed to get the working directory"));
1578 // VZ: the old code used to return "." on error which didn't make any
1579 // sense at all to me - empty string is a better error indicator
1580 // (NULL might be even better but I'm afraid this could lead to
1581 // problems with the old code assuming the return is never NULL)
1584 else // ok, but we might need to massage the path into the right format
1587 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1588 // with / deliminers. We don't like that.
1589 for (wxChar
*ch
= buf
; *ch
; ch
++)
1591 if (*ch
== wxT('/'))
1596 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1597 // he needs Unix as opposed to Win32 pathnames
1598 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1599 // another example of DOS/Unix mix (Cygwin)
1600 wxString pathUnix
= buf
;
1601 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1602 #endif // __CYGWIN__
1614 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1615 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1616 wxString
str( buffer
);
1622 bool wxSetWorkingDirectory(const wxString
& d
)
1624 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1625 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1626 #elif defined(__WXPM__)
1627 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1628 #elif defined(__WINDOWS__)
1631 return (bool)(SetCurrentDirectory(d
) != 0);
1633 // Must change drive, too.
1634 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1637 wxChar firstChar
= d
[0];
1641 firstChar
= firstChar
- 32;
1643 // To a drive number
1644 unsigned int driveNo
= firstChar
- 64;
1647 unsigned int noDrives
;
1648 _dos_setdrive(driveNo
, &noDrives
);
1651 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1659 // Get the OS directory if appropriate (such as the Windows directory).
1660 // On non-Windows platform, probably just return the empty string.
1661 wxString
wxGetOSDirectory()
1663 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1665 GetWindowsDirectory(buf
, 256);
1666 return wxString(buf
);
1667 #elif defined(__WXMAC__)
1668 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1670 return wxEmptyString
;
1674 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1676 size_t len
= wxStrlen(pszFileName
);
1678 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1681 // find a file in a list of directories, returns FALSE if not found
1682 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1684 // we assume that it's not empty
1685 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1686 _T("empty file name in wxFindFileInPath"));
1688 // skip path separator in the beginning of the file name if present
1689 if ( wxIsPathSeparator(*pszFile
) )
1692 // copy the path (strtok will modify it)
1693 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1694 wxStrcpy(szPath
, pszPath
);
1697 wxChar
*pc
, *save_ptr
;
1698 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1700 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1702 // search for the file in this directory
1704 if ( !wxEndsWithPathSeparator(pc
) )
1705 strFile
+= wxFILE_SEP_PATH
;
1708 if ( wxFileExists(strFile
) ) {
1714 // suppress warning about unused variable save_ptr when wxStrtok() is a
1715 // macro which throws away its third argument
1720 return pc
!= NULL
; // if TRUE => we breaked from the loop
1723 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1728 // it can be empty, but it shouldn't be NULL
1729 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1731 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1734 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1737 wxStat( filename
, &buf
);
1739 return buf
.st_mtime
;
1743 //------------------------------------------------------------------------
1744 // wild character routines
1745 //------------------------------------------------------------------------
1747 bool wxIsWild( const wxString
& pattern
)
1749 wxString tmp
= pattern
;
1750 wxChar
*pat
= WXSTRINGCAST(tmp
);
1755 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1766 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1768 * The match procedure is public domain code (from ircII's reg.c)
1771 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1775 /* Match if both are empty. */
1779 const wxChar
*m
= pat
.c_str(),
1790 if (dot_special
&& (*n
== wxT('.')))
1792 /* Never match so that hidden Unix files
1793 * are never found. */
1807 else if (*m
== wxT('?'))
1815 if (*m
== wxT('\\'))
1818 /* Quoting "nothing" is a bad thing */
1825 * If we are out of both strings or we just
1826 * saw a wildcard, then we can say we have a
1837 * We could check for *n == NULL at this point, but
1838 * since it's more common to have a character there,
1839 * check to see if they match first (m and n) and
1840 * then if they don't match, THEN we can check for
1858 * If there are no more characters in the
1859 * string, but we still need to find another
1860 * character (*m != NULL), then it will be
1861 * impossible to match it
1868 if (*np
== wxT(' '))
1894 #pragma warning(default:4706) // assignment within conditional expression