1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "filefn.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
35 #include "wx/filename.h"
38 // there are just too many of those...
40 #pragma warning(disable:4706) // assignment within conditional expression
47 #if !defined(__WATCOMC__)
48 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
53 #if defined(__WXMAC__)
54 #include "wx/mac/private.h" // includes mac headers
60 #include <sys/types.h>
64 #include <sys/types.h>
84 #include "wx/os2/private.h"
86 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
87 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
92 #endif // native Win compiler
105 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
106 // this (3.1 I believe) and how to test for it.
107 // If this works for Borland 4.0 as well, then no worries.
118 // No, Cygwin doesn't appear to have fnmatch.h after all.
119 #if defined(HAVE_FNMATCH_H)
125 #include "wx/msw/mslu.h"
127 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
129 // note that it must be included after <windows.h>
132 #include <sys/cygwin.h>
134 #endif // __GNUWIN32__
135 #endif // __WINDOWS__
137 // TODO: Borland probably has _wgetcwd as well?
142 // ----------------------------------------------------------------------------
144 // ----------------------------------------------------------------------------
147 #define _MAXPATHLEN 1024
152 # include "MoreFilesX.h"
154 # include "MoreFiles.h"
155 # include "MoreFilesExtras.h"
156 # include "FullPath.h"
157 # include "FSpCompat.h"
161 // ----------------------------------------------------------------------------
163 // ----------------------------------------------------------------------------
165 // MT-FIXME: get rid of this horror and all code using it
166 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
168 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
170 // VisualAge C++ V4.0 cannot have any external linkage const decs
171 // in headers included by more than one primary source
173 const off_t wxInvalidOffset
= (off_t
)-1;
176 // ----------------------------------------------------------------------------
178 // ----------------------------------------------------------------------------
180 // we need to translate Mac filenames before passing them to OS functions
181 #define OS_FILENAME(s) (s.fn_str())
183 // ============================================================================
185 // ============================================================================
187 #ifdef wxNEED_WX_UNISTD_H
189 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
191 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
194 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
196 return access( wxConvFile
.cWX2MB( pathname
), mode
);
199 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
201 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
205 // wxNEED_WX_UNISTD_H
207 // ----------------------------------------------------------------------------
209 // ----------------------------------------------------------------------------
211 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
213 void wxPathList::Add (const wxString
& path
)
215 wxStringList::Add (WXSTRINGCAST path
);
218 // Add paths e.g. from the PATH environment variable
219 void wxPathList::AddEnvList (const wxString
& envVariable
)
221 static const wxChar PATH_TOKS
[] =
224 The space has been removed from the tokenizers, otherwise a
225 path such as "C:\Program Files" would be split into 2 paths:
226 "C:\Program" and "Files"
228 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
229 wxT(";"); // Don't seperate with colon in DOS (used for drive)
234 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
237 wxChar
*s
= copystring (val
);
238 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
245 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
253 // suppress warning about unused variable save_ptr when wxStrtok() is a
254 // macro which throws away its third argument
261 // Given a full filename (with path), ensure that that file can
262 // be accessed again USING FILENAME ONLY by adding the path
263 // to the list if not already there.
264 void wxPathList::EnsureFileAccessible (const wxString
& path
)
266 wxString
path_only(wxPathOnly(path
));
267 if ( !path_only
.IsEmpty() )
269 if ( !Member(path_only
) )
274 bool wxPathList::Member (const wxString
& path
)
276 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
278 wxString
path2( node
->GetData() );
280 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
282 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
284 // Case sensitive File System
285 path
.CompareTo (path2
) == 0
293 wxString
wxPathList::FindValidPath (const wxString
& file
)
295 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
296 return wxString(wxFileFunctionsBuffer
);
298 wxChar buf
[_MAXPATHLEN
];
299 wxStrcpy(buf
, wxFileFunctionsBuffer
);
301 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
302 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
304 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
306 wxChar
*path
= node
->GetData();
307 wxStrcpy (wxFileFunctionsBuffer
, path
);
308 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
309 if (ch
!= wxT('\\') && ch
!= wxT('/'))
310 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
311 wxStrcat (wxFileFunctionsBuffer
, filename
);
313 wxUnix2DosFilename (wxFileFunctionsBuffer
);
315 if (wxFileExists (wxFileFunctionsBuffer
))
317 return wxString(wxFileFunctionsBuffer
); // Found!
321 return wxEmptyString
; // Not found
324 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
326 wxString f
= FindValidPath(file
);
327 if ( wxIsAbsolutePath(f
) )
331 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
333 if ( !wxEndsWithPathSeparator(buf
) )
335 buf
+= wxFILE_SEP_PATH
;
343 wxFileExists (const wxString
& filename
)
345 // we must use GetFileAttributes() instead of the ANSI C functions because
346 // it can cope with network (UNC) paths unlike them
347 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
348 DWORD ret
= ::GetFileAttributes(filename
);
350 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
353 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
354 #endif // __WIN32__/!__WIN32__
358 wxIsAbsolutePath (const wxString
& filename
)
360 if (filename
!= wxT(""))
362 #if defined(__WXMAC__) && !defined(__DARWIN__)
363 // Classic or Carbon CodeWarrior like
364 // Carbon with Apple DevTools is Unix like
366 // This seems wrong to me, but there is no fix. since
367 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
368 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
369 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
372 // Unix like or Windows
373 if (filename
[0] == wxT('/'))
377 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
382 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
390 * Strip off any extension (dot something) from end of file,
391 * IF one exists. Inserts zero into buffer.
395 void wxStripExtension(wxChar
*buffer
)
397 int len
= wxStrlen(buffer
);
401 if (buffer
[i
] == wxT('.'))
410 void wxStripExtension(wxString
& buffer
)
412 size_t len
= buffer
.Length();
416 if (buffer
.GetChar(i
) == wxT('.'))
418 buffer
= buffer
.Left(i
);
425 // Destructive removal of /./ and /../ stuff
426 wxChar
*wxRealPath (wxChar
*path
)
429 static const wxChar SEP
= wxT('\\');
430 wxUnix2DosFilename(path
);
432 static const wxChar SEP
= wxT('/');
434 if (path
[0] && path
[1]) {
435 /* MATTHEW: special case "/./x" */
437 if (path
[2] == SEP
&& path
[1] == wxT('.'))
445 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
448 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
453 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
454 && (q
- 1 <= path
|| q
[-1] != SEP
))
457 if (path
[0] == wxT('\0'))
463 /* Check that path[2] is NULL! */
464 else if (path
[1] == wxT(':') && !path
[2])
473 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
482 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
484 if (filename
== wxT(""))
485 return (wxChar
*) NULL
;
487 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
488 wxChar buf
[_MAXPATHLEN
];
490 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
491 wxChar ch
= buf
[wxStrlen(buf
) - 1];
493 if (ch
!= wxT('\\') && ch
!= wxT('/'))
494 wxStrcat(buf
, wxT("\\"));
497 wxStrcat(buf
, wxT("/"));
499 wxStrcat(buf
, wxFileFunctionsBuffer
);
500 return copystring( wxRealPath(buf
) );
502 return copystring( wxFileFunctionsBuffer
);
508 ~user/ => user's home dir
509 If the environment variable a = "foo" and b = "bar" then:
526 /* input name in name, pathname output to buf. */
528 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
530 register wxChar
*d
, *s
, *nm
;
531 wxChar lnm
[_MAXPATHLEN
];
534 // Some compilers don't like this line.
535 // const wxChar trimchars[] = wxT("\n \t");
538 trimchars
[0] = wxT('\n');
539 trimchars
[1] = wxT(' ');
540 trimchars
[2] = wxT('\t');
544 const wxChar SEP
= wxT('\\');
546 const wxChar SEP
= wxT('/');
549 if (name
== NULL
|| *name
== wxT('\0'))
551 nm
= copystring(name
); // Make a scratch copy
554 /* Skip leading whitespace and cr */
555 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
557 /* And strip off trailing whitespace and cr */
558 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
559 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
567 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
570 /* Expand inline environment variables */
588 while ((*d
++ = *s
) != 0) {
590 if (*s
== wxT('\\')) {
591 if ((*(d
- 1) = *++s
)) {
600 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
602 if (*s
++ == wxT('$'))
605 register wxChar
*start
= d
;
606 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
607 register wxChar
*value
;
608 while ((*d
++ = *s
) != 0)
609 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
614 value
= wxGetenv(braces
? start
+ 1 : start
);
616 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
628 /* Expand ~ and ~user */
630 if (nm
[0] == wxT('~') && !q
)
633 if (nm
[1] == SEP
|| nm
[1] == 0)
635 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
636 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
641 { /* ~user/filename */
642 register wxChar
*nnm
;
643 register wxChar
*home
;
644 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
648 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
649 was_sep
= (*s
== SEP
);
650 nnm
= *s
? s
+ 1 : s
;
652 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
653 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
654 if (was_sep
) /* replace only if it was there: */
665 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
667 while (wxT('\0') != (*d
++ = *s
++))
670 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
674 while ((*d
++ = *s
++) != 0)
678 delete[] nm_tmp
; // clean up alloc
679 /* Now clean up the buffer */
680 return wxRealPath(buf
);
683 /* Contract Paths to be build upon an environment variable
686 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
688 The call wxExpandPath can convert these back!
691 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
693 static wxChar dest
[_MAXPATHLEN
];
695 if (filename
== wxT(""))
696 return (wxChar
*) NULL
;
698 wxStrcpy (dest
, WXSTRINGCAST filename
);
700 wxUnix2DosFilename(dest
);
703 // Handle environment
704 const wxChar
*val
= (const wxChar
*) NULL
;
705 wxChar
*tcp
= (wxChar
*) NULL
;
706 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
707 (tcp
= wxStrstr (dest
, val
)) != NULL
)
709 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
712 wxStrcpy (tcp
, WXSTRINGCAST envname
);
713 wxStrcat (tcp
, wxT("}"));
714 wxStrcat (tcp
, wxFileFunctionsBuffer
);
717 // Handle User's home (ignore root homes!)
719 if ((val
= wxGetUserHome (user
)) != NULL
&&
720 (len
= wxStrlen(val
)) > 2 &&
721 wxStrncmp(dest
, val
, len
) == 0)
723 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
725 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
726 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
727 wxStrcpy (dest
, wxFileFunctionsBuffer
);
733 // Return just the filename, not the path (basename)
734 wxChar
*wxFileNameFromPath (wxChar
*path
)
737 wxString n
= wxFileNameFromPath(p
);
739 return path
+ p
.length() - n
.length();
742 wxString
wxFileNameFromPath (const wxString
& path
)
745 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
747 wxString fullname
= name
;
750 fullname
<< wxFILE_SEP_EXT
<< ext
;
756 // Return just the directory, or NULL if no directory
758 wxPathOnly (wxChar
*path
)
762 static wxChar buf
[_MAXPATHLEN
];
765 wxStrcpy (buf
, path
);
767 int l
= wxStrlen(path
);
770 // Search backward for a backward or forward slash
773 #if defined(__WXMAC__) && !defined(__DARWIN__)
774 // Classic or Carbon CodeWarrior like
775 // Carbon with Apple DevTools is Unix like
776 if (path
[i
] == wxT(':') )
782 // Unix like or Windows
783 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
790 if (path
[i
] == wxT(']'))
799 #if defined(__WXMSW__) || defined(__WXPM__)
800 // Try Drive specifier
801 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
803 // A:junk --> A:. (since A:.\junk Not A:\junk)
810 return (wxChar
*) NULL
;
813 // Return just the directory, or NULL if no directory
814 wxString
wxPathOnly (const wxString
& path
)
818 wxChar buf
[_MAXPATHLEN
];
821 wxStrcpy (buf
, WXSTRINGCAST path
);
823 int l
= path
.Length();
826 // Search backward for a backward or forward slash
829 #if defined(__WXMAC__) && !defined(__DARWIN__)
830 // Classic or Carbon CodeWarrior like
831 // Carbon with Apple DevTools is Unix like
832 if (path
[i
] == wxT(':') )
835 return wxString(buf
);
838 // Unix like or Windows
839 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
842 return wxString(buf
);
846 if (path
[i
] == wxT(']'))
849 return wxString(buf
);
855 #if defined(__WXMSW__) || defined(__WXPM__)
856 // Try Drive specifier
857 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
859 // A:junk --> A:. (since A:.\junk Not A:\junk)
862 return wxString(buf
);
866 return wxString(wxT(""));
869 // Utility for converting delimiters in DOS filenames to UNIX style
870 // and back again - or we get nasty problems with delimiters.
871 // Also, convert to lower case, since case is significant in UNIX.
873 #if defined(__WXMAC__)
874 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
881 Boolean isDirectory
= FALSE
;
882 Str255 theParentPath
= "\p";
883 FSSpec theParentSpec
;
885 char theFileName
[FILENAME_MAX
];
886 char thePath
[FILENAME_MAX
];
890 // GD: Separate file name from path and make a FSRef to the parent
891 // directory. This is necessary since FSRefs cannot reference files
892 // that have not yet been created.
893 // Based on example code from Apple Technical Note TN2022
894 // http://developer.apple.com/technotes/tn/tn2022.html
896 // check whether we are converting a directory
897 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
898 // count length of file name
899 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
901 // prepend path separator since it will later be appended to the path
902 theFileName
[0] = wxFILE_SEP_PATH
;
903 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
904 theFileName
[j
- i
] = spec
->name
[j
];
906 theFileName
[j
- i
] = '\0';
908 for (j
= 1; j
<= i
; j
++) {
909 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
911 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
912 if (theErr
== noErr
) {
913 // convert the FSSpec to an FSRef
914 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
916 if (theErr
== noErr
) {
917 // get the POSIX path associated with the FSRef
918 theStatus
= FSRefMakePath(&theParentRef
,
919 (UInt8
*)thePath
, sizeof(thePath
));
921 if (theStatus
== noErr
) {
922 // append file name to path
923 // includes previously prepended path separator
924 strcat(thePath
, theFileName
);
927 // create path string for return value
928 wxString
result( thePath
) ;
933 // get length of path and allocate handle
934 FSpGetFullPath( spec
, &length
, &myPath
) ;
935 ::SetHandleSize( myPath
, length
+ 1 ) ;
937 (*myPath
)[length
] = 0 ;
938 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
939 (*myPath
)[length
-1] = 0 ;
941 // create path string for return value
942 wxString result
= wxMacMakeStringFromCString( *myPath
) ;
944 // free allocated handle
945 ::HUnlock( myPath
) ;
946 ::DisposeHandle( myPath
) ;
952 // Mac file names are POSIX (Unix style) under Darwin
953 // therefore the conversion functions below are not needed
955 static wxChar sMacFileNameConversion
[ 1000 ] ;
956 static char scMacFileNameConversion
[ 1000 ] ;
959 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
961 OSStatus err
= noErr
;
965 // get the FSRef associated with the POSIX path
966 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
967 // convert the FSRef to an FSSpec
968 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
970 if ( strchr( path
, ':' ) == NULL
)
972 // try whether it is a volume / or a mounted volume
973 strncpy( scMacFileNameConversion
, path
, 1000 ) ;
974 scMacFileNameConversion
[998] = 0 ;
975 strcat( scMacFileNameConversion
, ":" ) ;
976 err
= FSpLocationFromFullPath( strlen(scMacFileNameConversion
) , scMacFileNameConversion
, spec
) ;
980 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
986 WXDLLEXPORT
void wxMacFilename2FSSpec( const wxChar
*path
, FSSpec
*spec
)
988 return wxMacFilename2FSSpec( wxMacStringToCString( wxString( path
) ) , spec
) ;
994 wxString
wxMac2UnixFilename (const wxChar
*str
)
996 wxChar
*s
= sMacFileNameConversion
;
997 wxStrcpy( s
, str
) ;
1000 memmove( s
+1 , s
,wxStrlen( s
) + 1 * sizeof(wxChar
)) ;
1011 *s
= wxTolower(*s
); // Case INDEPENDENT
1015 return wxString(sMacFileNameConversion
) ;
1018 wxString
wxUnix2MacFilename (const wxChar
*str
)
1020 wxChar
*s
= sMacFileNameConversion
;
1021 wxStrcpy( s
, str
) ;
1026 // relative path , since it goes on with slash which is translated to a :
1027 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
)) ;
1029 else if ( *s
== '/' )
1031 // absolute path -> on mac just start with the drive name
1032 memmove( s
, s
+1 ,wxStrlen( s
) * sizeof(wxChar
) ) ;
1036 wxASSERT_MSG( 1 , wxT("unkown path beginning") ) ;
1040 if (*s
== '/' || *s
== '\\')
1042 // convert any back-directory situations
1043 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1046 memmove( s
+1 , s
+3 ,(wxStrlen( s
+3 ) + 1)*sizeof(wxChar
) ) ;
1054 return wxString(sMacFileNameConversion
) ;
1057 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1059 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1062 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1064 wxString var
= wxUnix2MacFilename( path
) ;
1065 wxMacFilename2FSSpec( var
, spec
) ;
1067 #endif // ! __DARWIN__
1072 wxDos2UnixFilename (char *s
)
1081 *s
= wxTolower (*s
); // Case INDEPENDENT
1088 #if defined(__WXMSW__) || defined(__WXPM__)
1089 wxUnix2DosFilename (wxChar
*s
)
1091 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1094 // Yes, I really mean this to happen under DOS only! JACS
1095 #if defined(__WXMSW__) || defined(__WXPM__)
1106 // Concatenate two files to form third
1108 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1111 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1114 FILE *fp1
= (FILE *) NULL
;
1115 FILE *fp2
= (FILE *) NULL
;
1116 FILE *fp3
= (FILE *) NULL
;
1117 // Open the inputs and outputs
1118 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1119 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1120 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1132 while ((ch
= getc (fp1
)) != EOF
)
1133 (void) putc (ch
, fp3
);
1136 while ((ch
= getc (fp2
)) != EOF
)
1137 (void) putc (ch
, fp3
);
1141 bool result
= wxRenameFile(outfile
, file3
);
1147 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1149 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1150 // CopyFile() copies file attributes and modification time too, so use it
1151 // instead of our code if available
1153 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1154 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1156 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1157 file1
.c_str(), file2
.c_str());
1161 #elif defined(__WXPM__)
1162 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1167 // get permissions of file1
1168 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1170 // the file probably doesn't exist or we haven't the rights to read
1172 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1177 // open file1 for reading
1178 wxFile
fileIn(file1
, wxFile::read
);
1179 if ( !fileIn
.IsOpened() )
1182 // remove file2, if it exists. This is needed for creating
1183 // file2 with the correct permissions in the next step
1184 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1186 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1192 // reset the umask as we want to create the file with exactly the same
1193 // permissions as the original one
1194 mode_t oldUmask
= umask( 0 );
1197 // create file2 with the same permissions than file1 and open it for
1201 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1205 /// restore the old umask
1209 // copy contents of file1 to file2
1214 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1215 if ( fileIn
.Error() )
1222 if ( fileOut
.Write(buf
, count
) < count
)
1226 // we can expect fileIn to be closed successfully, but we should ensure
1227 // that fileOut was closed as some write errors (disk full) might not be
1228 // detected before doing this
1229 if ( !fileIn
.Close() || !fileOut
.Close() )
1232 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1233 // no chmod in VA. Should be some permission API for HPFS386 partitions
1235 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1237 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1241 #endif // OS/2 || Mac
1242 #endif // __WXMSW__ && __WIN32__
1248 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1250 // Normal system call
1251 if ( wxRename (file1
, file2
) == 0 )
1255 if (wxCopyFile(file1
, file2
)) {
1256 wxRemoveFile(file1
);
1263 bool wxRemoveFile(const wxString
& file
)
1265 #if defined(__VISUALC__) \
1266 || defined(__BORLANDC__) \
1267 || defined(__WATCOMC__) \
1268 || defined(__GNUWIN32__)
1269 int res
= wxRemove(file
);
1270 #elif defined(__WXMAC__)
1271 int res
= unlink(wxFNCONV(file
));
1273 int res
= unlink(OS_FILENAME(file
));
1279 bool wxMkdir(const wxString
& dir
, int perm
)
1281 #if defined(__WXMAC__) && !defined(__UNIX__)
1282 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1284 const wxChar
*dirname
= dir
.c_str();
1286 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1287 // for the GNU compiler
1288 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1290 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1292 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1294 #elif defined(__WXPM__)
1295 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1296 #elif defined(__DOS__)
1297 #if defined(__WATCOMC__)
1299 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1300 #elif defined(__DJGPP__)
1301 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1303 #error "Unsupported DOS compiler!"
1305 #else // !MSW, !DOS and !OS/2 VAC++
1307 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1310 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1319 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1322 return FALSE
; //to be changed since rmdir exists in VMS7.x
1323 #elif defined(__WXPM__)
1324 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1328 return FALSE
; // What to do?
1330 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1336 // does the path exists? (may have or not '/' or '\\' at the end)
1337 bool wxPathExists(const wxChar
*pszPathName
)
1339 wxString
strPath(pszPathName
);
1342 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1343 // so remove all trailing backslashes from the path - but don't do this for
1344 // the pathes "d:\" (which are different from "d:") nor for just "\"
1345 while ( wxEndsWithPathSeparator(strPath
) )
1347 size_t len
= strPath
.length();
1348 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1351 strPath
.Truncate(len
- 1);
1353 #endif // __WINDOWS__
1355 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1356 // stat() can't cope with network paths
1357 DWORD ret
= ::GetFileAttributes(strPath
);
1359 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1363 #ifndef __VISAGECPP__
1364 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1366 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1367 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1370 #endif // __WIN32__/!__WIN32__
1373 // Get a temporary filename, opening and closing the file.
1374 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1376 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1377 if ( filename
.empty() )
1381 wxStrcpy(buf
, filename
);
1383 buf
= copystring(filename
);
1388 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1390 buf
= wxFileName::CreateTempFileName(prefix
);
1392 return !buf
.empty();
1395 // Get first file name matching given wild card.
1397 static wxDir
*gs_dir
= NULL
;
1398 static wxString gs_dirPath
;
1400 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1402 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1403 if ( gs_dirPath
.IsEmpty() )
1404 gs_dirPath
= wxT(".");
1405 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1406 gs_dirPath
<< wxFILE_SEP_PATH
;
1410 gs_dir
= new wxDir(gs_dirPath
);
1412 if ( !gs_dir
->IsOpened() )
1414 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1415 return wxEmptyString
;
1421 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1422 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1423 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1427 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1428 if ( result
.IsEmpty() )
1434 return gs_dirPath
+ result
;
1437 wxString
wxFindNextFile()
1439 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1442 gs_dir
->GetNext(&result
);
1444 if ( result
.IsEmpty() )
1450 return gs_dirPath
+ result
;
1454 // Get current working directory.
1455 // If buf is NULL, allocates space using new, else
1457 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1461 buf
= new wxChar
[sz
+ 1];
1466 // for the compilers which have Unicode version of _getcwd(), call it
1467 // directly, for the others call the ANSI version and do the translation
1470 #else // wxUSE_UNICODE
1471 bool needsANSI
= TRUE
;
1473 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1474 // This is not legal code as the compiler
1475 // is allowed destroy the wxCharBuffer.
1476 // wxCharBuffer c_buffer(sz);
1477 // char *cbuf = (char*)(const char*)c_buffer;
1478 char cbuf
[_MAXPATHLEN
];
1482 #if wxUSE_UNICODE_MSLU
1483 if ( wxGetOsVersion() != wxWIN95
)
1485 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1488 ok
= _wgetcwd(buf
, sz
) != NULL
;
1494 #endif // wxUSE_UNICODE
1497 ok
= _getcwd(cbuf
, sz
) != NULL
;
1498 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1503 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1505 pb
.ioRefNum
= LMGetCurApRefNum();
1507 error
= PBGetFCBInfoSync(&pb
);
1508 if ( error
== noErr
)
1510 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1511 cwdSpec
.parID
= pb
.ioFCBParID
;
1512 cwdSpec
.name
[0] = 0 ;
1513 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1514 wxStrcpy( buf
, res
) ;
1521 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1523 rc
= ::DosQueryCurrentDir( 0 // current drive
1528 #else // !Win32/VC++ !Mac !OS2
1529 ok
= getcwd(cbuf
, sz
) != NULL
;
1532 #if wxUSE_UNICODE && !defined(__WXMAC__)
1533 // finally convert the result to Unicode if needed
1534 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1535 #endif // wxUSE_UNICODE
1540 wxLogSysError(_("Failed to get the working directory"));
1542 // VZ: the old code used to return "." on error which didn't make any
1543 // sense at all to me - empty string is a better error indicator
1544 // (NULL might be even better but I'm afraid this could lead to
1545 // problems with the old code assuming the return is never NULL)
1548 else // ok, but we might need to massage the path into the right format
1551 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1552 // with / deliminers. We don't like that.
1553 for (wxChar
*ch
= buf
; *ch
; ch
++)
1555 if (*ch
== wxT('/'))
1560 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1561 // he needs Unix as opposed to Win32 pathnames
1562 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1563 // another example of DOS/Unix mix (Cygwin)
1564 wxString pathUnix
= buf
;
1565 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1566 #endif // __CYGWIN__
1578 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1579 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1580 wxString
str( buffer
);
1586 bool wxSetWorkingDirectory(const wxString
& d
)
1588 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1589 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1590 #elif defined(__WXPM__)
1591 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1592 #elif defined(__WINDOWS__)
1595 return (bool)(SetCurrentDirectory(d
) != 0);
1597 // Must change drive, too.
1598 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1601 wxChar firstChar
= d
[0];
1605 firstChar
= firstChar
- 32;
1607 // To a drive number
1608 unsigned int driveNo
= firstChar
- 64;
1611 unsigned int noDrives
;
1612 _dos_setdrive(driveNo
, &noDrives
);
1615 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1623 // Get the OS directory if appropriate (such as the Windows directory).
1624 // On non-Windows platform, probably just return the empty string.
1625 wxString
wxGetOSDirectory()
1627 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1629 GetWindowsDirectory(buf
, 256);
1630 return wxString(buf
);
1632 return wxEmptyString
;
1636 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1638 size_t len
= wxStrlen(pszFileName
);
1640 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1643 // find a file in a list of directories, returns FALSE if not found
1644 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1646 // we assume that it's not empty
1647 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1648 _T("empty file name in wxFindFileInPath"));
1650 // skip path separator in the beginning of the file name if present
1651 if ( wxIsPathSeparator(*pszFile
) )
1654 // copy the path (strtok will modify it)
1655 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1656 wxStrcpy(szPath
, pszPath
);
1659 wxChar
*pc
, *save_ptr
;
1660 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1662 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1664 // search for the file in this directory
1666 if ( !wxEndsWithPathSeparator(pc
) )
1667 strFile
+= wxFILE_SEP_PATH
;
1670 if ( wxFileExists(strFile
) ) {
1676 // suppress warning about unused variable save_ptr when wxStrtok() is a
1677 // macro which throws away its third argument
1682 return pc
!= NULL
; // if TRUE => we breaked from the loop
1685 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1690 // it can be empty, but it shouldn't be NULL
1691 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1693 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1696 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1699 wxStat( filename
, &buf
);
1701 return buf
.st_mtime
;
1705 //------------------------------------------------------------------------
1706 // wild character routines
1707 //------------------------------------------------------------------------
1709 bool wxIsWild( const wxString
& pattern
)
1711 wxString tmp
= pattern
;
1712 wxChar
*pat
= WXSTRINGCAST(tmp
);
1717 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1728 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1730 * The match procedure is public domain code (from ircII's reg.c)
1733 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1737 /* Match if both are empty. */
1741 const wxChar
*m
= pat
.c_str(),
1752 if (dot_special
&& (*n
== wxT('.')))
1754 /* Never match so that hidden Unix files
1755 * are never found. */
1769 else if (*m
== wxT('?'))
1777 if (*m
== wxT('\\'))
1780 /* Quoting "nothing" is a bad thing */
1787 * If we are out of both strings or we just
1788 * saw a wildcard, then we can say we have a
1799 * We could check for *n == NULL at this point, but
1800 * since it's more common to have a character there,
1801 * check to see if they match first (m and n) and
1802 * then if they don't match, THEN we can check for
1820 * If there are no more characters in the
1821 * string, but we still need to find another
1822 * character (*m != NULL), then it will be
1823 * impossible to match it
1830 if (*np
== wxT(' '))
1856 #pragma warning(default:4706) // assignment within conditional expression