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 void wxPathList::Add (const wxString
& path
)
220 wxStringList::Add (WXSTRINGCAST path
);
223 // Add paths e.g. from the PATH environment variable
224 void wxPathList::AddEnvList (const wxString
& envVariable
)
226 static const wxChar PATH_TOKS
[] =
229 The space has been removed from the tokenizers, otherwise a
230 path such as "C:\Program Files" would be split into 2 paths:
231 "C:\Program" and "Files"
233 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
234 wxT(";"); // Don't seperate with colon in DOS (used for drive)
239 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
242 wxChar
*s
= copystring (val
);
243 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
250 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
258 // suppress warning about unused variable save_ptr when wxStrtok() is a
259 // macro which throws away its third argument
266 // Given a full filename (with path), ensure that that file can
267 // be accessed again USING FILENAME ONLY by adding the path
268 // to the list if not already there.
269 void wxPathList::EnsureFileAccessible (const wxString
& path
)
271 wxString
path_only(wxPathOnly(path
));
272 if ( !path_only
.IsEmpty() )
274 if ( !Member(path_only
) )
279 bool wxPathList::Member (const wxString
& path
)
281 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
283 wxString
path2( node
->GetData() );
285 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
287 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
289 // Case sensitive File System
290 path
.CompareTo (path2
) == 0
298 wxString
wxPathList::FindValidPath (const wxString
& file
)
300 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
301 return wxString(wxFileFunctionsBuffer
);
303 wxChar buf
[_MAXPATHLEN
];
304 wxStrcpy(buf
, wxFileFunctionsBuffer
);
306 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
307 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
309 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
311 wxChar
*path
= node
->GetData();
312 wxStrcpy (wxFileFunctionsBuffer
, path
);
313 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
314 if (ch
!= wxT('\\') && ch
!= wxT('/'))
315 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
316 wxStrcat (wxFileFunctionsBuffer
, filename
);
318 wxUnix2DosFilename (wxFileFunctionsBuffer
);
320 if (wxFileExists (wxFileFunctionsBuffer
))
322 return wxString(wxFileFunctionsBuffer
); // Found!
326 return wxEmptyString
; // Not found
329 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
331 wxString f
= FindValidPath(file
);
332 if ( wxIsAbsolutePath(f
) )
336 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
338 if ( !wxEndsWithPathSeparator(buf
) )
340 buf
+= wxFILE_SEP_PATH
;
348 wxFileExists (const wxString
& filename
)
350 // we must use GetFileAttributes() instead of the ANSI C functions because
351 // it can cope with network (UNC) paths unlike them
352 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
353 DWORD ret
= ::GetFileAttributes(filename
);
355 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
358 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
359 #endif // __WIN32__/!__WIN32__
363 wxIsAbsolutePath (const wxString
& filename
)
365 if (filename
!= wxT(""))
367 #if defined(__WXMAC__) && !defined(__DARWIN__)
368 // Classic or Carbon CodeWarrior like
369 // Carbon with Apple DevTools is Unix like
371 // This seems wrong to me, but there is no fix. since
372 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
373 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
374 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
377 // Unix like or Windows
378 if (filename
[0] == wxT('/'))
382 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
387 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
395 * Strip off any extension (dot something) from end of file,
396 * IF one exists. Inserts zero into buffer.
400 void wxStripExtension(wxChar
*buffer
)
402 int len
= wxStrlen(buffer
);
406 if (buffer
[i
] == wxT('.'))
415 void wxStripExtension(wxString
& buffer
)
417 size_t len
= buffer
.Length();
421 if (buffer
.GetChar(i
) == wxT('.'))
423 buffer
= buffer
.Left(i
);
430 // Destructive removal of /./ and /../ stuff
431 wxChar
*wxRealPath (wxChar
*path
)
434 static const wxChar SEP
= wxT('\\');
435 wxUnix2DosFilename(path
);
437 static const wxChar SEP
= wxT('/');
439 if (path
[0] && path
[1]) {
440 /* MATTHEW: special case "/./x" */
442 if (path
[2] == SEP
&& path
[1] == wxT('.'))
450 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
453 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
458 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
459 && (q
- 1 <= path
|| q
[-1] != SEP
))
462 if (path
[0] == wxT('\0'))
468 /* Check that path[2] is NULL! */
469 else if (path
[1] == wxT(':') && !path
[2])
478 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
487 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
489 if (filename
== wxT(""))
490 return (wxChar
*) NULL
;
492 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
493 wxChar buf
[_MAXPATHLEN
];
495 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
496 wxChar ch
= buf
[wxStrlen(buf
) - 1];
498 if (ch
!= wxT('\\') && ch
!= wxT('/'))
499 wxStrcat(buf
, wxT("\\"));
502 wxStrcat(buf
, wxT("/"));
504 wxStrcat(buf
, wxFileFunctionsBuffer
);
505 return copystring( wxRealPath(buf
) );
507 return copystring( wxFileFunctionsBuffer
);
513 ~user/ => user's home dir
514 If the environment variable a = "foo" and b = "bar" then:
531 /* input name in name, pathname output to buf. */
533 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
535 register wxChar
*d
, *s
, *nm
;
536 wxChar lnm
[_MAXPATHLEN
];
539 // Some compilers don't like this line.
540 // const wxChar trimchars[] = wxT("\n \t");
543 trimchars
[0] = wxT('\n');
544 trimchars
[1] = wxT(' ');
545 trimchars
[2] = wxT('\t');
549 const wxChar SEP
= wxT('\\');
551 const wxChar SEP
= wxT('/');
554 if (name
== NULL
|| *name
== wxT('\0'))
556 nm
= copystring(name
); // Make a scratch copy
559 /* Skip leading whitespace and cr */
560 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
562 /* And strip off trailing whitespace and cr */
563 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
564 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
572 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
575 /* Expand inline environment variables */
593 while ((*d
++ = *s
) != 0) {
595 if (*s
== wxT('\\')) {
596 if ((*(d
- 1) = *++s
)) {
605 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
607 if (*s
++ == wxT('$'))
610 register wxChar
*start
= d
;
611 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
612 register wxChar
*value
;
613 while ((*d
++ = *s
) != 0)
614 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
619 value
= wxGetenv(braces
? start
+ 1 : start
);
621 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
633 /* Expand ~ and ~user */
635 if (nm
[0] == wxT('~') && !q
)
638 if (nm
[1] == SEP
|| nm
[1] == 0)
640 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
641 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
646 { /* ~user/filename */
647 register wxChar
*nnm
;
648 register wxChar
*home
;
649 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
653 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
654 was_sep
= (*s
== SEP
);
655 nnm
= *s
? s
+ 1 : s
;
657 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
658 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
659 if (was_sep
) /* replace only if it was there: */
670 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
672 while (wxT('\0') != (*d
++ = *s
++))
675 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
679 while ((*d
++ = *s
++) != 0)
683 delete[] nm_tmp
; // clean up alloc
684 /* Now clean up the buffer */
685 return wxRealPath(buf
);
688 /* Contract Paths to be build upon an environment variable
691 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
693 The call wxExpandPath can convert these back!
696 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
698 static wxChar dest
[_MAXPATHLEN
];
700 if (filename
== wxT(""))
701 return (wxChar
*) NULL
;
703 wxStrcpy (dest
, WXSTRINGCAST filename
);
705 wxUnix2DosFilename(dest
);
708 // Handle environment
709 const wxChar
*val
= (const wxChar
*) NULL
;
710 wxChar
*tcp
= (wxChar
*) NULL
;
711 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
712 (tcp
= wxStrstr (dest
, val
)) != NULL
)
714 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
717 wxStrcpy (tcp
, WXSTRINGCAST envname
);
718 wxStrcat (tcp
, wxT("}"));
719 wxStrcat (tcp
, wxFileFunctionsBuffer
);
722 // Handle User's home (ignore root homes!)
724 if ((val
= wxGetUserHome (user
)) != NULL
&&
725 (len
= wxStrlen(val
)) > 2 &&
726 wxStrncmp(dest
, val
, len
) == 0)
728 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
730 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
731 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
732 wxStrcpy (dest
, wxFileFunctionsBuffer
);
738 // Return just the filename, not the path (basename)
739 wxChar
*wxFileNameFromPath (wxChar
*path
)
742 wxString n
= wxFileNameFromPath(p
);
744 return path
+ p
.length() - n
.length();
747 wxString
wxFileNameFromPath (const wxString
& path
)
750 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
752 wxString fullname
= name
;
755 fullname
<< wxFILE_SEP_EXT
<< ext
;
761 // Return just the directory, or NULL if no directory
763 wxPathOnly (wxChar
*path
)
767 static wxChar buf
[_MAXPATHLEN
];
770 wxStrcpy (buf
, path
);
772 int l
= wxStrlen(path
);
775 // Search backward for a backward or forward slash
778 #if defined(__WXMAC__) && !defined(__DARWIN__)
779 // Classic or Carbon CodeWarrior like
780 // Carbon with Apple DevTools is Unix like
781 if (path
[i
] == wxT(':') )
787 // Unix like or Windows
788 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
795 if (path
[i
] == wxT(']'))
804 #if defined(__WXMSW__) || defined(__WXPM__)
805 // Try Drive specifier
806 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
808 // A:junk --> A:. (since A:.\junk Not A:\junk)
815 return (wxChar
*) NULL
;
818 // Return just the directory, or NULL if no directory
819 wxString
wxPathOnly (const wxString
& path
)
823 wxChar buf
[_MAXPATHLEN
];
826 wxStrcpy (buf
, WXSTRINGCAST path
);
828 int l
= path
.Length();
831 // Search backward for a backward or forward slash
834 #if defined(__WXMAC__) && !defined(__DARWIN__)
835 // Classic or Carbon CodeWarrior like
836 // Carbon with Apple DevTools is Unix like
837 if (path
[i
] == wxT(':') )
840 return wxString(buf
);
843 // Unix like or Windows
844 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
847 return wxString(buf
);
851 if (path
[i
] == wxT(']'))
854 return wxString(buf
);
860 #if defined(__WXMSW__) || defined(__WXPM__)
861 // Try Drive specifier
862 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
864 // A:junk --> A:. (since A:.\junk Not A:\junk)
867 return wxString(buf
);
871 return wxString(wxT(""));
874 // Utility for converting delimiters in DOS filenames to UNIX style
875 // and back again - or we get nasty problems with delimiters.
876 // Also, convert to lower case, since case is significant in UNIX.
878 #if defined(__WXMAC__)
879 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
886 Boolean isDirectory
= FALSE
;
887 Str255 theParentPath
= "\p";
888 FSSpec theParentSpec
;
890 char theFileName
[FILENAME_MAX
];
891 char thePath
[FILENAME_MAX
];
895 // GD: Separate file name from path and make a FSRef to the parent
896 // directory. This is necessary since FSRefs cannot reference files
897 // that have not yet been created.
898 // Based on example code from Apple Technical Note TN2022
899 // http://developer.apple.com/technotes/tn/tn2022.html
901 // check whether we are converting a directory
902 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
903 // count length of file name
904 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
906 // prepend path separator since it will later be appended to the path
907 theFileName
[0] = wxFILE_SEP_PATH
;
908 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
909 theFileName
[j
- i
] = spec
->name
[j
];
911 theFileName
[j
- i
] = '\0';
913 for (j
= 1; j
<= i
; j
++) {
914 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
916 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
917 if (theErr
== noErr
) {
918 // convert the FSSpec to an FSRef
919 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
921 if (theErr
== noErr
) {
922 // get the POSIX path associated with the FSRef
923 theStatus
= FSRefMakePath(&theParentRef
,
924 (UInt8
*)thePath
, sizeof(thePath
));
926 if (theStatus
== noErr
) {
927 // append file name to path
928 // includes previously prepended path separator
929 strcat(thePath
, theFileName
);
932 // create path string for return value
933 wxString
result( thePath
) ;
938 // get length of path and allocate handle
939 FSpGetFullPath( spec
, &length
, &myPath
) ;
940 ::SetHandleSize( myPath
, length
+ 1 ) ;
942 (*myPath
)[length
] = 0 ;
943 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
944 (*myPath
)[length
-1] = 0 ;
946 // create path string for return value
947 wxString result
= wxMacMakeStringFromCString( *myPath
) ;
949 // free allocated handle
950 ::HUnlock( myPath
) ;
951 ::DisposeHandle( myPath
) ;
957 // Mac file names are POSIX (Unix style) under Darwin
958 // therefore the conversion functions below are not needed
960 static wxChar sMacFileNameConversion
[ 1000 ] ;
961 static char scMacFileNameConversion
[ 1000 ] ;
964 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
966 OSStatus err
= noErr
;
970 // get the FSRef associated with the POSIX path
971 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
972 // convert the FSRef to an FSSpec
973 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
975 if ( strchr( path
, ':' ) == NULL
)
977 // try whether it is a volume / or a mounted volume
978 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
979 scMacFileNameConversion
[998] = 0 ;
980 strcat( scMacFileNameConversion
, ":" ) ;
981 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
985 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
991 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
993 return wxMacFilename2FSSpec( wxMacStringToCString( wxString( path
) ) , spec
) ;
999 wxString
wxMac2UnixFilename (const wxChar
*str
)
1001 wxChar
*s
= sMacFileNameConversion
;
1002 wxStrcpy( s
, str
) ;
1005 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1016 *s
= wxTolower(*s
); // Case INDEPENDENT
1020 return wxString(sMacFileNameConversion
) ;
1023 wxString
wxUnix2MacFilename (const wxChar
*str
)
1025 wxChar
*s
= sMacFileNameConversion
;
1026 wxStrcpy( s
, str
) ;
1031 // relative path , since it goes on with slash which is translated to a :
1032 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1034 else if ( *s
== '/' )
1036 // absolute path -> on mac just start with the drive name
1037 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1041 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1045 if (*s
== '/' || *s
== '\\')
1047 // convert any back-directory situations
1048 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1051 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1059 return wxString(sMacFileNameConversion
) ;
1062 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1064 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1067 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1069 wxString var
= wxUnix2MacFilename( path
) ;
1070 wxMacFilename2FSSpec( var
, spec
) ;
1072 #endif // ! __DARWIN__
1077 wxDos2UnixFilename (wxChar
*s
)
1086 *s
= wxTolower (*s
); // Case INDEPENDENT
1093 #if defined(__WXMSW__) || defined(__WXPM__)
1094 wxUnix2DosFilename (wxChar
*s
)
1096 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1099 // Yes, I really mean this to happen under DOS only! JACS
1100 #if defined(__WXMSW__) || defined(__WXPM__)
1111 // Concatenate two files to form third
1113 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1116 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1119 FILE *fp1
= (FILE *) NULL
;
1120 FILE *fp2
= (FILE *) NULL
;
1121 FILE *fp3
= (FILE *) NULL
;
1122 // Open the inputs and outputs
1123 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1124 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1125 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1137 while ((ch
= getc (fp1
)) != EOF
)
1138 (void) putc (ch
, fp3
);
1141 while ((ch
= getc (fp2
)) != EOF
)
1142 (void) putc (ch
, fp3
);
1146 bool result
= wxRenameFile(outfile
, file3
);
1152 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1154 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1155 // CopyFile() copies file attributes and modification time too, so use it
1156 // instead of our code if available
1158 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1159 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1161 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1162 file1
.c_str(), file2
.c_str());
1166 #elif defined(__WXPM__)
1167 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1172 // get permissions of file1
1173 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1175 // the file probably doesn't exist or we haven't the rights to read
1177 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1182 // open file1 for reading
1183 wxFile
fileIn(file1
, wxFile::read
);
1184 if ( !fileIn
.IsOpened() )
1187 // remove file2, if it exists. This is needed for creating
1188 // file2 with the correct permissions in the next step
1189 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1191 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1197 // reset the umask as we want to create the file with exactly the same
1198 // permissions as the original one
1199 mode_t oldUmask
= umask( 0 );
1202 // create file2 with the same permissions than file1 and open it for
1206 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1210 /// restore the old umask
1214 // copy contents of file1 to file2
1219 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1220 if ( fileIn
.Error() )
1227 if ( fileOut
.Write(buf
, count
) < count
)
1231 // we can expect fileIn to be closed successfully, but we should ensure
1232 // that fileOut was closed as some write errors (disk full) might not be
1233 // detected before doing this
1234 if ( !fileIn
.Close() || !fileOut
.Close() )
1237 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1238 // no chmod in VA. Should be some permission API for HPFS386 partitions
1240 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1242 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1246 #endif // OS/2 || Mac
1247 #endif // __WXMSW__ && __WIN32__
1253 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1255 // Normal system call
1256 if ( wxRename (file1
, file2
) == 0 )
1260 if (wxCopyFile(file1
, file2
)) {
1261 wxRemoveFile(file1
);
1268 bool wxRemoveFile(const wxString
& file
)
1270 #if defined(__VISUALC__) \
1271 || defined(__BORLANDC__) \
1272 || defined(__WATCOMC__) \
1273 || defined(__GNUWIN32__)
1274 int res
= wxRemove(file
);
1275 #elif defined(__WXMAC__)
1276 int res
= unlink(wxFNCONV(file
));
1278 int res
= unlink(OS_FILENAME(file
));
1284 bool wxMkdir(const wxString
& dir
, int perm
)
1286 #if defined(__WXMAC__) && !defined(__UNIX__)
1287 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1289 const wxChar
*dirname
= dir
.c_str();
1291 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1292 // for the GNU compiler
1293 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1295 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1297 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1299 #elif defined(__WXPM__)
1300 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1301 #elif defined(__DOS__)
1302 #if defined(__WATCOMC__)
1304 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1305 #elif defined(__DJGPP__)
1306 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1308 #error "Unsupported DOS compiler!"
1310 #else // !MSW, !DOS and !OS/2 VAC++
1312 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1315 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1324 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1327 return FALSE
; //to be changed since rmdir exists in VMS7.x
1328 #elif defined(__WXPM__)
1329 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1333 return FALSE
; // What to do?
1335 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1341 // does the path exists? (may have or not '/' or '\\' at the end)
1342 bool wxPathExists(const wxChar
*pszPathName
)
1344 wxString
strPath(pszPathName
);
1347 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1348 // so remove all trailing backslashes from the path - but don't do this for
1349 // the pathes "d:\" (which are different from "d:") nor for just "\"
1350 while ( wxEndsWithPathSeparator(strPath
) )
1352 size_t len
= strPath
.length();
1353 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1356 strPath
.Truncate(len
- 1);
1358 #endif // __WINDOWS__
1360 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1361 // stat() can't cope with network paths
1362 DWORD ret
= ::GetFileAttributes(strPath
);
1364 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1368 #ifndef __VISAGECPP__
1369 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1371 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1372 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1375 #endif // __WIN32__/!__WIN32__
1378 // Get a temporary filename, opening and closing the file.
1379 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1381 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1382 if ( filename
.empty() )
1386 wxStrcpy(buf
, filename
);
1388 buf
= copystring(filename
);
1393 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1395 buf
= wxFileName::CreateTempFileName(prefix
);
1397 return !buf
.empty();
1400 // Get first file name matching given wild card.
1402 static wxDir
*gs_dir
= NULL
;
1403 static wxString gs_dirPath
;
1405 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1407 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1408 if ( gs_dirPath
.IsEmpty() )
1409 gs_dirPath
= wxT(".");
1410 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1411 gs_dirPath
<< wxFILE_SEP_PATH
;
1415 gs_dir
= new wxDir(gs_dirPath
);
1417 if ( !gs_dir
->IsOpened() )
1419 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1420 return wxEmptyString
;
1426 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1427 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1428 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1432 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1433 if ( result
.IsEmpty() )
1439 return gs_dirPath
+ result
;
1442 wxString
wxFindNextFile()
1444 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1447 gs_dir
->GetNext(&result
);
1449 if ( result
.IsEmpty() )
1455 return gs_dirPath
+ result
;
1459 // Get current working directory.
1460 // If buf is NULL, allocates space using new, else
1462 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1466 buf
= new wxChar
[sz
+ 1];
1471 // for the compilers which have Unicode version of _getcwd(), call it
1472 // directly, for the others call the ANSI version and do the translation
1475 #else // wxUSE_UNICODE
1476 bool needsANSI
= TRUE
;
1478 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1479 // This is not legal code as the compiler
1480 // is allowed destroy the wxCharBuffer.
1481 // wxCharBuffer c_buffer(sz);
1482 // char *cbuf = (char*)(const char*)c_buffer;
1483 char cbuf
[_MAXPATHLEN
];
1487 #if wxUSE_UNICODE_MSLU
1488 if ( wxGetOsVersion() != wxWIN95
)
1490 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1493 ok
= _wgetcwd(buf
, sz
) != NULL
;
1499 #endif // wxUSE_UNICODE
1501 #if defined(_MSC_VER) || defined(__MINGW32__)
1502 ok
= _getcwd(cbuf
, sz
) != NULL
;
1503 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1508 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1510 pb
.ioRefNum
= LMGetCurApRefNum();
1512 error
= PBGetFCBInfoSync(&pb
);
1513 if ( error
== noErr
)
1515 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1516 cwdSpec
.parID
= pb
.ioFCBParID
;
1517 cwdSpec
.name
[0] = 0 ;
1518 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1519 wxStrcpy( buf
, res
) ;
1526 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1528 rc
= ::DosQueryCurrentDir( 0 // current drive
1533 #else // !Win32/VC++ !Mac !OS2
1534 ok
= getcwd(cbuf
, sz
) != NULL
;
1537 #if wxUSE_UNICODE && !defined(__WXMAC__)
1538 // finally convert the result to Unicode if needed
1539 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1540 #endif // wxUSE_UNICODE
1545 wxLogSysError(_("Failed to get the working directory"));
1547 // VZ: the old code used to return "." on error which didn't make any
1548 // sense at all to me - empty string is a better error indicator
1549 // (NULL might be even better but I'm afraid this could lead to
1550 // problems with the old code assuming the return is never NULL)
1553 else // ok, but we might need to massage the path into the right format
1556 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1557 // with / deliminers. We don't like that.
1558 for (wxChar
*ch
= buf
; *ch
; ch
++)
1560 if (*ch
== wxT('/'))
1565 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1566 // he needs Unix as opposed to Win32 pathnames
1567 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1568 // another example of DOS/Unix mix (Cygwin)
1569 wxString pathUnix
= buf
;
1570 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1571 #endif // __CYGWIN__
1583 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1584 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1585 wxString
str( buffer
);
1591 bool wxSetWorkingDirectory(const wxString
& d
)
1593 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1594 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1595 #elif defined(__WXPM__)
1596 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1597 #elif defined(__WINDOWS__)
1600 return (bool)(SetCurrentDirectory(d
) != 0);
1602 // Must change drive, too.
1603 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1606 wxChar firstChar
= d
[0];
1610 firstChar
= firstChar
- 32;
1612 // To a drive number
1613 unsigned int driveNo
= firstChar
- 64;
1616 unsigned int noDrives
;
1617 _dos_setdrive(driveNo
, &noDrives
);
1620 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1628 // Get the OS directory if appropriate (such as the Windows directory).
1629 // On non-Windows platform, probably just return the empty string.
1630 wxString
wxGetOSDirectory()
1632 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1634 GetWindowsDirectory(buf
, 256);
1635 return wxString(buf
);
1636 #elif defined(__WXMAC__)
1637 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1639 return wxEmptyString
;
1643 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1645 size_t len
= wxStrlen(pszFileName
);
1647 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1650 // find a file in a list of directories, returns FALSE if not found
1651 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1653 // we assume that it's not empty
1654 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1655 _T("empty file name in wxFindFileInPath"));
1657 // skip path separator in the beginning of the file name if present
1658 if ( wxIsPathSeparator(*pszFile
) )
1661 // copy the path (strtok will modify it)
1662 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1663 wxStrcpy(szPath
, pszPath
);
1666 wxChar
*pc
, *save_ptr
;
1667 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1669 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1671 // search for the file in this directory
1673 if ( !wxEndsWithPathSeparator(pc
) )
1674 strFile
+= wxFILE_SEP_PATH
;
1677 if ( wxFileExists(strFile
) ) {
1683 // suppress warning about unused variable save_ptr when wxStrtok() is a
1684 // macro which throws away its third argument
1689 return pc
!= NULL
; // if TRUE => we breaked from the loop
1692 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1697 // it can be empty, but it shouldn't be NULL
1698 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1700 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1703 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1706 wxStat( filename
, &buf
);
1708 return buf
.st_mtime
;
1712 //------------------------------------------------------------------------
1713 // wild character routines
1714 //------------------------------------------------------------------------
1716 bool wxIsWild( const wxString
& pattern
)
1718 wxString tmp
= pattern
;
1719 wxChar
*pat
= WXSTRINGCAST(tmp
);
1724 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1735 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1737 * The match procedure is public domain code (from ircII's reg.c)
1740 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1744 /* Match if both are empty. */
1748 const wxChar
*m
= pat
.c_str(),
1759 if (dot_special
&& (*n
== wxT('.')))
1761 /* Never match so that hidden Unix files
1762 * are never found. */
1776 else if (*m
== wxT('?'))
1784 if (*m
== wxT('\\'))
1787 /* Quoting "nothing" is a bad thing */
1794 * If we are out of both strings or we just
1795 * saw a wildcard, then we can say we have a
1806 * We could check for *n == NULL at this point, but
1807 * since it's more common to have a character there,
1808 * check to see if they match first (m and n) and
1809 * then if they don't match, THEN we can check for
1827 * If there are no more characters in the
1828 * string, but we still need to find another
1829 * character (*m != NULL), then it will be
1830 * impossible to match it
1837 if (*np
== wxT(' '))
1863 #pragma warning(default:4706) // assignment within conditional expression