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 #ifdef wxNEED_WX_UNISTD_H
194 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
196 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
199 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
201 return access( wxConvFile
.cWX2MB( pathname
), mode
);
204 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
206 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
210 // wxNEED_WX_UNISTD_H
212 // ----------------------------------------------------------------------------
214 // ----------------------------------------------------------------------------
216 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
218 static inline wxChar
* MYcopystring(const wxString
& s
)
220 wxChar
* copy
= new wxChar
[s
.length() + 1];
221 return wxStrcpy(copy
, s
.c_str());
224 static inline wxChar
* MYcopystring(const wxChar
* s
)
226 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
227 return wxStrcpy(copy
, s
);
230 void wxPathList::Add (const wxString
& path
)
232 wxStringList::Add (WXSTRINGCAST path
);
235 // Add paths e.g. from the PATH environment variable
236 void wxPathList::AddEnvList (const wxString
& envVariable
)
238 static const wxChar PATH_TOKS
[] =
241 The space has been removed from the tokenizers, otherwise a
242 path such as "C:\Program Files" would be split into 2 paths:
243 "C:\Program" and "Files"
245 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
246 wxT(";"); // Don't seperate with colon in DOS (used for drive)
251 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
254 wxChar
*s
= MYcopystring (val
);
255 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
262 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
270 // suppress warning about unused variable save_ptr when wxStrtok() is a
271 // macro which throws away its third argument
278 // Given a full filename (with path), ensure that that file can
279 // be accessed again USING FILENAME ONLY by adding the path
280 // to the list if not already there.
281 void wxPathList::EnsureFileAccessible (const wxString
& path
)
283 wxString
path_only(wxPathOnly(path
));
284 if ( !path_only
.IsEmpty() )
286 if ( !Member(path_only
) )
291 bool wxPathList::Member (const wxString
& path
)
293 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
295 wxString
path2( node
->GetData() );
297 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
299 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
301 // Case sensitive File System
302 path
.CompareTo (path2
) == 0
310 wxString
wxPathList::FindValidPath (const wxString
& file
)
312 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
313 return wxString(wxFileFunctionsBuffer
);
315 wxChar buf
[_MAXPATHLEN
];
316 wxStrcpy(buf
, wxFileFunctionsBuffer
);
318 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
319 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
321 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
323 wxChar
*path
= node
->GetData();
324 wxStrcpy (wxFileFunctionsBuffer
, path
);
325 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
326 if (ch
!= wxT('\\') && ch
!= wxT('/'))
327 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
328 wxStrcat (wxFileFunctionsBuffer
, filename
);
330 wxUnix2DosFilename (wxFileFunctionsBuffer
);
332 if (wxFileExists (wxFileFunctionsBuffer
))
334 return wxString(wxFileFunctionsBuffer
); // Found!
338 return wxEmptyString
; // Not found
341 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
343 wxString f
= FindValidPath(file
);
344 if ( wxIsAbsolutePath(f
) )
348 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
350 if ( !wxEndsWithPathSeparator(buf
) )
352 buf
+= wxFILE_SEP_PATH
;
360 wxFileExists (const wxString
& filename
)
362 // we must use GetFileAttributes() instead of the ANSI C functions because
363 // it can cope with network (UNC) paths unlike them
364 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
365 DWORD ret
= ::GetFileAttributes(filename
);
367 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
370 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
371 #endif // __WIN32__/!__WIN32__
375 wxIsAbsolutePath (const wxString
& filename
)
377 if (filename
!= wxT(""))
379 #if defined(__WXMAC__) && !defined(__DARWIN__)
380 // Classic or Carbon CodeWarrior like
381 // Carbon with Apple DevTools is Unix like
383 // This seems wrong to me, but there is no fix. since
384 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
385 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
386 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
389 // Unix like or Windows
390 if (filename
[0] == wxT('/'))
394 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
399 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
407 * Strip off any extension (dot something) from end of file,
408 * IF one exists. Inserts zero into buffer.
412 void wxStripExtension(wxChar
*buffer
)
414 int len
= wxStrlen(buffer
);
418 if (buffer
[i
] == wxT('.'))
427 void wxStripExtension(wxString
& buffer
)
429 size_t len
= buffer
.Length();
433 if (buffer
.GetChar(i
) == wxT('.'))
435 buffer
= buffer
.Left(i
);
442 // Destructive removal of /./ and /../ stuff
443 wxChar
*wxRealPath (wxChar
*path
)
446 static const wxChar SEP
= wxT('\\');
447 wxUnix2DosFilename(path
);
449 static const wxChar SEP
= wxT('/');
451 if (path
[0] && path
[1]) {
452 /* MATTHEW: special case "/./x" */
454 if (path
[2] == SEP
&& path
[1] == wxT('.'))
462 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
465 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
470 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
471 && (q
- 1 <= path
|| q
[-1] != SEP
))
474 if (path
[0] == wxT('\0'))
480 /* Check that path[2] is NULL! */
481 else if (path
[1] == wxT(':') && !path
[2])
490 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
499 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
501 if (filename
== wxT(""))
502 return (wxChar
*) NULL
;
504 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
505 wxChar buf
[_MAXPATHLEN
];
507 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
508 wxChar ch
= buf
[wxStrlen(buf
) - 1];
510 if (ch
!= wxT('\\') && ch
!= wxT('/'))
511 wxStrcat(buf
, wxT("\\"));
514 wxStrcat(buf
, wxT("/"));
516 wxStrcat(buf
, wxFileFunctionsBuffer
);
517 return MYcopystring( wxRealPath(buf
) );
519 return MYcopystring( wxFileFunctionsBuffer
);
525 ~user/ => user's home dir
526 If the environment variable a = "foo" and b = "bar" then:
543 /* input name in name, pathname output to buf. */
545 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
547 register wxChar
*d
, *s
, *nm
;
548 wxChar lnm
[_MAXPATHLEN
];
551 // Some compilers don't like this line.
552 // const wxChar trimchars[] = wxT("\n \t");
555 trimchars
[0] = wxT('\n');
556 trimchars
[1] = wxT(' ');
557 trimchars
[2] = wxT('\t');
561 const wxChar SEP
= wxT('\\');
563 const wxChar SEP
= wxT('/');
566 if (name
== NULL
|| *name
== wxT('\0'))
568 nm
= MYcopystring(name
); // Make a scratch copy
571 /* Skip leading whitespace and cr */
572 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
574 /* And strip off trailing whitespace and cr */
575 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
576 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
584 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
587 /* Expand inline environment variables */
605 while ((*d
++ = *s
) != 0) {
607 if (*s
== wxT('\\')) {
608 if ((*(d
- 1) = *++s
)) {
617 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
619 if (*s
++ == wxT('$'))
622 register wxChar
*start
= d
;
623 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
624 register wxChar
*value
;
625 while ((*d
++ = *s
) != 0)
626 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
631 value
= wxGetenv(braces
? start
+ 1 : start
);
633 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
645 /* Expand ~ and ~user */
647 if (nm
[0] == wxT('~') && !q
)
650 if (nm
[1] == SEP
|| nm
[1] == 0)
652 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
653 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
658 { /* ~user/filename */
659 register wxChar
*nnm
;
660 register wxChar
*home
;
661 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
665 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
666 was_sep
= (*s
== SEP
);
667 nnm
= *s
? s
+ 1 : s
;
669 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
670 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
671 if (was_sep
) /* replace only if it was there: */
682 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
684 while (wxT('\0') != (*d
++ = *s
++))
687 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
691 while ((*d
++ = *s
++) != 0)
695 delete[] nm_tmp
; // clean up alloc
696 /* Now clean up the buffer */
697 return wxRealPath(buf
);
700 /* Contract Paths to be build upon an environment variable
703 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
705 The call wxExpandPath can convert these back!
708 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
710 static wxChar dest
[_MAXPATHLEN
];
712 if (filename
== wxT(""))
713 return (wxChar
*) NULL
;
715 wxStrcpy (dest
, WXSTRINGCAST filename
);
717 wxUnix2DosFilename(dest
);
720 // Handle environment
721 const wxChar
*val
= (const wxChar
*) NULL
;
722 wxChar
*tcp
= (wxChar
*) NULL
;
723 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
724 (tcp
= wxStrstr (dest
, val
)) != NULL
)
726 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
729 wxStrcpy (tcp
, WXSTRINGCAST envname
);
730 wxStrcat (tcp
, wxT("}"));
731 wxStrcat (tcp
, wxFileFunctionsBuffer
);
734 // Handle User's home (ignore root homes!)
736 if ((val
= wxGetUserHome (user
)) != NULL
&&
737 (len
= wxStrlen(val
)) > 2 &&
738 wxStrncmp(dest
, val
, len
) == 0)
740 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
742 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
743 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
744 wxStrcpy (dest
, wxFileFunctionsBuffer
);
750 // Return just the filename, not the path (basename)
751 wxChar
*wxFileNameFromPath (wxChar
*path
)
754 wxString n
= wxFileNameFromPath(p
);
756 return path
+ p
.length() - n
.length();
759 wxString
wxFileNameFromPath (const wxString
& path
)
762 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
764 wxString fullname
= name
;
767 fullname
<< wxFILE_SEP_EXT
<< ext
;
773 // Return just the directory, or NULL if no directory
775 wxPathOnly (wxChar
*path
)
779 static wxChar buf
[_MAXPATHLEN
];
782 wxStrcpy (buf
, path
);
784 int l
= wxStrlen(path
);
787 // Search backward for a backward or forward slash
790 #if defined(__WXMAC__) && !defined(__DARWIN__)
791 // Classic or Carbon CodeWarrior like
792 // Carbon with Apple DevTools is Unix like
793 if (path
[i
] == wxT(':') )
799 // Unix like or Windows
800 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
807 if (path
[i
] == wxT(']'))
816 #if defined(__WXMSW__) || defined(__WXPM__)
817 // Try Drive specifier
818 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
820 // A:junk --> A:. (since A:.\junk Not A:\junk)
827 return (wxChar
*) NULL
;
830 // Return just the directory, or NULL if no directory
831 wxString
wxPathOnly (const wxString
& path
)
835 wxChar buf
[_MAXPATHLEN
];
838 wxStrcpy (buf
, WXSTRINGCAST path
);
840 int l
= path
.Length();
843 // Search backward for a backward or forward slash
846 #if defined(__WXMAC__) && !defined(__DARWIN__)
847 // Classic or Carbon CodeWarrior like
848 // Carbon with Apple DevTools is Unix like
849 if (path
[i
] == wxT(':') )
852 return wxString(buf
);
855 // Unix like or Windows
856 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
859 return wxString(buf
);
863 if (path
[i
] == wxT(']'))
866 return wxString(buf
);
872 #if defined(__WXMSW__) || defined(__WXPM__)
873 // Try Drive specifier
874 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
876 // A:junk --> A:. (since A:.\junk Not A:\junk)
879 return wxString(buf
);
883 return wxString(wxT(""));
886 // Utility for converting delimiters in DOS filenames to UNIX style
887 // and back again - or we get nasty problems with delimiters.
888 // Also, convert to lower case, since case is significant in UNIX.
890 #if defined(__WXMAC__)
891 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
898 Boolean isDirectory
= FALSE
;
899 Str255 theParentPath
= "\p";
900 FSSpec theParentSpec
;
902 char theFileName
[FILENAME_MAX
];
903 char thePath
[FILENAME_MAX
];
907 // GD: Separate file name from path and make a FSRef to the parent
908 // directory. This is necessary since FSRefs cannot reference files
909 // that have not yet been created.
910 // Based on example code from Apple Technical Note TN2022
911 // http://developer.apple.com/technotes/tn/tn2022.html
913 // check whether we are converting a directory
914 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
915 // count length of file name
916 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
918 // prepend path separator since it will later be appended to the path
919 theFileName
[0] = wxFILE_SEP_PATH
;
920 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
921 theFileName
[j
- i
] = spec
->name
[j
];
923 theFileName
[j
- i
] = '\0';
925 for (j
= 1; j
<= i
; j
++) {
926 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
928 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
929 if (theErr
== noErr
) {
930 // convert the FSSpec to an FSRef
931 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
933 if (theErr
== noErr
) {
934 // get the POSIX path associated with the FSRef
935 theStatus
= FSRefMakePath(&theParentRef
,
936 (UInt8
*)thePath
, sizeof(thePath
));
938 if (theStatus
== noErr
) {
939 // append file name to path
940 // includes previously prepended path separator
941 strcat(thePath
, theFileName
);
944 // create path string for return value
945 wxString
result( thePath
) ;
950 // get length of path and allocate handle
951 FSpGetFullPath( spec
, &length
, &myPath
) ;
952 ::SetHandleSize( myPath
, length
+ 1 ) ;
954 (*myPath
)[length
] = 0 ;
955 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
956 (*myPath
)[length
-1] = 0 ;
958 // create path string for return value
959 wxString result
= wxMacMakeStringFromCString( *myPath
) ;
961 // free allocated handle
962 ::HUnlock( myPath
) ;
963 ::DisposeHandle( myPath
) ;
969 // Mac file names are POSIX (Unix style) under Darwin
970 // therefore the conversion functions below are not needed
972 static wxChar sMacFileNameConversion
[ 1000 ] ;
973 static char scMacFileNameConversion
[ 1000 ] ;
976 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
978 OSStatus err
= noErr
;
982 // get the FSRef associated with the POSIX path
983 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
984 // convert the FSRef to an FSSpec
985 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
987 if ( strchr( path
, ':' ) == NULL
)
989 // try whether it is a volume / or a mounted volume
990 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
991 scMacFileNameConversion
[998] = 0 ;
992 strcat( scMacFileNameConversion
, ":" ) ;
993 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
997 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
1003 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
1005 return wxMacFilename2FSSpec( wxMacStringToCString( wxString( path
) ) , spec
) ;
1011 wxString
wxMac2UnixFilename (const wxChar
*str
)
1013 wxChar
*s
= sMacFileNameConversion
;
1014 wxStrcpy( s
, str
) ;
1017 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1028 *s
= wxTolower(*s
); // Case INDEPENDENT
1032 return wxString(sMacFileNameConversion
) ;
1035 wxString
wxUnix2MacFilename (const wxChar
*str
)
1037 wxChar
*s
= sMacFileNameConversion
;
1038 wxStrcpy( s
, str
) ;
1043 // relative path , since it goes on with slash which is translated to a :
1044 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1046 else if ( *s
== '/' )
1048 // absolute path -> on mac just start with the drive name
1049 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1053 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1057 if (*s
== '/' || *s
== '\\')
1059 // convert any back-directory situations
1060 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1063 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1071 return wxString(sMacFileNameConversion
) ;
1074 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1076 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1079 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1081 wxString var
= wxUnix2MacFilename( path
) ;
1082 wxMacFilename2FSSpec( var
, spec
) ;
1084 #endif // ! __DARWIN__
1089 wxDos2UnixFilename (wxChar
*s
)
1098 *s
= wxTolower (*s
); // Case INDEPENDENT
1105 #if defined(__WXMSW__) || defined(__WXPM__)
1106 wxUnix2DosFilename (wxChar
*s
)
1108 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1111 // Yes, I really mean this to happen under DOS only! JACS
1112 #if defined(__WXMSW__) || defined(__WXPM__)
1123 // Concatenate two files to form third
1125 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1128 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1131 FILE *fp1
= (FILE *) NULL
;
1132 FILE *fp2
= (FILE *) NULL
;
1133 FILE *fp3
= (FILE *) NULL
;
1134 // Open the inputs and outputs
1135 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1136 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1137 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1149 while ((ch
= getc (fp1
)) != EOF
)
1150 (void) putc (ch
, fp3
);
1153 while ((ch
= getc (fp2
)) != EOF
)
1154 (void) putc (ch
, fp3
);
1158 bool result
= wxRenameFile(outfile
, file3
);
1164 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1166 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1167 // CopyFile() copies file attributes and modification time too, so use it
1168 // instead of our code if available
1170 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1171 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1173 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1174 file1
.c_str(), file2
.c_str());
1178 #elif defined(__WXPM__)
1179 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1184 // get permissions of file1
1185 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1187 // the file probably doesn't exist or we haven't the rights to read
1189 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1194 // open file1 for reading
1195 wxFile
fileIn(file1
, wxFile::read
);
1196 if ( !fileIn
.IsOpened() )
1199 // remove file2, if it exists. This is needed for creating
1200 // file2 with the correct permissions in the next step
1201 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1203 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1209 // reset the umask as we want to create the file with exactly the same
1210 // permissions as the original one
1211 mode_t oldUmask
= umask( 0 );
1214 // create file2 with the same permissions than file1 and open it for
1218 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1222 /// restore the old umask
1226 // copy contents of file1 to file2
1231 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1232 if ( fileIn
.Error() )
1239 if ( fileOut
.Write(buf
, count
) < count
)
1243 // we can expect fileIn to be closed successfully, but we should ensure
1244 // that fileOut was closed as some write errors (disk full) might not be
1245 // detected before doing this
1246 if ( !fileIn
.Close() || !fileOut
.Close() )
1249 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1250 // no chmod in VA. Should be some permission API for HPFS386 partitions
1252 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1254 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1258 #endif // OS/2 || Mac
1259 #endif // __WXMSW__ && __WIN32__
1265 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1267 // Normal system call
1268 if ( wxRename (file1
, file2
) == 0 )
1272 if (wxCopyFile(file1
, file2
)) {
1273 wxRemoveFile(file1
);
1280 bool wxRemoveFile(const wxString
& file
)
1282 #if defined(__VISUALC__) \
1283 || defined(__BORLANDC__) \
1284 || defined(__WATCOMC__) \
1285 || defined(__GNUWIN32__)
1286 int res
= wxRemove(file
);
1287 #elif defined(__WXMAC__)
1288 int res
= unlink(wxFNCONV(file
));
1290 int res
= unlink(OS_FILENAME(file
));
1296 bool wxMkdir(const wxString
& dir
, int perm
)
1298 #if defined(__WXMAC__) && !defined(__UNIX__)
1299 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1301 const wxChar
*dirname
= dir
.c_str();
1303 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1304 // for the GNU compiler
1305 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1307 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1309 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1311 #elif defined(__WXPM__)
1312 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1313 #elif defined(__DOS__)
1314 #if defined(__WATCOMC__)
1316 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1317 #elif defined(__DJGPP__)
1318 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1320 #error "Unsupported DOS compiler!"
1322 #else // !MSW, !DOS and !OS/2 VAC++
1324 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1327 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1336 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1339 return FALSE
; //to be changed since rmdir exists in VMS7.x
1340 #elif defined(__WXPM__)
1341 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1345 return FALSE
; // What to do?
1347 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1353 // does the path exists? (may have or not '/' or '\\' at the end)
1354 bool wxPathExists(const wxChar
*pszPathName
)
1356 wxString
strPath(pszPathName
);
1359 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1360 // so remove all trailing backslashes from the path - but don't do this for
1361 // the pathes "d:\" (which are different from "d:") nor for just "\"
1362 while ( wxEndsWithPathSeparator(strPath
) )
1364 size_t len
= strPath
.length();
1365 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1368 strPath
.Truncate(len
- 1);
1370 #endif // __WINDOWS__
1372 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1373 // stat() can't cope with network paths
1374 DWORD ret
= ::GetFileAttributes(strPath
);
1376 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1380 #ifndef __VISAGECPP__
1381 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1383 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1384 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1387 #endif // __WIN32__/!__WIN32__
1390 // Get a temporary filename, opening and closing the file.
1391 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1393 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1394 if ( filename
.empty() )
1398 wxStrcpy(buf
, filename
);
1400 buf
= MYcopystring(filename
);
1405 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1407 buf
= wxFileName::CreateTempFileName(prefix
);
1409 return !buf
.empty();
1412 // Get first file name matching given wild card.
1414 static wxDir
*gs_dir
= NULL
;
1415 static wxString gs_dirPath
;
1417 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1419 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1420 if ( gs_dirPath
.IsEmpty() )
1421 gs_dirPath
= wxT(".");
1422 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1423 gs_dirPath
<< wxFILE_SEP_PATH
;
1427 gs_dir
= new wxDir(gs_dirPath
);
1429 if ( !gs_dir
->IsOpened() )
1431 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1432 return wxEmptyString
;
1438 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1439 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1440 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1444 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1445 if ( result
.IsEmpty() )
1451 return gs_dirPath
+ result
;
1454 wxString
wxFindNextFile()
1456 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1459 gs_dir
->GetNext(&result
);
1461 if ( result
.IsEmpty() )
1467 return gs_dirPath
+ result
;
1471 // Get current working directory.
1472 // If buf is NULL, allocates space using new, else
1474 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1478 buf
= new wxChar
[sz
+ 1];
1483 // for the compilers which have Unicode version of _getcwd(), call it
1484 // directly, for the others call the ANSI version and do the translation
1487 #else // wxUSE_UNICODE
1488 bool needsANSI
= TRUE
;
1490 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1491 // This is not legal code as the compiler
1492 // is allowed destroy the wxCharBuffer.
1493 // wxCharBuffer c_buffer(sz);
1494 // char *cbuf = (char*)(const char*)c_buffer;
1495 char cbuf
[_MAXPATHLEN
];
1499 #if wxUSE_UNICODE_MSLU
1500 if ( wxGetOsVersion() != wxWIN95
)
1502 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1505 ok
= _wgetcwd(buf
, sz
) != NULL
;
1511 #endif // wxUSE_UNICODE
1513 #if defined(_MSC_VER) || defined(__MINGW32__)
1514 ok
= _getcwd(cbuf
, sz
) != NULL
;
1515 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1520 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1522 pb
.ioRefNum
= LMGetCurApRefNum();
1524 error
= PBGetFCBInfoSync(&pb
);
1525 if ( error
== noErr
)
1527 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1528 cwdSpec
.parID
= pb
.ioFCBParID
;
1529 cwdSpec
.name
[0] = 0 ;
1530 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1531 wxStrcpy( buf
, res
) ;
1538 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1540 rc
= ::DosQueryCurrentDir( 0 // current drive
1545 #else // !Win32/VC++ !Mac !OS2
1546 ok
= getcwd(cbuf
, sz
) != NULL
;
1549 #if wxUSE_UNICODE && !defined(__WXMAC__)
1550 // finally convert the result to Unicode if needed
1551 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1552 #endif // wxUSE_UNICODE
1557 wxLogSysError(_("Failed to get the working directory"));
1559 // VZ: the old code used to return "." on error which didn't make any
1560 // sense at all to me - empty string is a better error indicator
1561 // (NULL might be even better but I'm afraid this could lead to
1562 // problems with the old code assuming the return is never NULL)
1565 else // ok, but we might need to massage the path into the right format
1568 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1569 // with / deliminers. We don't like that.
1570 for (wxChar
*ch
= buf
; *ch
; ch
++)
1572 if (*ch
== wxT('/'))
1577 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1578 // he needs Unix as opposed to Win32 pathnames
1579 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1580 // another example of DOS/Unix mix (Cygwin)
1581 wxString pathUnix
= buf
;
1582 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1583 #endif // __CYGWIN__
1595 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1596 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1597 wxString
str( buffer
);
1603 bool wxSetWorkingDirectory(const wxString
& d
)
1605 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1606 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1607 #elif defined(__WXPM__)
1608 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1609 #elif defined(__WINDOWS__)
1612 return (bool)(SetCurrentDirectory(d
) != 0);
1614 // Must change drive, too.
1615 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1618 wxChar firstChar
= d
[0];
1622 firstChar
= firstChar
- 32;
1624 // To a drive number
1625 unsigned int driveNo
= firstChar
- 64;
1628 unsigned int noDrives
;
1629 _dos_setdrive(driveNo
, &noDrives
);
1632 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1640 // Get the OS directory if appropriate (such as the Windows directory).
1641 // On non-Windows platform, probably just return the empty string.
1642 wxString
wxGetOSDirectory()
1644 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1646 GetWindowsDirectory(buf
, 256);
1647 return wxString(buf
);
1648 #elif defined(__WXMAC__)
1649 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1651 return wxEmptyString
;
1655 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1657 size_t len
= wxStrlen(pszFileName
);
1659 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1662 // find a file in a list of directories, returns FALSE if not found
1663 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1665 // we assume that it's not empty
1666 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1667 _T("empty file name in wxFindFileInPath"));
1669 // skip path separator in the beginning of the file name if present
1670 if ( wxIsPathSeparator(*pszFile
) )
1673 // copy the path (strtok will modify it)
1674 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1675 wxStrcpy(szPath
, pszPath
);
1678 wxChar
*pc
, *save_ptr
;
1679 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1681 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1683 // search for the file in this directory
1685 if ( !wxEndsWithPathSeparator(pc
) )
1686 strFile
+= wxFILE_SEP_PATH
;
1689 if ( wxFileExists(strFile
) ) {
1695 // suppress warning about unused variable save_ptr when wxStrtok() is a
1696 // macro which throws away its third argument
1701 return pc
!= NULL
; // if TRUE => we breaked from the loop
1704 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1709 // it can be empty, but it shouldn't be NULL
1710 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1712 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1715 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1718 wxStat( filename
, &buf
);
1720 return buf
.st_mtime
;
1724 //------------------------------------------------------------------------
1725 // wild character routines
1726 //------------------------------------------------------------------------
1728 bool wxIsWild( const wxString
& pattern
)
1730 wxString tmp
= pattern
;
1731 wxChar
*pat
= WXSTRINGCAST(tmp
);
1736 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1747 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1749 * The match procedure is public domain code (from ircII's reg.c)
1752 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1756 /* Match if both are empty. */
1760 const wxChar
*m
= pat
.c_str(),
1771 if (dot_special
&& (*n
== wxT('.')))
1773 /* Never match so that hidden Unix files
1774 * are never found. */
1788 else if (*m
== wxT('?'))
1796 if (*m
== wxT('\\'))
1799 /* Quoting "nothing" is a bad thing */
1806 * If we are out of both strings or we just
1807 * saw a wildcard, then we can say we have a
1818 * We could check for *n == NULL at this point, but
1819 * since it's more common to have a character there,
1820 * check to see if they match first (m and n) and
1821 * then if they don't match, THEN we can check for
1839 * If there are no more characters in the
1840 * string, but we still need to find another
1841 * character (*m != NULL), then it will be
1842 * impossible to match it
1849 if (*np
== wxT(' '))
1875 #pragma warning(default:4706) // assignment within conditional expression