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>
77 #include "wx/os2/private.h"
79 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
80 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
85 #endif // native Win compiler
98 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
99 // this (3.1 I believe) and how to test for it.
100 // If this works for Borland 4.0 as well, then no worries.
111 // No, Cygwin doesn't appear to have fnmatch.h after all.
112 #if defined(HAVE_FNMATCH_H)
118 #include "wx/msw/mslu.h"
120 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
122 // note that it must be included after <windows.h>
125 #include <sys/cygwin.h>
129 #include <sys/unistd.h>
131 #endif // __GNUWIN32__
132 #endif // __WINDOWS__
134 // TODO: Borland probably has _wgetcwd as well?
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
144 #define _MAXPATHLEN 1024
149 # include "MoreFilesX.h"
151 # include "MoreFiles.h"
152 # include "MoreFilesExtras.h"
153 # include "FullPath.h"
154 # include "FSpCompat.h"
158 // ----------------------------------------------------------------------------
160 // ----------------------------------------------------------------------------
162 // MT-FIXME: get rid of this horror and all code using it
163 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
165 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
167 // VisualAge C++ V4.0 cannot have any external linkage const decs
168 // in headers included by more than one primary source
170 const off_t wxInvalidOffset
= (off_t
)-1;
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
177 // we need to translate Mac filenames before passing them to OS functions
178 #define OS_FILENAME(s) (s.fn_str())
180 // ============================================================================
182 // ============================================================================
184 #ifdef wxNEED_WX_UNISTD_H
186 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
188 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
191 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
193 return access( wxConvFile
.cWX2MB( pathname
), mode
);
196 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
198 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
202 // wxNEED_WX_UNISTD_H
204 // ----------------------------------------------------------------------------
206 // ----------------------------------------------------------------------------
208 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
210 void wxPathList::Add (const wxString
& path
)
212 wxStringList::Add (WXSTRINGCAST path
);
215 // Add paths e.g. from the PATH environment variable
216 void wxPathList::AddEnvList (const wxString
& envVariable
)
218 static const wxChar PATH_TOKS
[] =
221 The space has been removed from the tokenizers, otherwise a
222 path such as "C:\Program Files" would be split into 2 paths:
223 "C:\Program" and "Files"
225 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
226 wxT(";"); // Don't seperate with colon in DOS (used for drive)
231 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
234 wxChar
*s
= copystring (val
);
235 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
242 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
250 // suppress warning about unused variable save_ptr when wxStrtok() is a
251 // macro which throws away its third argument
258 // Given a full filename (with path), ensure that that file can
259 // be accessed again USING FILENAME ONLY by adding the path
260 // to the list if not already there.
261 void wxPathList::EnsureFileAccessible (const wxString
& path
)
263 wxString
path_only(wxPathOnly(path
));
264 if ( !path_only
.IsEmpty() )
266 if ( !Member(path_only
) )
271 bool wxPathList::Member (const wxString
& path
)
273 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
275 wxString
path2( node
->GetData() );
277 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
279 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
281 // Case sensitive File System
282 path
.CompareTo (path2
) == 0
290 wxString
wxPathList::FindValidPath (const wxString
& file
)
292 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
293 return wxString(wxFileFunctionsBuffer
);
295 wxChar buf
[_MAXPATHLEN
];
296 wxStrcpy(buf
, wxFileFunctionsBuffer
);
298 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
299 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
301 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
303 wxChar
*path
= node
->GetData();
304 wxStrcpy (wxFileFunctionsBuffer
, path
);
305 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
306 if (ch
!= wxT('\\') && ch
!= wxT('/'))
307 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
308 wxStrcat (wxFileFunctionsBuffer
, filename
);
310 wxUnix2DosFilename (wxFileFunctionsBuffer
);
312 if (wxFileExists (wxFileFunctionsBuffer
))
314 return wxString(wxFileFunctionsBuffer
); // Found!
318 return wxEmptyString
; // Not found
321 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
323 wxString f
= FindValidPath(file
);
324 if ( wxIsAbsolutePath(f
) )
328 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
330 if ( !wxEndsWithPathSeparator(buf
) )
332 buf
+= wxFILE_SEP_PATH
;
340 wxFileExists (const wxString
& filename
)
342 // we must use GetFileAttributes() instead of the ANSI C functions because
343 // it can cope with network (UNC) paths unlike them
344 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
345 DWORD ret
= ::GetFileAttributes(filename
);
347 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
350 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
351 #endif // __WIN32__/!__WIN32__
355 wxIsAbsolutePath (const wxString
& filename
)
357 if (filename
!= wxT(""))
359 #if defined(__WXMAC__) && !defined(__DARWIN__)
360 // Classic or Carbon CodeWarrior like
361 // Carbon with Apple DevTools is Unix like
363 // This seems wrong to me, but there is no fix. since
364 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
365 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
366 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
369 // Unix like or Windows
370 if (filename
[0] == wxT('/'))
374 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
379 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
387 * Strip off any extension (dot something) from end of file,
388 * IF one exists. Inserts zero into buffer.
392 void wxStripExtension(wxChar
*buffer
)
394 int len
= wxStrlen(buffer
);
398 if (buffer
[i
] == wxT('.'))
407 void wxStripExtension(wxString
& buffer
)
409 size_t len
= buffer
.Length();
413 if (buffer
.GetChar(i
) == wxT('.'))
415 buffer
= buffer
.Left(i
);
422 // Destructive removal of /./ and /../ stuff
423 wxChar
*wxRealPath (wxChar
*path
)
426 static const wxChar SEP
= wxT('\\');
427 wxUnix2DosFilename(path
);
429 static const wxChar SEP
= wxT('/');
431 if (path
[0] && path
[1]) {
432 /* MATTHEW: special case "/./x" */
434 if (path
[2] == SEP
&& path
[1] == wxT('.'))
442 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
445 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
450 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
451 && (q
- 1 <= path
|| q
[-1] != SEP
))
454 if (path
[0] == wxT('\0'))
460 /* Check that path[2] is NULL! */
461 else if (path
[1] == wxT(':') && !path
[2])
470 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
479 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
481 if (filename
== wxT(""))
482 return (wxChar
*) NULL
;
484 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
485 wxChar buf
[_MAXPATHLEN
];
487 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
488 wxChar ch
= buf
[wxStrlen(buf
) - 1];
490 if (ch
!= wxT('\\') && ch
!= wxT('/'))
491 wxStrcat(buf
, wxT("\\"));
494 wxStrcat(buf
, wxT("/"));
496 wxStrcat(buf
, wxFileFunctionsBuffer
);
497 return copystring( wxRealPath(buf
) );
499 return copystring( wxFileFunctionsBuffer
);
505 ~user/ => user's home dir
506 If the environment variable a = "foo" and b = "bar" then:
523 /* input name in name, pathname output to buf. */
525 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
527 register wxChar
*d
, *s
, *nm
;
528 wxChar lnm
[_MAXPATHLEN
];
531 // Some compilers don't like this line.
532 // const wxChar trimchars[] = wxT("\n \t");
535 trimchars
[0] = wxT('\n');
536 trimchars
[1] = wxT(' ');
537 trimchars
[2] = wxT('\t');
541 const wxChar SEP
= wxT('\\');
543 const wxChar SEP
= wxT('/');
546 if (name
== NULL
|| *name
== wxT('\0'))
548 nm
= copystring(name
); // Make a scratch copy
551 /* Skip leading whitespace and cr */
552 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
554 /* And strip off trailing whitespace and cr */
555 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
556 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
564 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
567 /* Expand inline environment variables */
585 while ((*d
++ = *s
) != 0) {
587 if (*s
== wxT('\\')) {
588 if ((*(d
- 1) = *++s
)) {
597 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
599 if (*s
++ == wxT('$'))
602 register wxChar
*start
= d
;
603 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
604 register wxChar
*value
;
605 while ((*d
++ = *s
) != 0)
606 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
611 value
= wxGetenv(braces
? start
+ 1 : start
);
613 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
625 /* Expand ~ and ~user */
627 if (nm
[0] == wxT('~') && !q
)
630 if (nm
[1] == SEP
|| nm
[1] == 0)
632 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
633 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
638 { /* ~user/filename */
639 register wxChar
*nnm
;
640 register wxChar
*home
;
641 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
645 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
646 was_sep
= (*s
== SEP
);
647 nnm
= *s
? s
+ 1 : s
;
649 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
650 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
651 if (was_sep
) /* replace only if it was there: */
662 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
664 while (wxT('\0') != (*d
++ = *s
++))
667 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
671 while ((*d
++ = *s
++) != 0)
675 delete[] nm_tmp
; // clean up alloc
676 /* Now clean up the buffer */
677 return wxRealPath(buf
);
680 /* Contract Paths to be build upon an environment variable
683 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
685 The call wxExpandPath can convert these back!
688 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
690 static wxChar dest
[_MAXPATHLEN
];
692 if (filename
== wxT(""))
693 return (wxChar
*) NULL
;
695 wxStrcpy (dest
, WXSTRINGCAST filename
);
697 wxUnix2DosFilename(dest
);
700 // Handle environment
701 const wxChar
*val
= (const wxChar
*) NULL
;
702 wxChar
*tcp
= (wxChar
*) NULL
;
703 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
704 (tcp
= wxStrstr (dest
, val
)) != NULL
)
706 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
709 wxStrcpy (tcp
, WXSTRINGCAST envname
);
710 wxStrcat (tcp
, wxT("}"));
711 wxStrcat (tcp
, wxFileFunctionsBuffer
);
714 // Handle User's home (ignore root homes!)
716 if ((val
= wxGetUserHome (user
)) != NULL
&&
717 (len
= wxStrlen(val
)) > 2 &&
718 wxStrncmp(dest
, val
, len
) == 0)
720 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
722 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
723 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
724 wxStrcpy (dest
, wxFileFunctionsBuffer
);
730 // Return just the filename, not the path (basename)
731 wxChar
*wxFileNameFromPath (wxChar
*path
)
734 wxString n
= wxFileNameFromPath(p
);
736 return path
+ p
.length() - n
.length();
739 wxString
wxFileNameFromPath (const wxString
& path
)
742 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
744 wxString fullname
= name
;
747 fullname
<< wxFILE_SEP_EXT
<< ext
;
753 // Return just the directory, or NULL if no directory
755 wxPathOnly (wxChar
*path
)
759 static wxChar buf
[_MAXPATHLEN
];
762 wxStrcpy (buf
, path
);
764 int l
= wxStrlen(path
);
767 // Search backward for a backward or forward slash
770 #if defined(__WXMAC__) && !defined(__DARWIN__)
771 // Classic or Carbon CodeWarrior like
772 // Carbon with Apple DevTools is Unix like
773 if (path
[i
] == wxT(':') )
779 // Unix like or Windows
780 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
787 if (path
[i
] == wxT(']'))
796 #if defined(__WXMSW__) || defined(__WXPM__)
797 // Try Drive specifier
798 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
800 // A:junk --> A:. (since A:.\junk Not A:\junk)
807 return (wxChar
*) NULL
;
810 // Return just the directory, or NULL if no directory
811 wxString
wxPathOnly (const wxString
& path
)
815 wxChar buf
[_MAXPATHLEN
];
818 wxStrcpy (buf
, WXSTRINGCAST path
);
820 int l
= path
.Length();
823 // Search backward for a backward or forward slash
826 #if defined(__WXMAC__) && !defined(__DARWIN__)
827 // Classic or Carbon CodeWarrior like
828 // Carbon with Apple DevTools is Unix like
829 if (path
[i
] == wxT(':') )
832 return wxString(buf
);
835 // Unix like or Windows
836 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
839 return wxString(buf
);
843 if (path
[i
] == wxT(']'))
846 return wxString(buf
);
852 #if defined(__WXMSW__) || defined(__WXPM__)
853 // Try Drive specifier
854 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
856 // A:junk --> A:. (since A:.\junk Not A:\junk)
859 return wxString(buf
);
863 return wxString(wxT(""));
866 // Utility for converting delimiters in DOS filenames to UNIX style
867 // and back again - or we get nasty problems with delimiters.
868 // Also, convert to lower case, since case is significant in UNIX.
870 #if defined(__WXMAC__)
871 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
878 Boolean isDirectory
= FALSE
;
879 Str255 theParentPath
= "\p";
880 FSSpec theParentSpec
;
882 char theFileName
[FILENAME_MAX
];
883 char thePath
[FILENAME_MAX
];
887 // GD: Separate file name from path and make a FSRef to the parent
888 // directory. This is necessary since FSRefs cannot reference files
889 // that have not yet been created.
890 // Based on example code from Apple Technical Note TN2022
891 // http://developer.apple.com/technotes/tn/tn2022.html
893 // check whether we are converting a directory
894 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
895 // count length of file name
896 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
898 // prepend path separator since it will later be appended to the path
899 theFileName
[0] = wxFILE_SEP_PATH
;
900 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
901 theFileName
[j
- i
] = spec
->name
[j
];
903 theFileName
[j
- i
] = '\0';
905 for (j
= 1; j
<= i
; j
++) {
906 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
908 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
909 if (theErr
== noErr
) {
910 // convert the FSSpec to an FSRef
911 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
913 if (theErr
== noErr
) {
914 // get the POSIX path associated with the FSRef
915 theStatus
= FSRefMakePath(&theParentRef
,
916 (UInt8
*)thePath
, sizeof(thePath
));
918 if (theStatus
== noErr
) {
919 // append file name to path
920 // includes previously prepended path separator
921 strcat(thePath
, theFileName
);
924 // create path string for return value
925 wxString
result( thePath
) ;
930 // get length of path and allocate handle
931 FSpGetFullPath( spec
, &length
, &myPath
) ;
932 ::SetHandleSize( myPath
, length
+ 1 ) ;
934 (*myPath
)[length
] = 0 ;
935 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
936 (*myPath
)[length
-1] = 0 ;
938 // create path string for return value
939 wxString result
= wxMacMakeStringFromCString( *myPath
) ;
941 // free allocated handle
942 ::HUnlock( myPath
) ;
943 ::DisposeHandle( myPath
) ;
949 // Mac file names are POSIX (Unix style) under Darwin
950 // therefore the conversion functions below are not needed
952 static wxChar sMacFileNameConversion
[ 1000 ] ;
953 static char scMacFileNameConversion
[ 1000 ] ;
956 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
958 OSStatus err
= noErr
;
962 // get the FSRef associated with the POSIX path
963 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
964 // convert the FSRef to an FSSpec
965 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
967 if ( strchr( path
, ':' ) == NULL
)
969 // try whether it is a volume / or a mounted volume
970 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
971 scMacFileNameConversion
[998] = 0 ;
972 strcat( scMacFileNameConversion
, ":" ) ;
973 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
977 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
983 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
985 return wxMacFilename2FSSpec( wxMacStringToCString( wxString( path
) ) , spec
) ;
991 wxString
wxMac2UnixFilename (const wxChar
*str
)
993 wxChar
*s
= sMacFileNameConversion
;
994 wxStrcpy( s
, str
) ;
997 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1008 *s
= wxTolower(*s
); // Case INDEPENDENT
1012 return wxString(sMacFileNameConversion
) ;
1015 wxString
wxUnix2MacFilename (const wxChar
*str
)
1017 wxChar
*s
= sMacFileNameConversion
;
1018 wxStrcpy( s
, str
) ;
1023 // relative path , since it goes on with slash which is translated to a :
1024 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1026 else if ( *s
== '/' )
1028 // absolute path -> on mac just start with the drive name
1029 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1033 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1037 if (*s
== '/' || *s
== '\\')
1039 // convert any back-directory situations
1040 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1043 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1051 return wxString(sMacFileNameConversion
) ;
1054 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1056 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1059 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1061 wxString var
= wxUnix2MacFilename( path
) ;
1062 wxMacFilename2FSSpec( var
, spec
) ;
1064 #endif // ! __DARWIN__
1069 wxDos2UnixFilename (char *s
)
1078 *s
= wxTolower (*s
); // Case INDEPENDENT
1085 #if defined(__WXMSW__) || defined(__WXPM__)
1086 wxUnix2DosFilename (wxChar
*s
)
1088 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1091 // Yes, I really mean this to happen under DOS only! JACS
1092 #if defined(__WXMSW__) || defined(__WXPM__)
1103 // Concatenate two files to form third
1105 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1108 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1111 FILE *fp1
= (FILE *) NULL
;
1112 FILE *fp2
= (FILE *) NULL
;
1113 FILE *fp3
= (FILE *) NULL
;
1114 // Open the inputs and outputs
1115 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1116 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1117 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1129 while ((ch
= getc (fp1
)) != EOF
)
1130 (void) putc (ch
, fp3
);
1133 while ((ch
= getc (fp2
)) != EOF
)
1134 (void) putc (ch
, fp3
);
1138 bool result
= wxRenameFile(outfile
, file3
);
1144 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1146 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1147 // CopyFile() copies file attributes and modification time too, so use it
1148 // instead of our code if available
1150 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1151 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1153 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1154 file1
.c_str(), file2
.c_str());
1158 #elif defined(__WXPM__)
1159 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1164 // get permissions of file1
1165 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1167 // the file probably doesn't exist or we haven't the rights to read
1169 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1174 // open file1 for reading
1175 wxFile
fileIn(file1
, wxFile::read
);
1176 if ( !fileIn
.IsOpened() )
1179 // remove file2, if it exists. This is needed for creating
1180 // file2 with the correct permissions in the next step
1181 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1183 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1189 // reset the umask as we want to create the file with exactly the same
1190 // permissions as the original one
1191 mode_t oldUmask
= umask( 0 );
1194 // create file2 with the same permissions than file1 and open it for
1198 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1202 /// restore the old umask
1206 // copy contents of file1 to file2
1211 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1212 if ( fileIn
.Error() )
1219 if ( fileOut
.Write(buf
, count
) < count
)
1223 // we can expect fileIn to be closed successfully, but we should ensure
1224 // that fileOut was closed as some write errors (disk full) might not be
1225 // detected before doing this
1226 if ( !fileIn
.Close() || !fileOut
.Close() )
1229 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1230 // no chmod in VA. Should be some permission API for HPFS386 partitions
1232 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1234 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1238 #endif // OS/2 || Mac
1239 #endif // __WXMSW__ && __WIN32__
1245 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1247 // Normal system call
1248 if ( wxRename (file1
, file2
) == 0 )
1252 if (wxCopyFile(file1
, file2
)) {
1253 wxRemoveFile(file1
);
1260 bool wxRemoveFile(const wxString
& file
)
1262 #if defined(__VISUALC__) \
1263 || defined(__BORLANDC__) \
1264 || defined(__WATCOMC__) \
1265 || defined(__GNUWIN32__)
1266 int res
= wxRemove(file
);
1267 #elif defined(__WXMAC__)
1268 int res
= unlink(wxFNCONV(file
));
1270 int res
= unlink(OS_FILENAME(file
));
1276 bool wxMkdir(const wxString
& dir
, int perm
)
1278 #if defined(__WXMAC__) && !defined(__UNIX__)
1279 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1281 const wxChar
*dirname
= dir
.c_str();
1283 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1284 // for the GNU compiler
1285 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1287 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1289 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1291 #elif defined(__WXPM__)
1292 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1293 #elif defined(__DOS__)
1294 #if defined(__WATCOMC__)
1296 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1297 #elif defined(__DJGPP__)
1298 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1300 #error "Unsupported DOS compiler!"
1302 #else // !MSW, !DOS and !OS/2 VAC++
1304 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1307 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1316 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1319 return FALSE
; //to be changed since rmdir exists in VMS7.x
1320 #elif defined(__WXPM__)
1321 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1325 return FALSE
; // What to do?
1327 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1333 // does the path exists? (may have or not '/' or '\\' at the end)
1334 bool wxPathExists(const wxChar
*pszPathName
)
1336 wxString
strPath(pszPathName
);
1339 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1340 // so remove all trailing backslashes from the path - but don't do this for
1341 // the pathes "d:\" (which are different from "d:") nor for just "\"
1342 while ( wxEndsWithPathSeparator(strPath
) )
1344 size_t len
= strPath
.length();
1345 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1348 strPath
.Truncate(len
- 1);
1350 #endif // __WINDOWS__
1352 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1353 // stat() can't cope with network paths
1354 DWORD ret
= ::GetFileAttributes(strPath
);
1356 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1360 #ifndef __VISAGECPP__
1361 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1363 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1364 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1367 #endif // __WIN32__/!__WIN32__
1370 // Get a temporary filename, opening and closing the file.
1371 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1373 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1374 if ( filename
.empty() )
1378 wxStrcpy(buf
, filename
);
1380 buf
= copystring(filename
);
1385 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1387 buf
= wxFileName::CreateTempFileName(prefix
);
1389 return !buf
.empty();
1392 // Get first file name matching given wild card.
1394 static wxDir
*gs_dir
= NULL
;
1395 static wxString gs_dirPath
;
1397 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1399 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1400 if ( gs_dirPath
.IsEmpty() )
1401 gs_dirPath
= wxT(".");
1402 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1403 gs_dirPath
<< wxFILE_SEP_PATH
;
1407 gs_dir
= new wxDir(gs_dirPath
);
1409 if ( !gs_dir
->IsOpened() )
1411 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1412 return wxEmptyString
;
1418 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1419 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1420 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1424 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1425 if ( result
.IsEmpty() )
1431 return gs_dirPath
+ result
;
1434 wxString
wxFindNextFile()
1436 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1439 gs_dir
->GetNext(&result
);
1441 if ( result
.IsEmpty() )
1447 return gs_dirPath
+ result
;
1451 // Get current working directory.
1452 // If buf is NULL, allocates space using new, else
1454 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1458 buf
= new wxChar
[sz
+ 1];
1463 // for the compilers which have Unicode version of _getcwd(), call it
1464 // directly, for the others call the ANSI version and do the translation
1467 #else // wxUSE_UNICODE
1468 bool needsANSI
= TRUE
;
1470 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1471 // This is not legal code as the compiler
1472 // is allowed destroy the wxCharBuffer.
1473 // wxCharBuffer c_buffer(sz);
1474 // char *cbuf = (char*)(const char*)c_buffer;
1475 char cbuf
[_MAXPATHLEN
];
1479 #if wxUSE_UNICODE_MSLU
1480 if ( wxGetOsVersion() != wxWIN95
)
1482 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1485 ok
= _wgetcwd(buf
, sz
) != NULL
;
1491 #endif // wxUSE_UNICODE
1494 ok
= _getcwd(cbuf
, sz
) != NULL
;
1495 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1500 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1502 pb
.ioRefNum
= LMGetCurApRefNum();
1504 error
= PBGetFCBInfoSync(&pb
);
1505 if ( error
== noErr
)
1507 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1508 cwdSpec
.parID
= pb
.ioFCBParID
;
1509 cwdSpec
.name
[0] = 0 ;
1510 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1511 wxStrcpy( buf
, res
) ;
1518 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1520 rc
= ::DosQueryCurrentDir( 0 // current drive
1525 #else // !Win32/VC++ !Mac !OS2
1526 ok
= getcwd(cbuf
, sz
) != NULL
;
1529 #if wxUSE_UNICODE && !defined(__WXMAC__)
1530 // finally convert the result to Unicode if needed
1531 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1532 #endif // wxUSE_UNICODE
1537 wxLogSysError(_("Failed to get the working directory"));
1539 // VZ: the old code used to return "." on error which didn't make any
1540 // sense at all to me - empty string is a better error indicator
1541 // (NULL might be even better but I'm afraid this could lead to
1542 // problems with the old code assuming the return is never NULL)
1545 else // ok, but we might need to massage the path into the right format
1548 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1549 // with / deliminers. We don't like that.
1550 for (wxChar
*ch
= buf
; *ch
; ch
++)
1552 if (*ch
== wxT('/'))
1557 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1558 // he needs Unix as opposed to Win32 pathnames
1559 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1560 // another example of DOS/Unix mix (Cygwin)
1561 wxString pathUnix
= buf
;
1562 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1563 #endif // __CYGWIN__
1575 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1576 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1577 wxString
str( buffer
);
1583 bool wxSetWorkingDirectory(const wxString
& d
)
1585 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1586 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1587 #elif defined(__WXPM__)
1588 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1589 #elif defined(__WINDOWS__)
1592 return (bool)(SetCurrentDirectory(d
) != 0);
1594 // Must change drive, too.
1595 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1598 wxChar firstChar
= d
[0];
1602 firstChar
= firstChar
- 32;
1604 // To a drive number
1605 unsigned int driveNo
= firstChar
- 64;
1608 unsigned int noDrives
;
1609 _dos_setdrive(driveNo
, &noDrives
);
1612 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1620 // Get the OS directory if appropriate (such as the Windows directory).
1621 // On non-Windows platform, probably just return the empty string.
1622 wxString
wxGetOSDirectory()
1624 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1626 GetWindowsDirectory(buf
, 256);
1627 return wxString(buf
);
1629 return wxEmptyString
;
1633 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1635 size_t len
= wxStrlen(pszFileName
);
1637 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1640 // find a file in a list of directories, returns FALSE if not found
1641 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1643 // we assume that it's not empty
1644 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1645 _T("empty file name in wxFindFileInPath"));
1647 // skip path separator in the beginning of the file name if present
1648 if ( wxIsPathSeparator(*pszFile
) )
1651 // copy the path (strtok will modify it)
1652 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1653 wxStrcpy(szPath
, pszPath
);
1656 wxChar
*pc
, *save_ptr
;
1657 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1659 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1661 // search for the file in this directory
1663 if ( !wxEndsWithPathSeparator(pc
) )
1664 strFile
+= wxFILE_SEP_PATH
;
1667 if ( wxFileExists(strFile
) ) {
1673 // suppress warning about unused variable save_ptr when wxStrtok() is a
1674 // macro which throws away its third argument
1679 return pc
!= NULL
; // if TRUE => we breaked from the loop
1682 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1687 // it can be empty, but it shouldn't be NULL
1688 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1690 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1693 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1696 wxStat( filename
, &buf
);
1698 return buf
.st_mtime
;
1702 //------------------------------------------------------------------------
1703 // wild character routines
1704 //------------------------------------------------------------------------
1706 bool wxIsWild( const wxString
& pattern
)
1708 wxString tmp
= pattern
;
1709 wxChar
*pat
= WXSTRINGCAST(tmp
);
1714 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1725 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1727 * The match procedure is public domain code (from ircII's reg.c)
1730 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1734 /* Match if both are empty. */
1738 const wxChar
*m
= pat
.c_str(),
1749 if (dot_special
&& (*n
== wxT('.')))
1751 /* Never match so that hidden Unix files
1752 * are never found. */
1766 else if (*m
== wxT('?'))
1774 if (*m
== wxT('\\'))
1777 /* Quoting "nothing" is a bad thing */
1784 * If we are out of both strings or we just
1785 * saw a wildcard, then we can say we have a
1796 * We could check for *n == NULL at this point, but
1797 * since it's more common to have a character there,
1798 * check to see if they match first (m and n) and
1799 * then if they don't match, THEN we can check for
1817 * If there are no more characters in the
1818 * string, but we still need to find another
1819 * character (*m != NULL), then it will be
1820 * impossible to match it
1827 if (*np
== wxT(' '))
1853 #pragma warning(default:4706) // assignment within conditional expression