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"
127 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
129 // note that it must be included after <windows.h>
132 #include <sys/cygwin.h>
136 #include <sys/unistd.h>
138 #endif // __GNUWIN32__
139 #endif // __WINDOWS__
141 // TODO: Borland probably has _wgetcwd as well?
146 // ----------------------------------------------------------------------------
148 // ----------------------------------------------------------------------------
151 #define _MAXPATHLEN 1024
156 # include "MoreFilesX.h"
158 # include "MoreFiles.h"
159 # include "MoreFilesExtras.h"
160 # include "FullPath.h"
161 # include "FSpCompat.h"
165 // ----------------------------------------------------------------------------
167 // ----------------------------------------------------------------------------
169 // MT-FIXME: get rid of this horror and all code using it
170 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
172 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
174 // VisualAge C++ V4.0 cannot have any external linkage const decs
175 // in headers included by more than one primary source
177 const off_t wxInvalidOffset
= (off_t
)-1;
180 // ----------------------------------------------------------------------------
182 // ----------------------------------------------------------------------------
184 // we need to translate Mac filenames before passing them to OS functions
185 #define OS_FILENAME(s) (s.fn_str())
187 // ============================================================================
189 // ============================================================================
191 #ifdef wxNEED_WX_UNISTD_H
193 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
195 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
198 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
200 return access( wxConvFile
.cWX2MB( pathname
), mode
);
203 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
205 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
209 // wxNEED_WX_UNISTD_H
211 // ----------------------------------------------------------------------------
213 // ----------------------------------------------------------------------------
215 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
217 void wxPathList::Add (const wxString
& path
)
219 wxStringList::Add (WXSTRINGCAST path
);
222 // Add paths e.g. from the PATH environment variable
223 void wxPathList::AddEnvList (const wxString
& envVariable
)
225 static const wxChar PATH_TOKS
[] =
228 The space has been removed from the tokenizers, otherwise a
229 path such as "C:\Program Files" would be split into 2 paths:
230 "C:\Program" and "Files"
232 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
233 wxT(";"); // Don't seperate with colon in DOS (used for drive)
238 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
241 wxChar
*s
= copystring (val
);
242 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
249 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
257 // suppress warning about unused variable save_ptr when wxStrtok() is a
258 // macro which throws away its third argument
265 // Given a full filename (with path), ensure that that file can
266 // be accessed again USING FILENAME ONLY by adding the path
267 // to the list if not already there.
268 void wxPathList::EnsureFileAccessible (const wxString
& path
)
270 wxString
path_only(wxPathOnly(path
));
271 if ( !path_only
.IsEmpty() )
273 if ( !Member(path_only
) )
278 bool wxPathList::Member (const wxString
& path
)
280 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
282 wxString
path2( node
->GetData() );
284 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
286 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
288 // Case sensitive File System
289 path
.CompareTo (path2
) == 0
297 wxString
wxPathList::FindValidPath (const wxString
& file
)
299 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
300 return wxString(wxFileFunctionsBuffer
);
302 wxChar buf
[_MAXPATHLEN
];
303 wxStrcpy(buf
, wxFileFunctionsBuffer
);
305 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
306 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
308 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
310 wxChar
*path
= node
->GetData();
311 wxStrcpy (wxFileFunctionsBuffer
, path
);
312 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
313 if (ch
!= wxT('\\') && ch
!= wxT('/'))
314 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
315 wxStrcat (wxFileFunctionsBuffer
, filename
);
317 wxUnix2DosFilename (wxFileFunctionsBuffer
);
319 if (wxFileExists (wxFileFunctionsBuffer
))
321 return wxString(wxFileFunctionsBuffer
); // Found!
325 return wxEmptyString
; // Not found
328 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
330 wxString f
= FindValidPath(file
);
331 if ( wxIsAbsolutePath(f
) )
335 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
337 if ( !wxEndsWithPathSeparator(buf
) )
339 buf
+= wxFILE_SEP_PATH
;
347 wxFileExists (const wxString
& filename
)
349 // we must use GetFileAttributes() instead of the ANSI C functions because
350 // it can cope with network (UNC) paths unlike them
351 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
352 DWORD ret
= ::GetFileAttributes(filename
);
354 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
357 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
358 #endif // __WIN32__/!__WIN32__
362 wxIsAbsolutePath (const wxString
& filename
)
364 if (filename
!= wxT(""))
366 #if defined(__WXMAC__) && !defined(__DARWIN__)
367 // Classic or Carbon CodeWarrior like
368 // Carbon with Apple DevTools is Unix like
370 // This seems wrong to me, but there is no fix. since
371 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
372 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
373 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
376 // Unix like or Windows
377 if (filename
[0] == wxT('/'))
381 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
386 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
394 * Strip off any extension (dot something) from end of file,
395 * IF one exists. Inserts zero into buffer.
399 void wxStripExtension(wxChar
*buffer
)
401 int len
= wxStrlen(buffer
);
405 if (buffer
[i
] == wxT('.'))
414 void wxStripExtension(wxString
& buffer
)
416 size_t len
= buffer
.Length();
420 if (buffer
.GetChar(i
) == wxT('.'))
422 buffer
= buffer
.Left(i
);
429 // Destructive removal of /./ and /../ stuff
430 wxChar
*wxRealPath (wxChar
*path
)
433 static const wxChar SEP
= wxT('\\');
434 wxUnix2DosFilename(path
);
436 static const wxChar SEP
= wxT('/');
438 if (path
[0] && path
[1]) {
439 /* MATTHEW: special case "/./x" */
441 if (path
[2] == SEP
&& path
[1] == wxT('.'))
449 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
452 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
457 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
458 && (q
- 1 <= path
|| q
[-1] != SEP
))
461 if (path
[0] == wxT('\0'))
467 /* Check that path[2] is NULL! */
468 else if (path
[1] == wxT(':') && !path
[2])
477 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
486 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
488 if (filename
== wxT(""))
489 return (wxChar
*) NULL
;
491 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
492 wxChar buf
[_MAXPATHLEN
];
494 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
495 wxChar ch
= buf
[wxStrlen(buf
) - 1];
497 if (ch
!= wxT('\\') && ch
!= wxT('/'))
498 wxStrcat(buf
, wxT("\\"));
501 wxStrcat(buf
, wxT("/"));
503 wxStrcat(buf
, wxFileFunctionsBuffer
);
504 return copystring( wxRealPath(buf
) );
506 return copystring( wxFileFunctionsBuffer
);
512 ~user/ => user's home dir
513 If the environment variable a = "foo" and b = "bar" then:
530 /* input name in name, pathname output to buf. */
532 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
534 register wxChar
*d
, *s
, *nm
;
535 wxChar lnm
[_MAXPATHLEN
];
538 // Some compilers don't like this line.
539 // const wxChar trimchars[] = wxT("\n \t");
542 trimchars
[0] = wxT('\n');
543 trimchars
[1] = wxT(' ');
544 trimchars
[2] = wxT('\t');
548 const wxChar SEP
= wxT('\\');
550 const wxChar SEP
= wxT('/');
553 if (name
== NULL
|| *name
== wxT('\0'))
555 nm
= copystring(name
); // Make a scratch copy
558 /* Skip leading whitespace and cr */
559 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
561 /* And strip off trailing whitespace and cr */
562 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
563 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
571 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
574 /* Expand inline environment variables */
592 while ((*d
++ = *s
) != 0) {
594 if (*s
== wxT('\\')) {
595 if ((*(d
- 1) = *++s
)) {
604 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
606 if (*s
++ == wxT('$'))
609 register wxChar
*start
= d
;
610 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
611 register wxChar
*value
;
612 while ((*d
++ = *s
) != 0)
613 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
618 value
= wxGetenv(braces
? start
+ 1 : start
);
620 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
632 /* Expand ~ and ~user */
634 if (nm
[0] == wxT('~') && !q
)
637 if (nm
[1] == SEP
|| nm
[1] == 0)
639 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
640 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
645 { /* ~user/filename */
646 register wxChar
*nnm
;
647 register wxChar
*home
;
648 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
652 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
653 was_sep
= (*s
== SEP
);
654 nnm
= *s
? s
+ 1 : s
;
656 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
657 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
658 if (was_sep
) /* replace only if it was there: */
669 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
671 while (wxT('\0') != (*d
++ = *s
++))
674 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
678 while ((*d
++ = *s
++) != 0)
682 delete[] nm_tmp
; // clean up alloc
683 /* Now clean up the buffer */
684 return wxRealPath(buf
);
687 /* Contract Paths to be build upon an environment variable
690 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
692 The call wxExpandPath can convert these back!
695 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
697 static wxChar dest
[_MAXPATHLEN
];
699 if (filename
== wxT(""))
700 return (wxChar
*) NULL
;
702 wxStrcpy (dest
, WXSTRINGCAST filename
);
704 wxUnix2DosFilename(dest
);
707 // Handle environment
708 const wxChar
*val
= (const wxChar
*) NULL
;
709 wxChar
*tcp
= (wxChar
*) NULL
;
710 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
711 (tcp
= wxStrstr (dest
, val
)) != NULL
)
713 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
716 wxStrcpy (tcp
, WXSTRINGCAST envname
);
717 wxStrcat (tcp
, wxT("}"));
718 wxStrcat (tcp
, wxFileFunctionsBuffer
);
721 // Handle User's home (ignore root homes!)
723 if ((val
= wxGetUserHome (user
)) != NULL
&&
724 (len
= wxStrlen(val
)) > 2 &&
725 wxStrncmp(dest
, val
, len
) == 0)
727 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
729 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
730 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
731 wxStrcpy (dest
, wxFileFunctionsBuffer
);
737 // Return just the filename, not the path (basename)
738 wxChar
*wxFileNameFromPath (wxChar
*path
)
741 wxString n
= wxFileNameFromPath(p
);
743 return path
+ p
.length() - n
.length();
746 wxString
wxFileNameFromPath (const wxString
& path
)
749 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
751 wxString fullname
= name
;
754 fullname
<< wxFILE_SEP_EXT
<< ext
;
760 // Return just the directory, or NULL if no directory
762 wxPathOnly (wxChar
*path
)
766 static wxChar buf
[_MAXPATHLEN
];
769 wxStrcpy (buf
, path
);
771 int l
= wxStrlen(path
);
774 // Search backward for a backward or forward slash
777 #if defined(__WXMAC__) && !defined(__DARWIN__)
778 // Classic or Carbon CodeWarrior like
779 // Carbon with Apple DevTools is Unix like
780 if (path
[i
] == wxT(':') )
786 // Unix like or Windows
787 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
794 if (path
[i
] == wxT(']'))
803 #if defined(__WXMSW__) || defined(__WXPM__)
804 // Try Drive specifier
805 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
807 // A:junk --> A:. (since A:.\junk Not A:\junk)
814 return (wxChar
*) NULL
;
817 // Return just the directory, or NULL if no directory
818 wxString
wxPathOnly (const wxString
& path
)
822 wxChar buf
[_MAXPATHLEN
];
825 wxStrcpy (buf
, WXSTRINGCAST path
);
827 int l
= path
.Length();
830 // Search backward for a backward or forward slash
833 #if defined(__WXMAC__) && !defined(__DARWIN__)
834 // Classic or Carbon CodeWarrior like
835 // Carbon with Apple DevTools is Unix like
836 if (path
[i
] == wxT(':') )
839 return wxString(buf
);
842 // Unix like or Windows
843 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
846 return wxString(buf
);
850 if (path
[i
] == wxT(']'))
853 return wxString(buf
);
859 #if defined(__WXMSW__) || defined(__WXPM__)
860 // Try Drive specifier
861 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
863 // A:junk --> A:. (since A:.\junk Not A:\junk)
866 return wxString(buf
);
870 return wxString(wxT(""));
873 // Utility for converting delimiters in DOS filenames to UNIX style
874 // and back again - or we get nasty problems with delimiters.
875 // Also, convert to lower case, since case is significant in UNIX.
877 #if defined(__WXMAC__)
878 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
885 Boolean isDirectory
= FALSE
;
886 Str255 theParentPath
= "\p";
887 FSSpec theParentSpec
;
889 char theFileName
[FILENAME_MAX
];
890 char thePath
[FILENAME_MAX
];
894 // GD: Separate file name from path and make a FSRef to the parent
895 // directory. This is necessary since FSRefs cannot reference files
896 // that have not yet been created.
897 // Based on example code from Apple Technical Note TN2022
898 // http://developer.apple.com/technotes/tn/tn2022.html
900 // check whether we are converting a directory
901 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
902 // count length of file name
903 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
905 // prepend path separator since it will later be appended to the path
906 theFileName
[0] = wxFILE_SEP_PATH
;
907 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
908 theFileName
[j
- i
] = spec
->name
[j
];
910 theFileName
[j
- i
] = '\0';
912 for (j
= 1; j
<= i
; j
++) {
913 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
915 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
916 if (theErr
== noErr
) {
917 // convert the FSSpec to an FSRef
918 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
920 if (theErr
== noErr
) {
921 // get the POSIX path associated with the FSRef
922 theStatus
= FSRefMakePath(&theParentRef
,
923 (UInt8
*)thePath
, sizeof(thePath
));
925 if (theStatus
== noErr
) {
926 // append file name to path
927 // includes previously prepended path separator
928 strcat(thePath
, theFileName
);
931 // create path string for return value
932 wxString
result( thePath
) ;
937 // get length of path and allocate handle
938 FSpGetFullPath( spec
, &length
, &myPath
) ;
939 ::SetHandleSize( myPath
, length
+ 1 ) ;
941 (*myPath
)[length
] = 0 ;
942 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
943 (*myPath
)[length
-1] = 0 ;
945 // create path string for return value
946 wxString result
= wxMacMakeStringFromCString( *myPath
) ;
948 // free allocated handle
949 ::HUnlock( myPath
) ;
950 ::DisposeHandle( myPath
) ;
956 // Mac file names are POSIX (Unix style) under Darwin
957 // therefore the conversion functions below are not needed
959 static wxChar sMacFileNameConversion
[ 1000 ] ;
960 static char scMacFileNameConversion
[ 1000 ] ;
963 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
965 OSStatus err
= noErr
;
969 // get the FSRef associated with the POSIX path
970 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
971 // convert the FSRef to an FSSpec
972 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
974 if ( strchr( path
, ':' ) == NULL
)
976 // try whether it is a volume / or a mounted volume
977 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
978 scMacFileNameConversion
[998] = 0 ;
979 strcat( scMacFileNameConversion
, ":" ) ;
980 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
984 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
990 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
992 return wxMacFilename2FSSpec( wxMacStringToCString( wxString( path
) ) , spec
) ;
998 wxString
wxMac2UnixFilename (const wxChar
*str
)
1000 wxChar
*s
= sMacFileNameConversion
;
1001 wxStrcpy( s
, str
) ;
1004 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1015 *s
= wxTolower(*s
); // Case INDEPENDENT
1019 return wxString(sMacFileNameConversion
) ;
1022 wxString
wxUnix2MacFilename (const wxChar
*str
)
1024 wxChar
*s
= sMacFileNameConversion
;
1025 wxStrcpy( s
, str
) ;
1030 // relative path , since it goes on with slash which is translated to a :
1031 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1033 else if ( *s
== '/' )
1035 // absolute path -> on mac just start with the drive name
1036 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1040 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1044 if (*s
== '/' || *s
== '\\')
1046 // convert any back-directory situations
1047 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1050 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1058 return wxString(sMacFileNameConversion
) ;
1061 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1063 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1066 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1068 wxString var
= wxUnix2MacFilename( path
) ;
1069 wxMacFilename2FSSpec( var
, spec
) ;
1071 #endif // ! __DARWIN__
1076 wxDos2UnixFilename (char *s
)
1085 *s
= wxTolower (*s
); // Case INDEPENDENT
1092 #if defined(__WXMSW__) || defined(__WXPM__)
1093 wxUnix2DosFilename (wxChar
*s
)
1095 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1098 // Yes, I really mean this to happen under DOS only! JACS
1099 #if defined(__WXMSW__) || defined(__WXPM__)
1110 // Concatenate two files to form third
1112 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1115 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1118 FILE *fp1
= (FILE *) NULL
;
1119 FILE *fp2
= (FILE *) NULL
;
1120 FILE *fp3
= (FILE *) NULL
;
1121 // Open the inputs and outputs
1122 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1123 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1124 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1136 while ((ch
= getc (fp1
)) != EOF
)
1137 (void) putc (ch
, fp3
);
1140 while ((ch
= getc (fp2
)) != EOF
)
1141 (void) putc (ch
, fp3
);
1145 bool result
= wxRenameFile(outfile
, file3
);
1151 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1153 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1154 // CopyFile() copies file attributes and modification time too, so use it
1155 // instead of our code if available
1157 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1158 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1160 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1161 file1
.c_str(), file2
.c_str());
1165 #elif defined(__WXPM__)
1166 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1171 // get permissions of file1
1172 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1174 // the file probably doesn't exist or we haven't the rights to read
1176 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1181 // open file1 for reading
1182 wxFile
fileIn(file1
, wxFile::read
);
1183 if ( !fileIn
.IsOpened() )
1186 // remove file2, if it exists. This is needed for creating
1187 // file2 with the correct permissions in the next step
1188 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1190 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1196 // reset the umask as we want to create the file with exactly the same
1197 // permissions as the original one
1198 mode_t oldUmask
= umask( 0 );
1201 // create file2 with the same permissions than file1 and open it for
1205 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1209 /// restore the old umask
1213 // copy contents of file1 to file2
1218 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1219 if ( fileIn
.Error() )
1226 if ( fileOut
.Write(buf
, count
) < count
)
1230 // we can expect fileIn to be closed successfully, but we should ensure
1231 // that fileOut was closed as some write errors (disk full) might not be
1232 // detected before doing this
1233 if ( !fileIn
.Close() || !fileOut
.Close() )
1236 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1237 // no chmod in VA. Should be some permission API for HPFS386 partitions
1239 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1241 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1245 #endif // OS/2 || Mac
1246 #endif // __WXMSW__ && __WIN32__
1252 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1254 // Normal system call
1255 if ( wxRename (file1
, file2
) == 0 )
1259 if (wxCopyFile(file1
, file2
)) {
1260 wxRemoveFile(file1
);
1267 bool wxRemoveFile(const wxString
& file
)
1269 #if defined(__VISUALC__) \
1270 || defined(__BORLANDC__) \
1271 || defined(__WATCOMC__) \
1272 || defined(__GNUWIN32__)
1273 int res
= wxRemove(file
);
1274 #elif defined(__WXMAC__)
1275 int res
= unlink(wxFNCONV(file
));
1277 int res
= unlink(OS_FILENAME(file
));
1283 bool wxMkdir(const wxString
& dir
, int perm
)
1285 #if defined(__WXMAC__) && !defined(__UNIX__)
1286 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1288 const wxChar
*dirname
= dir
.c_str();
1290 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1291 // for the GNU compiler
1292 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1294 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1296 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1298 #elif defined(__WXPM__)
1299 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1300 #elif defined(__DOS__)
1301 #if defined(__WATCOMC__)
1303 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1304 #elif defined(__DJGPP__)
1305 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1307 #error "Unsupported DOS compiler!"
1309 #else // !MSW, !DOS and !OS/2 VAC++
1311 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1314 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1323 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1326 return FALSE
; //to be changed since rmdir exists in VMS7.x
1327 #elif defined(__WXPM__)
1328 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1332 return FALSE
; // What to do?
1334 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1340 // does the path exists? (may have or not '/' or '\\' at the end)
1341 bool wxPathExists(const wxChar
*pszPathName
)
1343 wxString
strPath(pszPathName
);
1346 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1347 // so remove all trailing backslashes from the path - but don't do this for
1348 // the pathes "d:\" (which are different from "d:") nor for just "\"
1349 while ( wxEndsWithPathSeparator(strPath
) )
1351 size_t len
= strPath
.length();
1352 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1355 strPath
.Truncate(len
- 1);
1357 #endif // __WINDOWS__
1359 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1360 // stat() can't cope with network paths
1361 DWORD ret
= ::GetFileAttributes(strPath
);
1363 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1367 #ifndef __VISAGECPP__
1368 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1370 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1371 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1374 #endif // __WIN32__/!__WIN32__
1377 // Get a temporary filename, opening and closing the file.
1378 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1380 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1381 if ( filename
.empty() )
1385 wxStrcpy(buf
, filename
);
1387 buf
= copystring(filename
);
1392 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1394 buf
= wxFileName::CreateTempFileName(prefix
);
1396 return !buf
.empty();
1399 // Get first file name matching given wild card.
1401 static wxDir
*gs_dir
= NULL
;
1402 static wxString gs_dirPath
;
1404 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1406 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1407 if ( gs_dirPath
.IsEmpty() )
1408 gs_dirPath
= wxT(".");
1409 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1410 gs_dirPath
<< wxFILE_SEP_PATH
;
1414 gs_dir
= new wxDir(gs_dirPath
);
1416 if ( !gs_dir
->IsOpened() )
1418 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1419 return wxEmptyString
;
1425 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1426 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1427 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1431 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1432 if ( result
.IsEmpty() )
1438 return gs_dirPath
+ result
;
1441 wxString
wxFindNextFile()
1443 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1446 gs_dir
->GetNext(&result
);
1448 if ( result
.IsEmpty() )
1454 return gs_dirPath
+ result
;
1458 // Get current working directory.
1459 // If buf is NULL, allocates space using new, else
1461 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1465 buf
= new wxChar
[sz
+ 1];
1470 // for the compilers which have Unicode version of _getcwd(), call it
1471 // directly, for the others call the ANSI version and do the translation
1474 #else // wxUSE_UNICODE
1475 bool needsANSI
= TRUE
;
1477 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1478 // This is not legal code as the compiler
1479 // is allowed destroy the wxCharBuffer.
1480 // wxCharBuffer c_buffer(sz);
1481 // char *cbuf = (char*)(const char*)c_buffer;
1482 char cbuf
[_MAXPATHLEN
];
1486 #if wxUSE_UNICODE_MSLU
1487 if ( wxGetOsVersion() != wxWIN95
)
1489 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1492 ok
= _wgetcwd(buf
, sz
) != NULL
;
1498 #endif // wxUSE_UNICODE
1501 ok
= _getcwd(cbuf
, sz
) != NULL
;
1502 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1507 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1509 pb
.ioRefNum
= LMGetCurApRefNum();
1511 error
= PBGetFCBInfoSync(&pb
);
1512 if ( error
== noErr
)
1514 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1515 cwdSpec
.parID
= pb
.ioFCBParID
;
1516 cwdSpec
.name
[0] = 0 ;
1517 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1518 wxStrcpy( buf
, res
) ;
1525 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1527 rc
= ::DosQueryCurrentDir( 0 // current drive
1532 #else // !Win32/VC++ !Mac !OS2
1533 ok
= getcwd(cbuf
, sz
) != NULL
;
1536 #if wxUSE_UNICODE && !defined(__WXMAC__)
1537 // finally convert the result to Unicode if needed
1538 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1539 #endif // wxUSE_UNICODE
1544 wxLogSysError(_("Failed to get the working directory"));
1546 // VZ: the old code used to return "." on error which didn't make any
1547 // sense at all to me - empty string is a better error indicator
1548 // (NULL might be even better but I'm afraid this could lead to
1549 // problems with the old code assuming the return is never NULL)
1552 else // ok, but we might need to massage the path into the right format
1555 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1556 // with / deliminers. We don't like that.
1557 for (wxChar
*ch
= buf
; *ch
; ch
++)
1559 if (*ch
== wxT('/'))
1564 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1565 // he needs Unix as opposed to Win32 pathnames
1566 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1567 // another example of DOS/Unix mix (Cygwin)
1568 wxString pathUnix
= buf
;
1569 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1570 #endif // __CYGWIN__
1582 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1583 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1584 wxString
str( buffer
);
1590 bool wxSetWorkingDirectory(const wxString
& d
)
1592 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1593 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1594 #elif defined(__WXPM__)
1595 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1596 #elif defined(__WINDOWS__)
1599 return (bool)(SetCurrentDirectory(d
) != 0);
1601 // Must change drive, too.
1602 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1605 wxChar firstChar
= d
[0];
1609 firstChar
= firstChar
- 32;
1611 // To a drive number
1612 unsigned int driveNo
= firstChar
- 64;
1615 unsigned int noDrives
;
1616 _dos_setdrive(driveNo
, &noDrives
);
1619 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1627 // Get the OS directory if appropriate (such as the Windows directory).
1628 // On non-Windows platform, probably just return the empty string.
1629 wxString
wxGetOSDirectory()
1631 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1633 GetWindowsDirectory(buf
, 256);
1634 return wxString(buf
);
1636 return wxEmptyString
;
1640 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1642 size_t len
= wxStrlen(pszFileName
);
1644 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1647 // find a file in a list of directories, returns FALSE if not found
1648 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1650 // we assume that it's not empty
1651 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1652 _T("empty file name in wxFindFileInPath"));
1654 // skip path separator in the beginning of the file name if present
1655 if ( wxIsPathSeparator(*pszFile
) )
1658 // copy the path (strtok will modify it)
1659 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1660 wxStrcpy(szPath
, pszPath
);
1663 wxChar
*pc
, *save_ptr
;
1664 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1666 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1668 // search for the file in this directory
1670 if ( !wxEndsWithPathSeparator(pc
) )
1671 strFile
+= wxFILE_SEP_PATH
;
1674 if ( wxFileExists(strFile
) ) {
1680 // suppress warning about unused variable save_ptr when wxStrtok() is a
1681 // macro which throws away its third argument
1686 return pc
!= NULL
; // if TRUE => we breaked from the loop
1689 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1694 // it can be empty, but it shouldn't be NULL
1695 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1697 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1700 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1703 wxStat( filename
, &buf
);
1705 return buf
.st_mtime
;
1709 //------------------------------------------------------------------------
1710 // wild character routines
1711 //------------------------------------------------------------------------
1713 bool wxIsWild( const wxString
& pattern
)
1715 wxString tmp
= pattern
;
1716 wxChar
*pat
= WXSTRINGCAST(tmp
);
1721 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1732 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1734 * The match procedure is public domain code (from ircII's reg.c)
1737 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1741 /* Match if both are empty. */
1745 const wxChar
*m
= pat
.c_str(),
1756 if (dot_special
&& (*n
== wxT('.')))
1758 /* Never match so that hidden Unix files
1759 * are never found. */
1773 else if (*m
== wxT('?'))
1781 if (*m
== wxT('\\'))
1784 /* Quoting "nothing" is a bad thing */
1791 * If we are out of both strings or we just
1792 * saw a wildcard, then we can say we have a
1803 * We could check for *n == NULL at this point, but
1804 * since it's more common to have a character there,
1805 * check to see if they match first (m and n) and
1806 * then if they don't match, THEN we can check for
1824 * If there are no more characters in the
1825 * string, but we still need to find another
1826 * character (*m != NULL), then it will be
1827 * impossible to match it
1834 if (*np
== wxT(' '))
1860 #pragma warning(default:4706) // assignment within conditional expression