1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "filefn.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
35 #include "wx/filename.h"
38 // there are just too many of those...
40 #pragma warning(disable:4706) // assignment within conditional expression
47 #if !defined(__WATCOMC__)
48 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
53 #if defined(__WXMAC__)
54 #include "wx/mac/private.h" // includes mac headers
58 #include "wx/msw/wince/time.h"
59 #include "wx/msw/private.h"
66 #elif !defined(__MWERKS__)
67 #include <sys/types.h>
71 #include <sys/types.h>
91 #include "wx/os2/private.h"
93 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
94 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__) && !defined(__WXWINCE__)
99 #endif // native Win compiler
112 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
113 // this (3.1 I believe) and how to test for it.
114 // If this works for Borland 4.0 as well, then no worries.
125 // No, Cygwin doesn't appear to have fnmatch.h after all.
126 #if defined(HAVE_FNMATCH_H)
131 #include "wx/msw/wrapwin.h"
132 #include "wx/msw/mslu.h"
139 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
141 // note that it must be included after <windows.h>
144 #include <sys/cygwin.h>
146 #endif // __GNUWIN32__
147 #endif // __WINDOWS__
149 // TODO: Borland probably has _wgetcwd as well?
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
159 #define _MAXPATHLEN 1024
164 # include "MoreFilesX.h"
166 # include "MoreFiles.h"
167 # include "MoreFilesExtras.h"
168 # include "FullPath.h"
169 # include "FSpCompat.h"
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
177 // MT-FIXME: get rid of this horror and all code using it
178 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
180 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
182 // VisualAge C++ V4.0 cannot have any external linkage const decs
183 // in headers included by more than one primary source
185 const off_t wxInvalidOffset
= (off_t
)-1;
188 // ----------------------------------------------------------------------------
190 // ----------------------------------------------------------------------------
192 // we need to translate Mac filenames before passing them to OS functions
193 #define OS_FILENAME(s) (s.fn_str())
195 // ============================================================================
197 // ============================================================================
199 #ifdef wxNEED_WX_UNISTD_H
201 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
203 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
206 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
208 return access( wxConvFile
.cWX2MB( pathname
), mode
);
211 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
213 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
217 // wxNEED_WX_UNISTD_H
219 // ----------------------------------------------------------------------------
221 // ----------------------------------------------------------------------------
223 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
225 static inline wxChar
* MYcopystring(const wxString
& s
)
227 wxChar
* copy
= new wxChar
[s
.length() + 1];
228 return wxStrcpy(copy
, s
.c_str());
231 static inline wxChar
* MYcopystring(const wxChar
* s
)
233 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
234 return wxStrcpy(copy
, s
);
237 void wxPathList::Add (const wxString
& path
)
239 wxStringList::Add (WXSTRINGCAST path
);
242 // Add paths e.g. from the PATH environment variable
243 void wxPathList::AddEnvList (const wxString
& envVariable
)
245 // No environment variables on WinCE
247 static const wxChar PATH_TOKS
[] =
250 The space has been removed from the tokenizers, otherwise a
251 path such as "C:\Program Files" would be split into 2 paths:
252 "C:\Program" and "Files"
254 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
255 wxT(";"); // Don't seperate with colon in DOS (used for drive)
260 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
263 wxChar
*s
= MYcopystring (val
);
264 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
271 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
279 // suppress warning about unused variable save_ptr when wxStrtok() is a
280 // macro which throws away its third argument
288 // Given a full filename (with path), ensure that that file can
289 // be accessed again USING FILENAME ONLY by adding the path
290 // to the list if not already there.
291 void wxPathList::EnsureFileAccessible (const wxString
& path
)
293 wxString
path_only(wxPathOnly(path
));
294 if ( !path_only
.IsEmpty() )
296 if ( !Member(path_only
) )
301 bool wxPathList::Member (const wxString
& path
)
303 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
305 wxString
path2( node
->GetData() );
307 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
309 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
311 // Case sensitive File System
312 path
.CompareTo (path2
) == 0
320 wxString
wxPathList::FindValidPath (const wxString
& file
)
322 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
323 return wxString(wxFileFunctionsBuffer
);
325 wxChar buf
[_MAXPATHLEN
];
326 wxStrcpy(buf
, wxFileFunctionsBuffer
);
328 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
330 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
332 const wxChar
*path
= node
->GetData();
333 wxStrcpy (wxFileFunctionsBuffer
, path
);
334 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
335 if (ch
!= wxT('\\') && ch
!= wxT('/'))
336 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
337 wxStrcat (wxFileFunctionsBuffer
, filename
);
339 wxUnix2DosFilename (wxFileFunctionsBuffer
);
341 if (wxFileExists (wxFileFunctionsBuffer
))
343 return wxString(wxFileFunctionsBuffer
); // Found!
347 return wxEmptyString
; // Not found
350 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
352 wxString f
= FindValidPath(file
);
353 if ( wxIsAbsolutePath(f
) )
357 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
359 if ( !wxEndsWithPathSeparator(buf
) )
361 buf
+= wxFILE_SEP_PATH
;
369 wxFileExists (const wxString
& filename
)
371 // we must use GetFileAttributes() instead of the ANSI C functions because
372 // it can cope with network (UNC) paths unlike them
373 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
374 DWORD ret
= ::GetFileAttributes(filename
);
376 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
379 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
380 #endif // __WIN32__/!__WIN32__
384 wxIsAbsolutePath (const wxString
& filename
)
386 if (filename
!= wxT(""))
388 #if defined(__WXMAC__) && !defined(__DARWIN__)
389 // Classic or Carbon CodeWarrior like
390 // Carbon with Apple DevTools is Unix like
392 // This seems wrong to me, but there is no fix. since
393 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
394 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
395 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
398 // Unix like or Windows
399 if (filename
[0] == wxT('/'))
403 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
408 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
416 * Strip off any extension (dot something) from end of file,
417 * IF one exists. Inserts zero into buffer.
421 void wxStripExtension(wxChar
*buffer
)
423 int len
= wxStrlen(buffer
);
427 if (buffer
[i
] == wxT('.'))
436 void wxStripExtension(wxString
& buffer
)
438 size_t len
= buffer
.Length();
442 if (buffer
.GetChar(i
) == wxT('.'))
444 buffer
= buffer
.Left(i
);
451 // Destructive removal of /./ and /../ stuff
452 wxChar
*wxRealPath (wxChar
*path
)
455 static const wxChar SEP
= wxT('\\');
456 wxUnix2DosFilename(path
);
458 static const wxChar SEP
= wxT('/');
460 if (path
[0] && path
[1]) {
461 /* MATTHEW: special case "/./x" */
463 if (path
[2] == SEP
&& path
[1] == wxT('.'))
471 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
474 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
479 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
480 && (q
- 1 <= path
|| q
[-1] != SEP
))
483 if (path
[0] == wxT('\0'))
489 /* Check that path[2] is NULL! */
490 else if (path
[1] == wxT(':') && !path
[2])
499 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
508 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
510 if (filename
== wxT(""))
511 return (wxChar
*) NULL
;
513 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
514 wxChar buf
[_MAXPATHLEN
];
516 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
517 wxChar ch
= buf
[wxStrlen(buf
) - 1];
519 if (ch
!= wxT('\\') && ch
!= wxT('/'))
520 wxStrcat(buf
, wxT("\\"));
523 wxStrcat(buf
, wxT("/"));
525 wxStrcat(buf
, wxFileFunctionsBuffer
);
526 return MYcopystring( wxRealPath(buf
) );
528 return MYcopystring( wxFileFunctionsBuffer
);
534 ~user/ => user's home dir
535 If the environment variable a = "foo" and b = "bar" then:
552 /* input name in name, pathname output to buf. */
554 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
556 register wxChar
*d
, *s
, *nm
;
557 wxChar lnm
[_MAXPATHLEN
];
560 // Some compilers don't like this line.
561 // const wxChar trimchars[] = wxT("\n \t");
564 trimchars
[0] = wxT('\n');
565 trimchars
[1] = wxT(' ');
566 trimchars
[2] = wxT('\t');
570 const wxChar SEP
= wxT('\\');
572 const wxChar SEP
= wxT('/');
575 if (name
== NULL
|| *name
== wxT('\0'))
577 nm
= MYcopystring(name
); // Make a scratch copy
580 /* Skip leading whitespace and cr */
581 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
583 /* And strip off trailing whitespace and cr */
584 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
585 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
593 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
596 /* Expand inline environment variables */
614 while ((*d
++ = *s
) != 0) {
616 if (*s
== wxT('\\')) {
617 if ((*(d
- 1) = *++s
)) {
625 // No env variables on WinCE
628 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
630 if (*s
++ == wxT('$'))
633 register wxChar
*start
= d
;
634 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
635 register wxChar
*value
;
636 while ((*d
++ = *s
) != 0)
637 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
642 value
= wxGetenv(braces
? start
+ 1 : start
);
644 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
658 /* Expand ~ and ~user */
660 if (nm
[0] == wxT('~') && !q
)
663 if (nm
[1] == SEP
|| nm
[1] == 0)
665 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
666 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
671 { /* ~user/filename */
672 register wxChar
*nnm
;
673 register wxChar
*home
;
674 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
678 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
679 was_sep
= (*s
== SEP
);
680 nnm
= *s
? s
+ 1 : s
;
682 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
683 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
684 if (was_sep
) /* replace only if it was there: */
695 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
697 while (wxT('\0') != (*d
++ = *s
++))
700 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
704 while ((*d
++ = *s
++) != 0)
708 delete[] nm_tmp
; // clean up alloc
709 /* Now clean up the buffer */
710 return wxRealPath(buf
);
713 /* Contract Paths to be build upon an environment variable
716 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
718 The call wxExpandPath can convert these back!
721 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
723 static wxChar dest
[_MAXPATHLEN
];
725 if (filename
== wxT(""))
726 return (wxChar
*) NULL
;
728 wxStrcpy (dest
, WXSTRINGCAST filename
);
730 wxUnix2DosFilename(dest
);
733 // Handle environment
737 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
738 (tcp
= wxStrstr (dest
, val
)) != NULL
)
740 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
743 wxStrcpy (tcp
, WXSTRINGCAST envname
);
744 wxStrcat (tcp
, wxT("}"));
745 wxStrcat (tcp
, wxFileFunctionsBuffer
);
749 // Handle User's home (ignore root homes!)
751 if ((val
= wxGetUserHome (user
)) != NULL
&&
752 (len
= wxStrlen(val
)) > 2 &&
753 wxStrncmp(dest
, val
, len
) == 0)
755 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
757 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
758 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
759 wxStrcpy (dest
, wxFileFunctionsBuffer
);
765 // Return just the filename, not the path (basename)
766 wxChar
*wxFileNameFromPath (wxChar
*path
)
769 wxString n
= wxFileNameFromPath(p
);
771 return path
+ p
.length() - n
.length();
774 wxString
wxFileNameFromPath (const wxString
& path
)
777 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
779 wxString fullname
= name
;
782 fullname
<< wxFILE_SEP_EXT
<< ext
;
788 // Return just the directory, or NULL if no directory
790 wxPathOnly (wxChar
*path
)
794 static wxChar buf
[_MAXPATHLEN
];
797 wxStrcpy (buf
, path
);
799 int l
= wxStrlen(path
);
802 // Search backward for a backward or forward slash
805 #if defined(__WXMAC__) && !defined(__DARWIN__)
806 // Classic or Carbon CodeWarrior like
807 // Carbon with Apple DevTools is Unix like
808 if (path
[i
] == wxT(':') )
814 // Unix like or Windows
815 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
822 if (path
[i
] == wxT(']'))
831 #if defined(__WXMSW__) || defined(__WXPM__)
832 // Try Drive specifier
833 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
835 // A:junk --> A:. (since A:.\junk Not A:\junk)
842 return (wxChar
*) NULL
;
845 // Return just the directory, or NULL if no directory
846 wxString
wxPathOnly (const wxString
& path
)
850 wxChar buf
[_MAXPATHLEN
];
853 wxStrcpy (buf
, WXSTRINGCAST path
);
855 int l
= path
.Length();
858 // Search backward for a backward or forward slash
861 #if defined(__WXMAC__) && !defined(__DARWIN__)
862 // Classic or Carbon CodeWarrior like
863 // Carbon with Apple DevTools is Unix like
864 if (path
[i
] == wxT(':') )
867 return wxString(buf
);
870 // Unix like or Windows
871 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
874 return wxString(buf
);
878 if (path
[i
] == wxT(']'))
881 return wxString(buf
);
887 #if defined(__WXMSW__) || defined(__WXPM__)
888 // Try Drive specifier
889 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
891 // A:junk --> A:. (since A:.\junk Not A:\junk)
894 return wxString(buf
);
898 return wxString(wxT(""));
901 // Utility for converting delimiters in DOS filenames to UNIX style
902 // and back again - or we get nasty problems with delimiters.
903 // Also, convert to lower case, since case is significant in UNIX.
905 #if defined(__WXMAC__)
906 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
913 Boolean isDirectory
= FALSE
;
914 Str255 theParentPath
= "\p";
915 FSSpec theParentSpec
;
917 char theFileName
[FILENAME_MAX
];
918 char thePath
[FILENAME_MAX
];
922 // GD: Separate file name from path and make a FSRef to the parent
923 // directory. This is necessary since FSRefs cannot reference files
924 // that have not yet been created.
925 // Based on example code from Apple Technical Note TN2022
926 // http://developer.apple.com/technotes/tn/tn2022.html
928 // check whether we are converting a directory
929 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
930 // count length of file name
931 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
933 // prepend path separator since it will later be appended to the path
934 theFileName
[0] = wxFILE_SEP_PATH
;
935 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
936 theFileName
[j
- i
] = spec
->name
[j
];
938 theFileName
[j
- i
] = '\0';
940 for (j
= 1; j
<= i
; j
++) {
941 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
943 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
944 if (theErr
== noErr
) {
945 // convert the FSSpec to an FSRef
946 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
948 if (theErr
== noErr
) {
949 // get the POSIX path associated with the FSRef
950 theStatus
= FSRefMakePath(&theParentRef
,
951 (UInt8
*)thePath
, sizeof(thePath
));
953 if (theStatus
== noErr
) {
954 // append file name to path
955 // includes previously prepended path separator
956 strcat(thePath
, theFileName
);
959 // create path string for return value
960 wxString
result( thePath
, wxConvLocal
) ;
965 // get length of path and allocate handle
966 FSpGetFullPath( spec
, &length
, &myPath
) ;
967 ::SetHandleSize( myPath
, length
+ 1 ) ;
969 (*myPath
)[length
] = 0 ;
970 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
971 (*myPath
)[length
-1] = 0 ;
973 // create path string for return value
974 wxString
result( *myPath
, wxConvLocal
) ;
976 // free allocated handle
977 ::HUnlock( myPath
) ;
978 ::DisposeHandle( myPath
) ;
984 // Mac file names are POSIX (Unix style) under Darwin
985 // therefore the conversion functions below are not needed
987 static wxChar sMacFileNameConversion
[ 1000 ] ;
988 static char scMacFileNameConversion
[ 1000 ] ;
991 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
993 OSStatus err
= noErr
;
997 // get the FSRef associated with the POSIX path
998 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
999 // convert the FSRef to an FSSpec
1000 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
1002 if ( strchr( path
, ':' ) == NULL
)
1004 // try whether it is a volume / or a mounted volume
1005 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
1006 scMacFileNameConversion
[998] = 0 ;
1007 strcat( scMacFileNameConversion
, ":" ) ;
1008 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
1012 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
1018 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
1020 return wxMacFilename2FSSpec( wxConvFile
.cWC2MB(path
) , spec
) ;
1026 wxString
wxMac2UnixFilename (const wxChar
*str
)
1028 wxChar
*s
= sMacFileNameConversion
;
1029 wxStrcpy( s
, str
) ;
1032 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1043 *s
= wxTolower(*s
); // Case INDEPENDENT
1047 return wxString(sMacFileNameConversion
) ;
1050 wxString
wxUnix2MacFilename (const wxChar
*str
)
1052 wxChar
*s
= sMacFileNameConversion
;
1053 wxStrcpy( s
, str
) ;
1058 // relative path , since it goes on with slash which is translated to a :
1059 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1061 else if ( *s
== '/' )
1063 // absolute path -> on mac just start with the drive name
1064 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1068 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1072 if (*s
== '/' || *s
== '\\')
1074 // convert any back-directory situations
1075 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1078 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1086 return wxString(sMacFileNameConversion
) ;
1089 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1091 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1094 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1096 wxString var
= wxUnix2MacFilename( path
) ;
1097 wxMacFilename2FSSpec( var
, spec
) ;
1099 #endif // ! __DARWIN__
1104 wxDos2UnixFilename (wxChar
*s
)
1113 *s
= wxTolower (*s
); // Case INDEPENDENT
1120 #if defined(__WXMSW__) || defined(__WXPM__)
1121 wxUnix2DosFilename (wxChar
*s
)
1123 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1126 // Yes, I really mean this to happen under DOS only! JACS
1127 #if defined(__WXMSW__) || defined(__WXPM__)
1138 // Concatenate two files to form third
1140 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1143 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1146 FILE *fp1
wxDUMMY_INITIALIZE(NULL
);
1147 FILE *fp2
wxDUMMY_INITIALIZE(NULL
);
1148 FILE *fp3
wxDUMMY_INITIALIZE(NULL
);
1149 // Open the inputs and outputs
1150 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1151 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1152 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1164 while ((ch
= getc (fp1
)) != EOF
)
1165 (void) putc (ch
, fp3
);
1168 while ((ch
= getc (fp2
)) != EOF
)
1169 (void) putc (ch
, fp3
);
1173 bool result
= wxRenameFile(outfile
, file3
);
1179 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1181 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1182 // CopyFile() copies file attributes and modification time too, so use it
1183 // instead of our code if available
1185 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1186 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1188 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1189 file1
.c_str(), file2
.c_str());
1193 #elif defined(__WXPM__)
1194 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1199 // get permissions of file1
1200 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1202 // the file probably doesn't exist or we haven't the rights to read
1204 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1209 // open file1 for reading
1210 wxFile
fileIn(file1
, wxFile::read
);
1211 if ( !fileIn
.IsOpened() )
1214 // remove file2, if it exists. This is needed for creating
1215 // file2 with the correct permissions in the next step
1216 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1218 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1224 // reset the umask as we want to create the file with exactly the same
1225 // permissions as the original one
1226 mode_t oldUmask
= umask( 0 );
1229 // create file2 with the same permissions than file1 and open it for
1233 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1237 /// restore the old umask
1241 // copy contents of file1 to file2
1246 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1247 if ( fileIn
.Error() )
1254 if ( fileOut
.Write(buf
, count
) < count
)
1258 // we can expect fileIn to be closed successfully, but we should ensure
1259 // that fileOut was closed as some write errors (disk full) might not be
1260 // detected before doing this
1261 if ( !fileIn
.Close() || !fileOut
.Close() )
1264 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1265 // no chmod in VA. Should be some permission API for HPFS386 partitions
1267 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1269 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1273 #endif // OS/2 || Mac
1274 #endif // __WXMSW__ && __WIN32__
1280 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1283 // Normal system call
1284 if ( wxRename (file1
, file2
) == 0 )
1289 if (wxCopyFile(file1
, file2
)) {
1290 wxRemoveFile(file1
);
1297 bool wxRemoveFile(const wxString
& file
)
1299 #if defined(__VISUALC__) \
1300 || defined(__BORLANDC__) \
1301 || defined(__WATCOMC__) \
1302 || defined(__GNUWIN32__)
1303 int res
= wxRemove(file
);
1304 #elif defined(__WXMAC__)
1305 int res
= unlink(wxFNCONV(file
));
1307 int res
= unlink(OS_FILENAME(file
));
1313 bool wxMkdir(const wxString
& dir
, int perm
)
1315 #if defined(__WXMAC__) && !defined(__UNIX__)
1316 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1318 const wxChar
*dirname
= dir
.c_str();
1320 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1321 // for the GNU compiler
1322 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1324 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1326 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1328 #elif defined(__WXPM__)
1329 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1330 #elif defined(__DOS__)
1331 #if defined(__WATCOMC__)
1333 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1334 #elif defined(__DJGPP__)
1335 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1337 #error "Unsupported DOS compiler!"
1339 #else // !MSW, !DOS and !OS/2 VAC++
1342 if ( !CreateDirectory(dirname
, NULL
) )
1344 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1348 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1357 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1360 return FALSE
; //to be changed since rmdir exists in VMS7.x
1361 #elif defined(__WXPM__)
1362 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1366 return (CreateDirectory(dir
, NULL
) != 0);
1368 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1374 // does the path exists? (may have or not '/' or '\\' at the end)
1375 bool wxPathExists(const wxChar
*pszPathName
)
1377 wxString
strPath(pszPathName
);
1380 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1381 // so remove all trailing backslashes from the path - but don't do this for
1382 // the pathes "d:\" (which are different from "d:") nor for just "\"
1383 while ( wxEndsWithPathSeparator(strPath
) )
1385 size_t len
= strPath
.length();
1386 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1389 strPath
.Truncate(len
- 1);
1391 #endif // __WINDOWS__
1393 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1394 // stat() can't cope with network paths
1395 DWORD ret
= ::GetFileAttributes(strPath
);
1397 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1401 #ifndef __VISAGECPP__
1402 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1404 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1405 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1408 #endif // __WIN32__/!__WIN32__
1411 // Get a temporary filename, opening and closing the file.
1412 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1414 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1415 if ( filename
.empty() )
1419 wxStrcpy(buf
, filename
);
1421 buf
= MYcopystring(filename
);
1426 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1428 buf
= wxFileName::CreateTempFileName(prefix
);
1430 return !buf
.empty();
1433 // Get first file name matching given wild card.
1435 static wxDir
*gs_dir
= NULL
;
1436 static wxString gs_dirPath
;
1438 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1440 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1441 if ( gs_dirPath
.IsEmpty() )
1442 gs_dirPath
= wxT(".");
1443 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1444 gs_dirPath
<< wxFILE_SEP_PATH
;
1448 gs_dir
= new wxDir(gs_dirPath
);
1450 if ( !gs_dir
->IsOpened() )
1452 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1453 return wxEmptyString
;
1459 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1460 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1461 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1465 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1466 if ( result
.IsEmpty() )
1472 return gs_dirPath
+ result
;
1475 wxString
wxFindNextFile()
1477 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1480 gs_dir
->GetNext(&result
);
1482 if ( result
.IsEmpty() )
1488 return gs_dirPath
+ result
;
1492 // Get current working directory.
1493 // If buf is NULL, allocates space using new, else
1495 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1502 buf
= new wxChar
[sz
+ 1];
1505 bool ok
wxDUMMY_INITIALIZE(FALSE
);
1507 // for the compilers which have Unicode version of _getcwd(), call it
1508 // directly, for the others call the ANSI version and do the translation
1511 #else // wxUSE_UNICODE
1512 bool needsANSI
= TRUE
;
1514 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1515 // This is not legal code as the compiler
1516 // is allowed destroy the wxCharBuffer.
1517 // wxCharBuffer c_buffer(sz);
1518 // char *cbuf = (char*)(const char*)c_buffer;
1519 char cbuf
[_MAXPATHLEN
];
1523 #if wxUSE_UNICODE_MSLU
1524 if ( wxGetOsVersion() != wxWIN95
)
1526 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1529 ok
= _wgetcwd(buf
, sz
) != NULL
;
1535 #endif // wxUSE_UNICODE
1537 #if defined(_MSC_VER) || defined(__MINGW32__)
1538 ok
= _getcwd(cbuf
, sz
) != NULL
;
1539 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1544 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1546 pb
.ioRefNum
= LMGetCurApRefNum();
1548 error
= PBGetFCBInfoSync(&pb
);
1549 if ( error
== noErr
)
1551 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1552 cwdSpec
.parID
= pb
.ioFCBParID
;
1553 cwdSpec
.name
[0] = 0 ;
1554 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1555 wxStrcpy( buf
, res
) ;
1562 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1564 rc
= ::DosQueryCurrentDir( 0 // current drive
1569 #else // !Win32/VC++ !Mac !OS2
1570 ok
= getcwd(cbuf
, sz
) != NULL
;
1573 #if wxUSE_UNICODE && !defined(__WXMAC__)
1574 // finally convert the result to Unicode if needed
1575 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1576 #endif // wxUSE_UNICODE
1581 wxLogSysError(_("Failed to get the working directory"));
1583 // VZ: the old code used to return "." on error which didn't make any
1584 // sense at all to me - empty string is a better error indicator
1585 // (NULL might be even better but I'm afraid this could lead to
1586 // problems with the old code assuming the return is never NULL)
1589 else // ok, but we might need to massage the path into the right format
1592 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1593 // with / deliminers. We don't like that.
1594 for (wxChar
*ch
= buf
; *ch
; ch
++)
1596 if (*ch
== wxT('/'))
1601 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1602 // he needs Unix as opposed to Win32 pathnames
1603 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1604 // another example of DOS/Unix mix (Cygwin)
1605 wxString pathUnix
= buf
;
1606 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1607 #endif // __CYGWIN__
1622 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1623 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1624 wxString
str( buffer
);
1630 bool wxSetWorkingDirectory(const wxString
& d
)
1632 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1633 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1634 #elif defined(__WXPM__)
1635 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1636 #elif defined(__WINDOWS__)
1640 // No equivalent in WinCE
1643 return (bool)(SetCurrentDirectory(d
) != 0);
1646 // Must change drive, too.
1647 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1650 wxChar firstChar
= d
[0];
1654 firstChar
= firstChar
- 32;
1656 // To a drive number
1657 unsigned int driveNo
= firstChar
- 64;
1660 unsigned int noDrives
;
1661 _dos_setdrive(driveNo
, &noDrives
);
1664 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1672 // Get the OS directory if appropriate (such as the Windows directory).
1673 // On non-Windows platform, probably just return the empty string.
1674 wxString
wxGetOSDirectory()
1677 return wxString(wxT("\\Windows"));
1678 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1680 GetWindowsDirectory(buf
, 256);
1681 return wxString(buf
);
1682 #elif defined(__WXMAC__)
1683 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1685 return wxEmptyString
;
1689 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1691 size_t len
= wxStrlen(pszFileName
);
1693 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1696 // find a file in a list of directories, returns FALSE if not found
1697 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1699 // we assume that it's not empty
1700 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1701 _T("empty file name in wxFindFileInPath"));
1703 // skip path separator in the beginning of the file name if present
1704 if ( wxIsPathSeparator(*pszFile
) )
1707 // copy the path (strtok will modify it)
1708 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1709 wxStrcpy(szPath
, pszPath
);
1712 wxChar
*pc
, *save_ptr
;
1713 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1715 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1717 // search for the file in this directory
1719 if ( !wxEndsWithPathSeparator(pc
) )
1720 strFile
+= wxFILE_SEP_PATH
;
1723 if ( wxFileExists(strFile
) ) {
1729 // suppress warning about unused variable save_ptr when wxStrtok() is a
1730 // macro which throws away its third argument
1735 return pc
!= NULL
; // if TRUE => we breaked from the loop
1738 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1743 // it can be empty, but it shouldn't be NULL
1744 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1746 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1749 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1752 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1753 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1754 0, FILE_ATTRIBUTE_NORMAL
, 0);
1755 if (fileHandle
== INVALID_HANDLE_VALUE
)
1759 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1761 CloseHandle(fileHandle
);
1763 wxDateTime dateTime
;
1765 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1767 wxLogLastError(_T("FileTimeToLocalFileTime"));
1771 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1773 wxLogLastError(_T("FileTimeToSystemTime"));
1776 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1777 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1778 return dateTime
.GetTicks();
1785 wxStat( filename
, &buf
);
1787 return buf
.st_mtime
;
1792 //------------------------------------------------------------------------
1793 // wild character routines
1794 //------------------------------------------------------------------------
1796 bool wxIsWild( const wxString
& pattern
)
1798 wxString tmp
= pattern
;
1799 wxChar
*pat
= WXSTRINGCAST(tmp
);
1804 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1815 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1817 * The match procedure is public domain code (from ircII's reg.c)
1820 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1824 /* Match if both are empty. */
1828 const wxChar
*m
= pat
.c_str(),
1839 if (dot_special
&& (*n
== wxT('.')))
1841 /* Never match so that hidden Unix files
1842 * are never found. */
1856 else if (*m
== wxT('?'))
1864 if (*m
== wxT('\\'))
1867 /* Quoting "nothing" is a bad thing */
1874 * If we are out of both strings or we just
1875 * saw a wildcard, then we can say we have a
1886 * We could check for *n == NULL at this point, but
1887 * since it's more common to have a character there,
1888 * check to see if they match first (m and n) and
1889 * then if they don't match, THEN we can check for
1907 * If there are no more characters in the
1908 * string, but we still need to find another
1909 * character (*m != NULL), then it will be
1910 * impossible to match it
1917 if (*np
== wxT(' '))
1943 #pragma warning(default:4706) // assignment within conditional expression