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 // ----------------------------------------------------------------------------
20 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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
58 #include "wx/msw/wince/time.h"
59 #include "wx/msw/private.h"
66 #elif !defined(__MWERKS__)
67 #include <sys/types.h>
71 #include <sys/types.h>
91 #include "wx/os2/private.h"
93 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
94 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__) && !defined(__WXWINCE__)
99 #endif // native Win compiler
112 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
113 // this (3.1 I believe) and how to test for it.
114 // If this works for Borland 4.0 as well, then no worries.
125 // No, Cygwin doesn't appear to have fnmatch.h after all.
126 #if defined(HAVE_FNMATCH_H)
131 #include "wx/msw/wrapwin.h"
132 #include "wx/msw/mslu.h"
139 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
141 // note that it must be included after <windows.h>
144 #include <sys/cygwin.h>
146 #endif // __GNUWIN32__
147 #endif // __WINDOWS__
149 // TODO: Borland probably has _wgetcwd as well?
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
159 #define _MAXPATHLEN 1024
164 # include "MoreFilesX.h"
166 # include "MoreFiles.h"
167 # include "MoreFilesExtras.h"
168 # include "FullPath.h"
169 # include "FSpCompat.h"
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
177 // MT-FIXME: get rid of this horror and all code using it
178 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
180 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
182 // VisualAge C++ V4.0 cannot have any external linkage const decs
183 // in headers included by more than one primary source
185 const off_t wxInvalidOffset
= (off_t
)-1;
188 // ----------------------------------------------------------------------------
190 // ----------------------------------------------------------------------------
192 // we need to translate Mac filenames before passing them to OS functions
193 #define OS_FILENAME(s) (s.fn_str())
195 // ============================================================================
197 // ============================================================================
199 #ifdef wxNEED_WX_UNISTD_H
201 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
203 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
206 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
208 return access( wxConvFile
.cWX2MB( pathname
), mode
);
211 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
213 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
217 // wxNEED_WX_UNISTD_H
219 // ----------------------------------------------------------------------------
221 // ----------------------------------------------------------------------------
223 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
225 static inline wxChar
* MYcopystring(const wxString
& s
)
227 wxChar
* copy
= new wxChar
[s
.length() + 1];
228 return wxStrcpy(copy
, s
.c_str());
231 static inline wxChar
* MYcopystring(const wxChar
* s
)
233 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
234 return wxStrcpy(copy
, s
);
237 void wxPathList::Add (const wxString
& path
)
239 wxStringList::Add (WXSTRINGCAST path
);
242 // Add paths e.g. from the PATH environment variable
243 void wxPathList::AddEnvList (const wxString
& envVariable
)
245 // No environment variables on WinCE
247 static const wxChar PATH_TOKS
[] =
250 The space has been removed from the tokenizers, otherwise a
251 path such as "C:\Program Files" would be split into 2 paths:
252 "C:\Program" and "Files"
254 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
255 wxT(";"); // Don't seperate with colon in DOS (used for drive)
260 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
263 wxChar
*s
= MYcopystring (val
);
264 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
271 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
279 // suppress warning about unused variable save_ptr when wxStrtok() is a
280 // macro which throws away its third argument
288 // Given a full filename (with path), ensure that that file can
289 // be accessed again USING FILENAME ONLY by adding the path
290 // to the list if not already there.
291 void wxPathList::EnsureFileAccessible (const wxString
& path
)
293 wxString
path_only(wxPathOnly(path
));
294 if ( !path_only
.IsEmpty() )
296 if ( !Member(path_only
) )
301 bool wxPathList::Member (const wxString
& path
)
303 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
305 wxString
path2( node
->GetData() );
307 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
309 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
311 // Case sensitive File System
312 path
.CompareTo (path2
) == 0
320 wxString
wxPathList::FindValidPath (const wxString
& file
)
322 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
323 return wxString(wxFileFunctionsBuffer
);
325 wxChar buf
[_MAXPATHLEN
];
326 wxStrcpy(buf
, wxFileFunctionsBuffer
);
328 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
329 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
331 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
333 const wxChar
*path
= node
->GetData();
334 wxStrcpy (wxFileFunctionsBuffer
, path
);
335 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
336 if (ch
!= wxT('\\') && ch
!= wxT('/'))
337 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
338 wxStrcat (wxFileFunctionsBuffer
, filename
);
340 wxUnix2DosFilename (wxFileFunctionsBuffer
);
342 if (wxFileExists (wxFileFunctionsBuffer
))
344 return wxString(wxFileFunctionsBuffer
); // Found!
348 return wxEmptyString
; // Not found
351 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
353 wxString f
= FindValidPath(file
);
354 if ( wxIsAbsolutePath(f
) )
358 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
360 if ( !wxEndsWithPathSeparator(buf
) )
362 buf
+= wxFILE_SEP_PATH
;
370 wxFileExists (const wxString
& filename
)
372 // we must use GetFileAttributes() instead of the ANSI C functions because
373 // it can cope with network (UNC) paths unlike them
374 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
375 DWORD ret
= ::GetFileAttributes(filename
);
377 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
380 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
381 #endif // __WIN32__/!__WIN32__
385 wxIsAbsolutePath (const wxString
& filename
)
387 if (filename
!= wxT(""))
389 #if defined(__WXMAC__) && !defined(__DARWIN__)
390 // Classic or Carbon CodeWarrior like
391 // Carbon with Apple DevTools is Unix like
393 // This seems wrong to me, but there is no fix. since
394 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
395 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
396 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
399 // Unix like or Windows
400 if (filename
[0] == wxT('/'))
404 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
409 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
417 * Strip off any extension (dot something) from end of file,
418 * IF one exists. Inserts zero into buffer.
422 void wxStripExtension(wxChar
*buffer
)
424 int len
= wxStrlen(buffer
);
428 if (buffer
[i
] == wxT('.'))
437 void wxStripExtension(wxString
& buffer
)
439 size_t len
= buffer
.Length();
443 if (buffer
.GetChar(i
) == wxT('.'))
445 buffer
= buffer
.Left(i
);
452 // Destructive removal of /./ and /../ stuff
453 wxChar
*wxRealPath (wxChar
*path
)
456 static const wxChar SEP
= wxT('\\');
457 wxUnix2DosFilename(path
);
459 static const wxChar SEP
= wxT('/');
461 if (path
[0] && path
[1]) {
462 /* MATTHEW: special case "/./x" */
464 if (path
[2] == SEP
&& path
[1] == wxT('.'))
472 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
475 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
480 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
481 && (q
- 1 <= path
|| q
[-1] != SEP
))
484 if (path
[0] == wxT('\0'))
490 /* Check that path[2] is NULL! */
491 else if (path
[1] == wxT(':') && !path
[2])
500 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
509 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
511 if (filename
== wxT(""))
512 return (wxChar
*) NULL
;
514 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
515 wxChar buf
[_MAXPATHLEN
];
517 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
518 wxChar ch
= buf
[wxStrlen(buf
) - 1];
520 if (ch
!= wxT('\\') && ch
!= wxT('/'))
521 wxStrcat(buf
, wxT("\\"));
524 wxStrcat(buf
, wxT("/"));
526 wxStrcat(buf
, wxFileFunctionsBuffer
);
527 return MYcopystring( wxRealPath(buf
) );
529 return MYcopystring( wxFileFunctionsBuffer
);
535 ~user/ => user's home dir
536 If the environment variable a = "foo" and b = "bar" then:
553 /* input name in name, pathname output to buf. */
555 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
557 register wxChar
*d
, *s
, *nm
;
558 wxChar lnm
[_MAXPATHLEN
];
561 // Some compilers don't like this line.
562 // const wxChar trimchars[] = wxT("\n \t");
565 trimchars
[0] = wxT('\n');
566 trimchars
[1] = wxT(' ');
567 trimchars
[2] = wxT('\t');
571 const wxChar SEP
= wxT('\\');
573 const wxChar SEP
= wxT('/');
576 if (name
== NULL
|| *name
== wxT('\0'))
578 nm
= MYcopystring(name
); // Make a scratch copy
581 /* Skip leading whitespace and cr */
582 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
584 /* And strip off trailing whitespace and cr */
585 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
586 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
594 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
597 /* Expand inline environment variables */
615 while ((*d
++ = *s
) != 0) {
617 if (*s
== wxT('\\')) {
618 if ((*(d
- 1) = *++s
)) {
626 // No env variables on WinCE
629 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
631 if (*s
++ == wxT('$'))
634 register wxChar
*start
= d
;
635 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
636 register wxChar
*value
;
637 while ((*d
++ = *s
) != 0)
638 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
643 value
= wxGetenv(braces
? start
+ 1 : start
);
645 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
659 /* Expand ~ and ~user */
661 if (nm
[0] == wxT('~') && !q
)
664 if (nm
[1] == SEP
|| nm
[1] == 0)
666 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
667 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
672 { /* ~user/filename */
673 register wxChar
*nnm
;
674 register wxChar
*home
;
675 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
679 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
680 was_sep
= (*s
== SEP
);
681 nnm
= *s
? s
+ 1 : s
;
683 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
684 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
685 if (was_sep
) /* replace only if it was there: */
696 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
698 while (wxT('\0') != (*d
++ = *s
++))
701 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
705 while ((*d
++ = *s
++) != 0)
709 delete[] nm_tmp
; // clean up alloc
710 /* Now clean up the buffer */
711 return wxRealPath(buf
);
714 /* Contract Paths to be build upon an environment variable
717 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
719 The call wxExpandPath can convert these back!
722 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
724 static wxChar dest
[_MAXPATHLEN
];
726 if (filename
== wxT(""))
727 return (wxChar
*) NULL
;
729 wxStrcpy (dest
, WXSTRINGCAST filename
);
731 wxUnix2DosFilename(dest
);
734 // Handle environment
735 const wxChar
*val
= (const wxChar
*) NULL
;
737 wxChar
*tcp
= (wxChar
*) NULL
;
738 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
739 (tcp
= wxStrstr (dest
, val
)) != NULL
)
741 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
744 wxStrcpy (tcp
, WXSTRINGCAST envname
);
745 wxStrcat (tcp
, wxT("}"));
746 wxStrcat (tcp
, wxFileFunctionsBuffer
);
750 // Handle User's home (ignore root homes!)
752 if ((val
= wxGetUserHome (user
)) != NULL
&&
753 (len
= wxStrlen(val
)) > 2 &&
754 wxStrncmp(dest
, val
, len
) == 0)
756 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
758 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
759 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
760 wxStrcpy (dest
, wxFileFunctionsBuffer
);
766 // Return just the filename, not the path (basename)
767 wxChar
*wxFileNameFromPath (wxChar
*path
)
770 wxString n
= wxFileNameFromPath(p
);
772 return path
+ p
.length() - n
.length();
775 wxString
wxFileNameFromPath (const wxString
& path
)
778 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
780 wxString fullname
= name
;
783 fullname
<< wxFILE_SEP_EXT
<< ext
;
789 // Return just the directory, or NULL if no directory
791 wxPathOnly (wxChar
*path
)
795 static wxChar buf
[_MAXPATHLEN
];
798 wxStrcpy (buf
, path
);
800 int l
= wxStrlen(path
);
803 // Search backward for a backward or forward slash
806 #if defined(__WXMAC__) && !defined(__DARWIN__)
807 // Classic or Carbon CodeWarrior like
808 // Carbon with Apple DevTools is Unix like
809 if (path
[i
] == wxT(':') )
815 // Unix like or Windows
816 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
823 if (path
[i
] == wxT(']'))
832 #if defined(__WXMSW__) || defined(__WXPM__)
833 // Try Drive specifier
834 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
836 // A:junk --> A:. (since A:.\junk Not A:\junk)
843 return (wxChar
*) NULL
;
846 // Return just the directory, or NULL if no directory
847 wxString
wxPathOnly (const wxString
& path
)
851 wxChar buf
[_MAXPATHLEN
];
854 wxStrcpy (buf
, WXSTRINGCAST path
);
856 int l
= path
.Length();
859 // Search backward for a backward or forward slash
862 #if defined(__WXMAC__) && !defined(__DARWIN__)
863 // Classic or Carbon CodeWarrior like
864 // Carbon with Apple DevTools is Unix like
865 if (path
[i
] == wxT(':') )
868 return wxString(buf
);
871 // Unix like or Windows
872 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
875 return wxString(buf
);
879 if (path
[i
] == wxT(']'))
882 return wxString(buf
);
888 #if defined(__WXMSW__) || defined(__WXPM__)
889 // Try Drive specifier
890 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
892 // A:junk --> A:. (since A:.\junk Not A:\junk)
895 return wxString(buf
);
899 return wxString(wxT(""));
902 // Utility for converting delimiters in DOS filenames to UNIX style
903 // and back again - or we get nasty problems with delimiters.
904 // Also, convert to lower case, since case is significant in UNIX.
906 #if defined(__WXMAC__)
907 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
914 Boolean isDirectory
= FALSE
;
915 Str255 theParentPath
= "\p";
916 FSSpec theParentSpec
;
918 char theFileName
[FILENAME_MAX
];
919 char thePath
[FILENAME_MAX
];
923 // GD: Separate file name from path and make a FSRef to the parent
924 // directory. This is necessary since FSRefs cannot reference files
925 // that have not yet been created.
926 // Based on example code from Apple Technical Note TN2022
927 // http://developer.apple.com/technotes/tn/tn2022.html
929 // check whether we are converting a directory
930 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
931 // count length of file name
932 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
934 // prepend path separator since it will later be appended to the path
935 theFileName
[0] = wxFILE_SEP_PATH
;
936 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
937 theFileName
[j
- i
] = spec
->name
[j
];
939 theFileName
[j
- i
] = '\0';
941 for (j
= 1; j
<= i
; j
++) {
942 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
944 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
945 if (theErr
== noErr
) {
946 // convert the FSSpec to an FSRef
947 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
949 if (theErr
== noErr
) {
950 // get the POSIX path associated with the FSRef
951 theStatus
= FSRefMakePath(&theParentRef
,
952 (UInt8
*)thePath
, sizeof(thePath
));
954 if (theStatus
== noErr
) {
955 // append file name to path
956 // includes previously prepended path separator
957 strcat(thePath
, theFileName
);
960 // create path string for return value
961 wxString
result( thePath
, wxConvLocal
) ;
966 // get length of path and allocate handle
967 FSpGetFullPath( spec
, &length
, &myPath
) ;
968 ::SetHandleSize( myPath
, length
+ 1 ) ;
970 (*myPath
)[length
] = 0 ;
971 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
972 (*myPath
)[length
-1] = 0 ;
974 // create path string for return value
975 wxString
result( *myPath
, wxConvLocal
) ;
977 // free allocated handle
978 ::HUnlock( myPath
) ;
979 ::DisposeHandle( myPath
) ;
985 // Mac file names are POSIX (Unix style) under Darwin
986 // therefore the conversion functions below are not needed
988 static wxChar sMacFileNameConversion
[ 1000 ] ;
989 static char scMacFileNameConversion
[ 1000 ] ;
992 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
994 OSStatus err
= noErr
;
998 // get the FSRef associated with the POSIX path
999 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
1000 // convert the FSRef to an FSSpec
1001 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
1003 if ( strchr( path
, ':' ) == NULL
)
1005 // try whether it is a volume / or a mounted volume
1006 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
1007 scMacFileNameConversion
[998] = 0 ;
1008 strcat( scMacFileNameConversion
, ":" ) ;
1009 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
1013 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
1019 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
1021 return wxMacFilename2FSSpec( wxConvFile
.cWC2MB(path
) , spec
) ;
1027 wxString
wxMac2UnixFilename (const wxChar
*str
)
1029 wxChar
*s
= sMacFileNameConversion
;
1030 wxStrcpy( s
, str
) ;
1033 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1044 *s
= wxTolower(*s
); // Case INDEPENDENT
1048 return wxString(sMacFileNameConversion
) ;
1051 wxString
wxUnix2MacFilename (const wxChar
*str
)
1053 wxChar
*s
= sMacFileNameConversion
;
1054 wxStrcpy( s
, str
) ;
1059 // relative path , since it goes on with slash which is translated to a :
1060 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1062 else if ( *s
== '/' )
1064 // absolute path -> on mac just start with the drive name
1065 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1069 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1073 if (*s
== '/' || *s
== '\\')
1075 // convert any back-directory situations
1076 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1079 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1087 return wxString(sMacFileNameConversion
) ;
1090 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1092 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1095 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1097 wxString var
= wxUnix2MacFilename( path
) ;
1098 wxMacFilename2FSSpec( var
, spec
) ;
1100 #endif // ! __DARWIN__
1105 wxDos2UnixFilename (wxChar
*s
)
1114 *s
= wxTolower (*s
); // Case INDEPENDENT
1121 #if defined(__WXMSW__) || defined(__WXPM__)
1122 wxUnix2DosFilename (wxChar
*s
)
1124 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1127 // Yes, I really mean this to happen under DOS only! JACS
1128 #if defined(__WXMSW__) || defined(__WXPM__)
1139 // Concatenate two files to form third
1141 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1144 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1147 FILE *fp1
= (FILE *) NULL
;
1148 FILE *fp2
= (FILE *) NULL
;
1149 FILE *fp3
= (FILE *) NULL
;
1150 // Open the inputs and outputs
1151 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1152 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1153 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1165 while ((ch
= getc (fp1
)) != EOF
)
1166 (void) putc (ch
, fp3
);
1169 while ((ch
= getc (fp2
)) != EOF
)
1170 (void) putc (ch
, fp3
);
1174 bool result
= wxRenameFile(outfile
, file3
);
1180 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1182 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1183 // CopyFile() copies file attributes and modification time too, so use it
1184 // instead of our code if available
1186 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1187 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1189 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1190 file1
.c_str(), file2
.c_str());
1194 #elif defined(__WXPM__)
1195 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1200 // get permissions of file1
1201 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1203 // the file probably doesn't exist or we haven't the rights to read
1205 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1210 // open file1 for reading
1211 wxFile
fileIn(file1
, wxFile::read
);
1212 if ( !fileIn
.IsOpened() )
1215 // remove file2, if it exists. This is needed for creating
1216 // file2 with the correct permissions in the next step
1217 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1219 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1225 // reset the umask as we want to create the file with exactly the same
1226 // permissions as the original one
1227 mode_t oldUmask
= umask( 0 );
1230 // create file2 with the same permissions than file1 and open it for
1234 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1238 /// restore the old umask
1242 // copy contents of file1 to file2
1247 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1248 if ( fileIn
.Error() )
1255 if ( fileOut
.Write(buf
, count
) < count
)
1259 // we can expect fileIn to be closed successfully, but we should ensure
1260 // that fileOut was closed as some write errors (disk full) might not be
1261 // detected before doing this
1262 if ( !fileIn
.Close() || !fileOut
.Close() )
1265 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1266 // no chmod in VA. Should be some permission API for HPFS386 partitions
1268 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1270 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1274 #endif // OS/2 || Mac
1275 #endif // __WXMSW__ && __WIN32__
1281 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1284 // Normal system call
1285 if ( wxRename (file1
, file2
) == 0 )
1290 if (wxCopyFile(file1
, file2
)) {
1291 wxRemoveFile(file1
);
1298 bool wxRemoveFile(const wxString
& file
)
1300 #if defined(__VISUALC__) \
1301 || defined(__BORLANDC__) \
1302 || defined(__WATCOMC__) \
1303 || defined(__GNUWIN32__)
1304 int res
= wxRemove(file
);
1305 #elif defined(__WXMAC__)
1306 int res
= unlink(wxFNCONV(file
));
1308 int res
= unlink(OS_FILENAME(file
));
1314 bool wxMkdir(const wxString
& dir
, int perm
)
1316 #if defined(__WXMAC__) && !defined(__UNIX__)
1317 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1319 const wxChar
*dirname
= dir
.c_str();
1321 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1322 // for the GNU compiler
1323 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1325 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1327 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1329 #elif defined(__WXPM__)
1330 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1331 #elif defined(__DOS__)
1332 #if defined(__WATCOMC__)
1334 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1335 #elif defined(__DJGPP__)
1336 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1338 #error "Unsupported DOS compiler!"
1340 #else // !MSW, !DOS and !OS/2 VAC++
1343 if ( !CreateDirectory(dirname
, NULL
) )
1345 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1349 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1358 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1361 return FALSE
; //to be changed since rmdir exists in VMS7.x
1362 #elif defined(__WXPM__)
1363 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1367 return (CreateDirectory(dir
, NULL
) != 0);
1369 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1375 // does the path exists? (may have or not '/' or '\\' at the end)
1376 bool wxPathExists(const wxChar
*pszPathName
)
1378 wxString
strPath(pszPathName
);
1381 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1382 // so remove all trailing backslashes from the path - but don't do this for
1383 // the pathes "d:\" (which are different from "d:") nor for just "\"
1384 while ( wxEndsWithPathSeparator(strPath
) )
1386 size_t len
= strPath
.length();
1387 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1390 strPath
.Truncate(len
- 1);
1392 #endif // __WINDOWS__
1394 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1395 // stat() can't cope with network paths
1396 DWORD ret
= ::GetFileAttributes(strPath
);
1398 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1402 #ifndef __VISAGECPP__
1403 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1405 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1406 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1409 #endif // __WIN32__/!__WIN32__
1412 // Get a temporary filename, opening and closing the file.
1413 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1415 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1416 if ( filename
.empty() )
1420 wxStrcpy(buf
, filename
);
1422 buf
= MYcopystring(filename
);
1427 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1429 buf
= wxFileName::CreateTempFileName(prefix
);
1431 return !buf
.empty();
1434 // Get first file name matching given wild card.
1436 static wxDir
*gs_dir
= NULL
;
1437 static wxString gs_dirPath
;
1439 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1441 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1442 if ( gs_dirPath
.IsEmpty() )
1443 gs_dirPath
= wxT(".");
1444 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1445 gs_dirPath
<< wxFILE_SEP_PATH
;
1449 gs_dir
= new wxDir(gs_dirPath
);
1451 if ( !gs_dir
->IsOpened() )
1453 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1454 return wxEmptyString
;
1460 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1461 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1462 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1466 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1467 if ( result
.IsEmpty() )
1473 return gs_dirPath
+ result
;
1476 wxString
wxFindNextFile()
1478 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1481 gs_dir
->GetNext(&result
);
1483 if ( result
.IsEmpty() )
1489 return gs_dirPath
+ result
;
1493 // Get current working directory.
1494 // If buf is NULL, allocates space using new, else
1496 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1503 buf
= new wxChar
[sz
+ 1];
1508 // for the compilers which have Unicode version of _getcwd(), call it
1509 // directly, for the others call the ANSI version and do the translation
1512 #else // wxUSE_UNICODE
1513 bool needsANSI
= TRUE
;
1515 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1516 // This is not legal code as the compiler
1517 // is allowed destroy the wxCharBuffer.
1518 // wxCharBuffer c_buffer(sz);
1519 // char *cbuf = (char*)(const char*)c_buffer;
1520 char cbuf
[_MAXPATHLEN
];
1524 #if wxUSE_UNICODE_MSLU
1525 if ( wxGetOsVersion() != wxWIN95
)
1527 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1530 ok
= _wgetcwd(buf
, sz
) != NULL
;
1536 #endif // wxUSE_UNICODE
1538 #if defined(_MSC_VER) || defined(__MINGW32__)
1539 ok
= _getcwd(cbuf
, sz
) != NULL
;
1540 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1545 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1547 pb
.ioRefNum
= LMGetCurApRefNum();
1549 error
= PBGetFCBInfoSync(&pb
);
1550 if ( error
== noErr
)
1552 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1553 cwdSpec
.parID
= pb
.ioFCBParID
;
1554 cwdSpec
.name
[0] = 0 ;
1555 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1556 wxStrcpy( buf
, res
) ;
1563 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1565 rc
= ::DosQueryCurrentDir( 0 // current drive
1570 #else // !Win32/VC++ !Mac !OS2
1571 ok
= getcwd(cbuf
, sz
) != NULL
;
1574 #if wxUSE_UNICODE && !defined(__WXMAC__)
1575 // finally convert the result to Unicode if needed
1576 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1577 #endif // wxUSE_UNICODE
1582 wxLogSysError(_("Failed to get the working directory"));
1584 // VZ: the old code used to return "." on error which didn't make any
1585 // sense at all to me - empty string is a better error indicator
1586 // (NULL might be even better but I'm afraid this could lead to
1587 // problems with the old code assuming the return is never NULL)
1590 else // ok, but we might need to massage the path into the right format
1593 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1594 // with / deliminers. We don't like that.
1595 for (wxChar
*ch
= buf
; *ch
; ch
++)
1597 if (*ch
== wxT('/'))
1602 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1603 // he needs Unix as opposed to Win32 pathnames
1604 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1605 // another example of DOS/Unix mix (Cygwin)
1606 wxString pathUnix
= buf
;
1607 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1608 #endif // __CYGWIN__
1623 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1624 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1625 wxString
str( buffer
);
1631 bool wxSetWorkingDirectory(const wxString
& d
)
1633 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1634 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1635 #elif defined(__WXPM__)
1636 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1637 #elif defined(__WINDOWS__)
1641 // No equivalent in WinCE
1644 return (bool)(SetCurrentDirectory(d
) != 0);
1647 // Must change drive, too.
1648 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1651 wxChar firstChar
= d
[0];
1655 firstChar
= firstChar
- 32;
1657 // To a drive number
1658 unsigned int driveNo
= firstChar
- 64;
1661 unsigned int noDrives
;
1662 _dos_setdrive(driveNo
, &noDrives
);
1665 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1673 // Get the OS directory if appropriate (such as the Windows directory).
1674 // On non-Windows platform, probably just return the empty string.
1675 wxString
wxGetOSDirectory()
1678 return wxString(wxT("\\Windows"));
1679 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1681 GetWindowsDirectory(buf
, 256);
1682 return wxString(buf
);
1683 #elif defined(__WXMAC__)
1684 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1686 return wxEmptyString
;
1690 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1692 size_t len
= wxStrlen(pszFileName
);
1694 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1697 // find a file in a list of directories, returns FALSE if not found
1698 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1700 // we assume that it's not empty
1701 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1702 _T("empty file name in wxFindFileInPath"));
1704 // skip path separator in the beginning of the file name if present
1705 if ( wxIsPathSeparator(*pszFile
) )
1708 // copy the path (strtok will modify it)
1709 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1710 wxStrcpy(szPath
, pszPath
);
1713 wxChar
*pc
, *save_ptr
;
1714 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1716 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1718 // search for the file in this directory
1720 if ( !wxEndsWithPathSeparator(pc
) )
1721 strFile
+= wxFILE_SEP_PATH
;
1724 if ( wxFileExists(strFile
) ) {
1730 // suppress warning about unused variable save_ptr when wxStrtok() is a
1731 // macro which throws away its third argument
1736 return pc
!= NULL
; // if TRUE => we breaked from the loop
1739 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1744 // it can be empty, but it shouldn't be NULL
1745 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1747 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1750 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1753 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1754 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1755 0, FILE_ATTRIBUTE_NORMAL
, 0);
1756 if (fileHandle
== INVALID_HANDLE_VALUE
)
1760 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1762 CloseHandle(fileHandle
);
1764 wxDateTime dateTime
;
1766 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1768 wxLogLastError(_T("FileTimeToLocalFileTime"));
1772 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1774 wxLogLastError(_T("FileTimeToSystemTime"));
1777 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1778 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1779 return dateTime
.GetTicks();
1786 wxStat( filename
, &buf
);
1788 return buf
.st_mtime
;
1793 //------------------------------------------------------------------------
1794 // wild character routines
1795 //------------------------------------------------------------------------
1797 bool wxIsWild( const wxString
& pattern
)
1799 wxString tmp
= pattern
;
1800 wxChar
*pat
= WXSTRINGCAST(tmp
);
1805 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1816 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1818 * The match procedure is public domain code (from ircII's reg.c)
1821 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1825 /* Match if both are empty. */
1829 const wxChar
*m
= pat
.c_str(),
1840 if (dot_special
&& (*n
== wxT('.')))
1842 /* Never match so that hidden Unix files
1843 * are never found. */
1857 else if (*m
== wxT('?'))
1865 if (*m
== wxT('\\'))
1868 /* Quoting "nothing" is a bad thing */
1875 * If we are out of both strings or we just
1876 * saw a wildcard, then we can say we have a
1887 * We could check for *n == NULL at this point, but
1888 * since it's more common to have a character there,
1889 * check to see if they match first (m and n) and
1890 * then if they don't match, THEN we can check for
1908 * If there are no more characters in the
1909 * string, but we still need to find another
1910 * character (*m != NULL), then it will be
1911 * impossible to match it
1918 if (*np
== wxT(' '))
1944 #pragma warning(default:4706) // assignment within conditional expression