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 #if defined(__WXMAC__) && !defined(__DARWIN__)
201 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
203 return stat( wxMacStringToCString( file_name
), buf
);
206 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
208 return access( wxMacStringToCString( pathname
), mode
);
211 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
213 return open( wxMacStringToCString( pathname
), flags
, mode
);
218 #ifdef wxNEED_WX_UNISTD_H
220 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
222 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
225 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
227 return access( wxConvFile
.cWX2MB( pathname
), mode
);
230 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
232 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
236 // wxNEED_WX_UNISTD_H
238 // ----------------------------------------------------------------------------
240 // ----------------------------------------------------------------------------
242 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
244 static inline wxChar
* MYcopystring(const wxString
& s
)
246 wxChar
* copy
= new wxChar
[s
.length() + 1];
247 return wxStrcpy(copy
, s
.c_str());
250 static inline wxChar
* MYcopystring(const wxChar
* s
)
252 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
253 return wxStrcpy(copy
, s
);
256 void wxPathList::Add (const wxString
& path
)
258 wxStringList::Add (WXSTRINGCAST path
);
261 // Add paths e.g. from the PATH environment variable
262 void wxPathList::AddEnvList (const wxString
& envVariable
)
264 // No environment variables on WinCE
266 static const wxChar PATH_TOKS
[] =
269 The space has been removed from the tokenizers, otherwise a
270 path such as "C:\Program Files" would be split into 2 paths:
271 "C:\Program" and "Files"
273 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
274 wxT(";"); // Don't seperate with colon in DOS (used for drive)
279 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
282 wxChar
*s
= MYcopystring (val
);
283 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
290 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
298 // suppress warning about unused variable save_ptr when wxStrtok() is a
299 // macro which throws away its third argument
307 // Given a full filename (with path), ensure that that file can
308 // be accessed again USING FILENAME ONLY by adding the path
309 // to the list if not already there.
310 void wxPathList::EnsureFileAccessible (const wxString
& path
)
312 wxString
path_only(wxPathOnly(path
));
313 if ( !path_only
.IsEmpty() )
315 if ( !Member(path_only
) )
320 bool wxPathList::Member (const wxString
& path
)
322 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
324 wxString
path2( node
->GetData() );
326 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
328 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
330 // Case sensitive File System
331 path
.CompareTo (path2
) == 0
339 wxString
wxPathList::FindValidPath (const wxString
& file
)
341 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
342 return wxString(wxFileFunctionsBuffer
);
344 wxChar buf
[_MAXPATHLEN
];
345 wxStrcpy(buf
, wxFileFunctionsBuffer
);
347 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
348 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
350 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
352 const wxChar
*path
= node
->GetData();
353 wxStrcpy (wxFileFunctionsBuffer
, path
);
354 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
355 if (ch
!= wxT('\\') && ch
!= wxT('/'))
356 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
357 wxStrcat (wxFileFunctionsBuffer
, filename
);
359 wxUnix2DosFilename (wxFileFunctionsBuffer
);
361 if (wxFileExists (wxFileFunctionsBuffer
))
363 return wxString(wxFileFunctionsBuffer
); // Found!
367 return wxEmptyString
; // Not found
370 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
372 wxString f
= FindValidPath(file
);
373 if ( wxIsAbsolutePath(f
) )
377 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
379 if ( !wxEndsWithPathSeparator(buf
) )
381 buf
+= wxFILE_SEP_PATH
;
389 wxFileExists (const wxString
& filename
)
391 // we must use GetFileAttributes() instead of the ANSI C functions because
392 // it can cope with network (UNC) paths unlike them
393 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
394 DWORD ret
= ::GetFileAttributes(filename
);
396 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
399 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
400 #endif // __WIN32__/!__WIN32__
404 wxIsAbsolutePath (const wxString
& filename
)
406 if (filename
!= wxT(""))
408 #if defined(__WXMAC__) && !defined(__DARWIN__)
409 // Classic or Carbon CodeWarrior like
410 // Carbon with Apple DevTools is Unix like
412 // This seems wrong to me, but there is no fix. since
413 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
414 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
415 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
418 // Unix like or Windows
419 if (filename
[0] == wxT('/'))
423 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
428 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
436 * Strip off any extension (dot something) from end of file,
437 * IF one exists. Inserts zero into buffer.
441 void wxStripExtension(wxChar
*buffer
)
443 int len
= wxStrlen(buffer
);
447 if (buffer
[i
] == wxT('.'))
456 void wxStripExtension(wxString
& buffer
)
458 size_t len
= buffer
.Length();
462 if (buffer
.GetChar(i
) == wxT('.'))
464 buffer
= buffer
.Left(i
);
471 // Destructive removal of /./ and /../ stuff
472 wxChar
*wxRealPath (wxChar
*path
)
475 static const wxChar SEP
= wxT('\\');
476 wxUnix2DosFilename(path
);
478 static const wxChar SEP
= wxT('/');
480 if (path
[0] && path
[1]) {
481 /* MATTHEW: special case "/./x" */
483 if (path
[2] == SEP
&& path
[1] == wxT('.'))
491 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
494 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
499 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
500 && (q
- 1 <= path
|| q
[-1] != SEP
))
503 if (path
[0] == wxT('\0'))
509 /* Check that path[2] is NULL! */
510 else if (path
[1] == wxT(':') && !path
[2])
519 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
528 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
530 if (filename
== wxT(""))
531 return (wxChar
*) NULL
;
533 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
534 wxChar buf
[_MAXPATHLEN
];
536 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
537 wxChar ch
= buf
[wxStrlen(buf
) - 1];
539 if (ch
!= wxT('\\') && ch
!= wxT('/'))
540 wxStrcat(buf
, wxT("\\"));
543 wxStrcat(buf
, wxT("/"));
545 wxStrcat(buf
, wxFileFunctionsBuffer
);
546 return MYcopystring( wxRealPath(buf
) );
548 return MYcopystring( wxFileFunctionsBuffer
);
554 ~user/ => user's home dir
555 If the environment variable a = "foo" and b = "bar" then:
572 /* input name in name, pathname output to buf. */
574 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
576 register wxChar
*d
, *s
, *nm
;
577 wxChar lnm
[_MAXPATHLEN
];
580 // Some compilers don't like this line.
581 // const wxChar trimchars[] = wxT("\n \t");
584 trimchars
[0] = wxT('\n');
585 trimchars
[1] = wxT(' ');
586 trimchars
[2] = wxT('\t');
590 const wxChar SEP
= wxT('\\');
592 const wxChar SEP
= wxT('/');
595 if (name
== NULL
|| *name
== wxT('\0'))
597 nm
= MYcopystring(name
); // Make a scratch copy
600 /* Skip leading whitespace and cr */
601 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
603 /* And strip off trailing whitespace and cr */
604 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
605 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
613 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
616 /* Expand inline environment variables */
634 while ((*d
++ = *s
) != 0) {
636 if (*s
== wxT('\\')) {
637 if ((*(d
- 1) = *++s
)) {
645 // No env variables on WinCE
648 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
650 if (*s
++ == wxT('$'))
653 register wxChar
*start
= d
;
654 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
655 register wxChar
*value
;
656 while ((*d
++ = *s
) != 0)
657 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
662 value
= wxGetenv(braces
? start
+ 1 : start
);
664 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
678 /* Expand ~ and ~user */
680 if (nm
[0] == wxT('~') && !q
)
683 if (nm
[1] == SEP
|| nm
[1] == 0)
685 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
686 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
691 { /* ~user/filename */
692 register wxChar
*nnm
;
693 register wxChar
*home
;
694 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
698 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
699 was_sep
= (*s
== SEP
);
700 nnm
= *s
? s
+ 1 : s
;
702 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
703 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
704 if (was_sep
) /* replace only if it was there: */
715 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
717 while (wxT('\0') != (*d
++ = *s
++))
720 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
724 while ((*d
++ = *s
++) != 0)
728 delete[] nm_tmp
; // clean up alloc
729 /* Now clean up the buffer */
730 return wxRealPath(buf
);
733 /* Contract Paths to be build upon an environment variable
736 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
738 The call wxExpandPath can convert these back!
741 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
743 static wxChar dest
[_MAXPATHLEN
];
745 if (filename
== wxT(""))
746 return (wxChar
*) NULL
;
748 wxStrcpy (dest
, WXSTRINGCAST filename
);
750 wxUnix2DosFilename(dest
);
753 // Handle environment
754 const wxChar
*val
= (const wxChar
*) NULL
;
756 wxChar
*tcp
= (wxChar
*) NULL
;
757 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
758 (tcp
= wxStrstr (dest
, val
)) != NULL
)
760 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
763 wxStrcpy (tcp
, WXSTRINGCAST envname
);
764 wxStrcat (tcp
, wxT("}"));
765 wxStrcat (tcp
, wxFileFunctionsBuffer
);
769 // Handle User's home (ignore root homes!)
771 if ((val
= wxGetUserHome (user
)) != NULL
&&
772 (len
= wxStrlen(val
)) > 2 &&
773 wxStrncmp(dest
, val
, len
) == 0)
775 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
777 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
778 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
779 wxStrcpy (dest
, wxFileFunctionsBuffer
);
785 // Return just the filename, not the path (basename)
786 wxChar
*wxFileNameFromPath (wxChar
*path
)
789 wxString n
= wxFileNameFromPath(p
);
791 return path
+ p
.length() - n
.length();
794 wxString
wxFileNameFromPath (const wxString
& path
)
797 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
799 wxString fullname
= name
;
802 fullname
<< wxFILE_SEP_EXT
<< ext
;
808 // Return just the directory, or NULL if no directory
810 wxPathOnly (wxChar
*path
)
814 static wxChar buf
[_MAXPATHLEN
];
817 wxStrcpy (buf
, path
);
819 int l
= wxStrlen(path
);
822 // Search backward for a backward or forward slash
825 #if defined(__WXMAC__) && !defined(__DARWIN__)
826 // Classic or Carbon CodeWarrior like
827 // Carbon with Apple DevTools is Unix like
828 if (path
[i
] == wxT(':') )
834 // Unix like or Windows
835 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
842 if (path
[i
] == wxT(']'))
851 #if defined(__WXMSW__) || defined(__WXPM__)
852 // Try Drive specifier
853 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
855 // A:junk --> A:. (since A:.\junk Not A:\junk)
862 return (wxChar
*) NULL
;
865 // Return just the directory, or NULL if no directory
866 wxString
wxPathOnly (const wxString
& path
)
870 wxChar buf
[_MAXPATHLEN
];
873 wxStrcpy (buf
, WXSTRINGCAST path
);
875 int l
= path
.Length();
878 // Search backward for a backward or forward slash
881 #if defined(__WXMAC__) && !defined(__DARWIN__)
882 // Classic or Carbon CodeWarrior like
883 // Carbon with Apple DevTools is Unix like
884 if (path
[i
] == wxT(':') )
887 return wxString(buf
);
890 // Unix like or Windows
891 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
894 return wxString(buf
);
898 if (path
[i
] == wxT(']'))
901 return wxString(buf
);
907 #if defined(__WXMSW__) || defined(__WXPM__)
908 // Try Drive specifier
909 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
911 // A:junk --> A:. (since A:.\junk Not A:\junk)
914 return wxString(buf
);
918 return wxString(wxT(""));
921 // Utility for converting delimiters in DOS filenames to UNIX style
922 // and back again - or we get nasty problems with delimiters.
923 // Also, convert to lower case, since case is significant in UNIX.
925 #if defined(__WXMAC__)
926 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
933 Boolean isDirectory
= FALSE
;
934 Str255 theParentPath
= "\p";
935 FSSpec theParentSpec
;
937 char theFileName
[FILENAME_MAX
];
938 char thePath
[FILENAME_MAX
];
942 // GD: Separate file name from path and make a FSRef to the parent
943 // directory. This is necessary since FSRefs cannot reference files
944 // that have not yet been created.
945 // Based on example code from Apple Technical Note TN2022
946 // http://developer.apple.com/technotes/tn/tn2022.html
948 // check whether we are converting a directory
949 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
950 // count length of file name
951 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
953 // prepend path separator since it will later be appended to the path
954 theFileName
[0] = wxFILE_SEP_PATH
;
955 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
956 theFileName
[j
- i
] = spec
->name
[j
];
958 theFileName
[j
- i
] = '\0';
960 for (j
= 1; j
<= i
; j
++) {
961 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
963 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
964 if (theErr
== noErr
) {
965 // convert the FSSpec to an FSRef
966 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
968 if (theErr
== noErr
) {
969 // get the POSIX path associated with the FSRef
970 theStatus
= FSRefMakePath(&theParentRef
,
971 (UInt8
*)thePath
, sizeof(thePath
));
973 if (theStatus
== noErr
) {
974 // append file name to path
975 // includes previously prepended path separator
976 strcat(thePath
, theFileName
);
979 // create path string for return value
980 wxString
result( thePath
) ;
985 // get length of path and allocate handle
986 FSpGetFullPath( spec
, &length
, &myPath
) ;
987 ::SetHandleSize( myPath
, length
+ 1 ) ;
989 (*myPath
)[length
] = 0 ;
990 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
991 (*myPath
)[length
-1] = 0 ;
993 // create path string for return value
994 wxString result
= wxMacMakeStringFromCString( *myPath
) ;
996 // free allocated handle
997 ::HUnlock( myPath
) ;
998 ::DisposeHandle( myPath
) ;
1004 // Mac file names are POSIX (Unix style) under Darwin
1005 // therefore the conversion functions below are not needed
1007 static wxChar sMacFileNameConversion
[ 1000 ] ;
1008 static char scMacFileNameConversion
[ 1000 ] ;
1011 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
1013 OSStatus err
= noErr
;
1017 // get the FSRef associated with the POSIX path
1018 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
1019 // convert the FSRef to an FSSpec
1020 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
1022 if ( strchr( path
, ':' ) == NULL
)
1024 // try whether it is a volume / or a mounted volume
1025 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
1026 scMacFileNameConversion
[998] = 0 ;
1027 strcat( scMacFileNameConversion
, ":" ) ;
1028 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
1032 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
1038 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
1040 return wxMacFilename2FSSpec( wxMacStringToCString( wxString( path
) ) , spec
) ;
1046 wxString
wxMac2UnixFilename (const wxChar
*str
)
1048 wxChar
*s
= sMacFileNameConversion
;
1049 wxStrcpy( s
, str
) ;
1052 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1063 *s
= wxTolower(*s
); // Case INDEPENDENT
1067 return wxString(sMacFileNameConversion
) ;
1070 wxString
wxUnix2MacFilename (const wxChar
*str
)
1072 wxChar
*s
= sMacFileNameConversion
;
1073 wxStrcpy( s
, str
) ;
1078 // relative path , since it goes on with slash which is translated to a :
1079 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1081 else if ( *s
== '/' )
1083 // absolute path -> on mac just start with the drive name
1084 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1088 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1092 if (*s
== '/' || *s
== '\\')
1094 // convert any back-directory situations
1095 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1098 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1106 return wxString(sMacFileNameConversion
) ;
1109 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1111 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1114 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1116 wxString var
= wxUnix2MacFilename( path
) ;
1117 wxMacFilename2FSSpec( var
, spec
) ;
1119 #endif // ! __DARWIN__
1124 wxDos2UnixFilename (wxChar
*s
)
1133 *s
= wxTolower (*s
); // Case INDEPENDENT
1140 #if defined(__WXMSW__) || defined(__WXPM__)
1141 wxUnix2DosFilename (wxChar
*s
)
1143 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1146 // Yes, I really mean this to happen under DOS only! JACS
1147 #if defined(__WXMSW__) || defined(__WXPM__)
1158 // Concatenate two files to form third
1160 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1163 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1166 FILE *fp1
= (FILE *) NULL
;
1167 FILE *fp2
= (FILE *) NULL
;
1168 FILE *fp3
= (FILE *) NULL
;
1169 // Open the inputs and outputs
1170 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1171 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1172 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1184 while ((ch
= getc (fp1
)) != EOF
)
1185 (void) putc (ch
, fp3
);
1188 while ((ch
= getc (fp2
)) != EOF
)
1189 (void) putc (ch
, fp3
);
1193 bool result
= wxRenameFile(outfile
, file3
);
1199 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1201 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1202 // CopyFile() copies file attributes and modification time too, so use it
1203 // instead of our code if available
1205 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1206 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1208 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1209 file1
.c_str(), file2
.c_str());
1213 #elif defined(__WXPM__)
1214 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1219 // get permissions of file1
1220 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1222 // the file probably doesn't exist or we haven't the rights to read
1224 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1229 // open file1 for reading
1230 wxFile
fileIn(file1
, wxFile::read
);
1231 if ( !fileIn
.IsOpened() )
1234 // remove file2, if it exists. This is needed for creating
1235 // file2 with the correct permissions in the next step
1236 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1238 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1244 // reset the umask as we want to create the file with exactly the same
1245 // permissions as the original one
1246 mode_t oldUmask
= umask( 0 );
1249 // create file2 with the same permissions than file1 and open it for
1253 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1257 /// restore the old umask
1261 // copy contents of file1 to file2
1266 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1267 if ( fileIn
.Error() )
1274 if ( fileOut
.Write(buf
, count
) < count
)
1278 // we can expect fileIn to be closed successfully, but we should ensure
1279 // that fileOut was closed as some write errors (disk full) might not be
1280 // detected before doing this
1281 if ( !fileIn
.Close() || !fileOut
.Close() )
1284 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1285 // no chmod in VA. Should be some permission API for HPFS386 partitions
1287 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1289 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1293 #endif // OS/2 || Mac
1294 #endif // __WXMSW__ && __WIN32__
1300 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1303 // Normal system call
1304 if ( wxRename (file1
, file2
) == 0 )
1309 if (wxCopyFile(file1
, file2
)) {
1310 wxRemoveFile(file1
);
1317 bool wxRemoveFile(const wxString
& file
)
1319 #if defined(__VISUALC__) \
1320 || defined(__BORLANDC__) \
1321 || defined(__WATCOMC__) \
1322 || defined(__GNUWIN32__)
1323 int res
= wxRemove(file
);
1324 #elif defined(__WXMAC__)
1325 int res
= unlink(wxFNCONV(file
));
1327 int res
= unlink(OS_FILENAME(file
));
1333 bool wxMkdir(const wxString
& dir
, int perm
)
1335 #if defined(__WXMAC__) && !defined(__UNIX__)
1336 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1338 const wxChar
*dirname
= dir
.c_str();
1340 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1341 // for the GNU compiler
1342 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1344 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1346 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1348 #elif defined(__WXPM__)
1349 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1350 #elif defined(__DOS__)
1351 #if defined(__WATCOMC__)
1353 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1354 #elif defined(__DJGPP__)
1355 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1357 #error "Unsupported DOS compiler!"
1359 #else // !MSW, !DOS and !OS/2 VAC++
1362 if ( !CreateDirectory(dirname
, NULL
) )
1364 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1368 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1377 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1380 return FALSE
; //to be changed since rmdir exists in VMS7.x
1381 #elif defined(__WXPM__)
1382 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1386 return (CreateDirectory(dir
, NULL
) != 0);
1388 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1394 // does the path exists? (may have or not '/' or '\\' at the end)
1395 bool wxPathExists(const wxChar
*pszPathName
)
1397 wxString
strPath(pszPathName
);
1400 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1401 // so remove all trailing backslashes from the path - but don't do this for
1402 // the pathes "d:\" (which are different from "d:") nor for just "\"
1403 while ( wxEndsWithPathSeparator(strPath
) )
1405 size_t len
= strPath
.length();
1406 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1409 strPath
.Truncate(len
- 1);
1411 #endif // __WINDOWS__
1413 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1414 // stat() can't cope with network paths
1415 DWORD ret
= ::GetFileAttributes(strPath
);
1417 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1421 #ifndef __VISAGECPP__
1422 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1424 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1425 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1428 #endif // __WIN32__/!__WIN32__
1431 // Get a temporary filename, opening and closing the file.
1432 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1434 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1435 if ( filename
.empty() )
1439 wxStrcpy(buf
, filename
);
1441 buf
= MYcopystring(filename
);
1446 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1448 buf
= wxFileName::CreateTempFileName(prefix
);
1450 return !buf
.empty();
1453 // Get first file name matching given wild card.
1455 static wxDir
*gs_dir
= NULL
;
1456 static wxString gs_dirPath
;
1458 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1460 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1461 if ( gs_dirPath
.IsEmpty() )
1462 gs_dirPath
= wxT(".");
1463 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1464 gs_dirPath
<< wxFILE_SEP_PATH
;
1468 gs_dir
= new wxDir(gs_dirPath
);
1470 if ( !gs_dir
->IsOpened() )
1472 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1473 return wxEmptyString
;
1479 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1480 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1481 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1485 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1486 if ( result
.IsEmpty() )
1492 return gs_dirPath
+ result
;
1495 wxString
wxFindNextFile()
1497 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1500 gs_dir
->GetNext(&result
);
1502 if ( result
.IsEmpty() )
1508 return gs_dirPath
+ result
;
1512 // Get current working directory.
1513 // If buf is NULL, allocates space using new, else
1515 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1522 buf
= new wxChar
[sz
+ 1];
1527 // for the compilers which have Unicode version of _getcwd(), call it
1528 // directly, for the others call the ANSI version and do the translation
1531 #else // wxUSE_UNICODE
1532 bool needsANSI
= TRUE
;
1534 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1535 // This is not legal code as the compiler
1536 // is allowed destroy the wxCharBuffer.
1537 // wxCharBuffer c_buffer(sz);
1538 // char *cbuf = (char*)(const char*)c_buffer;
1539 char cbuf
[_MAXPATHLEN
];
1543 #if wxUSE_UNICODE_MSLU
1544 if ( wxGetOsVersion() != wxWIN95
)
1546 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1549 ok
= _wgetcwd(buf
, sz
) != NULL
;
1555 #endif // wxUSE_UNICODE
1557 #if defined(_MSC_VER) || defined(__MINGW32__)
1558 ok
= _getcwd(cbuf
, sz
) != NULL
;
1559 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1564 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1566 pb
.ioRefNum
= LMGetCurApRefNum();
1568 error
= PBGetFCBInfoSync(&pb
);
1569 if ( error
== noErr
)
1571 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1572 cwdSpec
.parID
= pb
.ioFCBParID
;
1573 cwdSpec
.name
[0] = 0 ;
1574 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1575 wxStrcpy( buf
, res
) ;
1582 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1584 rc
= ::DosQueryCurrentDir( 0 // current drive
1589 #else // !Win32/VC++ !Mac !OS2
1590 ok
= getcwd(cbuf
, sz
) != NULL
;
1593 #if wxUSE_UNICODE && !defined(__WXMAC__)
1594 // finally convert the result to Unicode if needed
1595 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1596 #endif // wxUSE_UNICODE
1601 wxLogSysError(_("Failed to get the working directory"));
1603 // VZ: the old code used to return "." on error which didn't make any
1604 // sense at all to me - empty string is a better error indicator
1605 // (NULL might be even better but I'm afraid this could lead to
1606 // problems with the old code assuming the return is never NULL)
1609 else // ok, but we might need to massage the path into the right format
1612 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1613 // with / deliminers. We don't like that.
1614 for (wxChar
*ch
= buf
; *ch
; ch
++)
1616 if (*ch
== wxT('/'))
1621 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1622 // he needs Unix as opposed to Win32 pathnames
1623 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1624 // another example of DOS/Unix mix (Cygwin)
1625 wxString pathUnix
= buf
;
1626 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1627 #endif // __CYGWIN__
1642 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1643 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1644 wxString
str( buffer
);
1650 bool wxSetWorkingDirectory(const wxString
& d
)
1652 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1653 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1654 #elif defined(__WXPM__)
1655 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1656 #elif defined(__WINDOWS__)
1660 // No equivalent in WinCE
1663 return (bool)(SetCurrentDirectory(d
) != 0);
1666 // Must change drive, too.
1667 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1670 wxChar firstChar
= d
[0];
1674 firstChar
= firstChar
- 32;
1676 // To a drive number
1677 unsigned int driveNo
= firstChar
- 64;
1680 unsigned int noDrives
;
1681 _dos_setdrive(driveNo
, &noDrives
);
1684 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1692 // Get the OS directory if appropriate (such as the Windows directory).
1693 // On non-Windows platform, probably just return the empty string.
1694 wxString
wxGetOSDirectory()
1697 return wxString(wxT("\\Windows"));
1698 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1700 GetWindowsDirectory(buf
, 256);
1701 return wxString(buf
);
1702 #elif defined(__WXMAC__)
1703 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1705 return wxEmptyString
;
1709 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1711 size_t len
= wxStrlen(pszFileName
);
1713 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1716 // find a file in a list of directories, returns FALSE if not found
1717 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1719 // we assume that it's not empty
1720 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1721 _T("empty file name in wxFindFileInPath"));
1723 // skip path separator in the beginning of the file name if present
1724 if ( wxIsPathSeparator(*pszFile
) )
1727 // copy the path (strtok will modify it)
1728 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1729 wxStrcpy(szPath
, pszPath
);
1732 wxChar
*pc
, *save_ptr
;
1733 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1735 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1737 // search for the file in this directory
1739 if ( !wxEndsWithPathSeparator(pc
) )
1740 strFile
+= wxFILE_SEP_PATH
;
1743 if ( wxFileExists(strFile
) ) {
1749 // suppress warning about unused variable save_ptr when wxStrtok() is a
1750 // macro which throws away its third argument
1755 return pc
!= NULL
; // if TRUE => we breaked from the loop
1758 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1763 // it can be empty, but it shouldn't be NULL
1764 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1766 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1769 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1772 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1773 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1774 0, FILE_ATTRIBUTE_NORMAL
, 0);
1775 if (fileHandle
== INVALID_HANDLE_VALUE
)
1779 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1781 CloseHandle(fileHandle
);
1783 wxDateTime dateTime
;
1785 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1787 wxLogLastError(_T("FileTimeToLocalFileTime"));
1791 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1793 wxLogLastError(_T("FileTimeToSystemTime"));
1796 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1797 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1798 return dateTime
.GetTicks();
1805 wxStat( filename
, &buf
);
1807 return buf
.st_mtime
;
1812 //------------------------------------------------------------------------
1813 // wild character routines
1814 //------------------------------------------------------------------------
1816 bool wxIsWild( const wxString
& pattern
)
1818 wxString tmp
= pattern
;
1819 wxChar
*pat
= WXSTRINGCAST(tmp
);
1824 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1835 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1837 * The match procedure is public domain code (from ircII's reg.c)
1840 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1844 /* Match if both are empty. */
1848 const wxChar
*m
= pat
.c_str(),
1859 if (dot_special
&& (*n
== wxT('.')))
1861 /* Never match so that hidden Unix files
1862 * are never found. */
1876 else if (*m
== wxT('?'))
1884 if (*m
== wxT('\\'))
1887 /* Quoting "nothing" is a bad thing */
1894 * If we are out of both strings or we just
1895 * saw a wildcard, then we can say we have a
1906 * We could check for *n == NULL at this point, but
1907 * since it's more common to have a character there,
1908 * check to see if they match first (m and n) and
1909 * then if they don't match, THEN we can check for
1927 * If there are no more characters in the
1928 * string, but we still need to find another
1929 * character (*m != NULL), then it will be
1930 * impossible to match it
1937 if (*np
== wxT(' '))
1963 #pragma warning(default:4706) // assignment within conditional expression