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>
76 #include "wx/os2/private.h"
78 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
79 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
84 #endif // native Win compiler
97 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
98 // this (3.1 I believe) and how to test for it.
99 // If this works for Borland 4.0 as well, then no worries.
110 // No, Cygwin doesn't appear to have fnmatch.h after all.
111 #if defined(HAVE_FNMATCH_H)
117 #include "wx/msw/mslu.h"
119 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
121 // note that it must be included after <windows.h>
124 #include <sys/cygwin.h>
128 #include <sys/unistd.h>
130 #endif // __GNUWIN32__
131 #endif // __WINDOWS__
133 // TODO: Borland probably has _wgetcwd as well?
138 // ----------------------------------------------------------------------------
140 // ----------------------------------------------------------------------------
143 #define _MAXPATHLEN 1024
148 # include "MoreFilesX.h"
150 # include "MoreFiles.h"
151 # include "MoreFilesExtras.h"
152 # include "FullPath.h"
153 # include "FSpCompat.h"
157 // ----------------------------------------------------------------------------
159 // ----------------------------------------------------------------------------
161 // MT-FIXME: get rid of this horror and all code using it
162 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
164 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
166 // VisualAge C++ V4.0 cannot have any external linkage const decs
167 // in headers included by more than one primary source
169 const off_t wxInvalidOffset
= (off_t
)-1;
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
176 // we need to translate Mac filenames before passing them to OS functions
177 #define OS_FILENAME(s) (s.fn_str())
179 // ============================================================================
181 // ============================================================================
183 #ifdef wxNEED_WX_UNISTD_H
185 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
187 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
190 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
192 return access( wxConvFile
.cWX2MB( pathname
), mode
);
195 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
197 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
201 // wxNEED_WX_UNISTD_H
203 // ----------------------------------------------------------------------------
205 // ----------------------------------------------------------------------------
207 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
209 void wxPathList::Add (const wxString
& path
)
211 wxStringList::Add (WXSTRINGCAST path
);
214 // Add paths e.g. from the PATH environment variable
215 void wxPathList::AddEnvList (const wxString
& envVariable
)
217 static const wxChar PATH_TOKS
[] =
220 The space has been removed from the tokenizers, otherwise a
221 path such as "C:\Program Files" would be split into 2 paths:
222 "C:\Program" and "Files"
224 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
225 wxT(";"); // Don't seperate with colon in DOS (used for drive)
230 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
233 wxChar
*s
= copystring (val
);
234 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
241 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
249 // suppress warning about unused variable save_ptr when wxStrtok() is a
250 // macro which throws away its third argument
257 // Given a full filename (with path), ensure that that file can
258 // be accessed again USING FILENAME ONLY by adding the path
259 // to the list if not already there.
260 void wxPathList::EnsureFileAccessible (const wxString
& path
)
262 wxString
path_only(wxPathOnly(path
));
263 if ( !path_only
.IsEmpty() )
265 if ( !Member(path_only
) )
270 bool wxPathList::Member (const wxString
& path
)
272 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
274 wxString
path2( node
->GetData() );
276 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
278 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
280 // Case sensitive File System
281 path
.CompareTo (path2
) == 0
289 wxString
wxPathList::FindValidPath (const wxString
& file
)
291 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
292 return wxString(wxFileFunctionsBuffer
);
294 wxChar buf
[_MAXPATHLEN
];
295 wxStrcpy(buf
, wxFileFunctionsBuffer
);
297 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
298 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
300 for (wxStringList::Node
*node
= GetFirst(); node
; node
= node
->GetNext())
302 wxChar
*path
= node
->GetData();
303 wxStrcpy (wxFileFunctionsBuffer
, path
);
304 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
305 if (ch
!= wxT('\\') && ch
!= wxT('/'))
306 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
307 wxStrcat (wxFileFunctionsBuffer
, filename
);
309 wxUnix2DosFilename (wxFileFunctionsBuffer
);
311 if (wxFileExists (wxFileFunctionsBuffer
))
313 return wxString(wxFileFunctionsBuffer
); // Found!
317 return wxEmptyString
; // Not found
320 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
322 wxString f
= FindValidPath(file
);
323 if ( wxIsAbsolutePath(f
) )
327 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
329 if ( !wxEndsWithPathSeparator(buf
) )
331 buf
+= wxFILE_SEP_PATH
;
339 wxFileExists (const wxString
& filename
)
341 // we must use GetFileAttributes() instead of the ANSI C functions because
342 // it can cope with network (UNC) paths unlike them
343 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
344 DWORD ret
= ::GetFileAttributes(filename
);
346 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
349 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
350 #endif // __WIN32__/!__WIN32__
354 wxIsAbsolutePath (const wxString
& filename
)
356 if (filename
!= wxT(""))
358 #if defined(__WXMAC__) && !defined(__DARWIN__)
359 // Classic or Carbon CodeWarrior like
360 // Carbon with Apple DevTools is Unix like
362 // This seems wrong to me, but there is no fix. since
363 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
364 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
365 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
368 // Unix like or Windows
369 if (filename
[0] == wxT('/'))
373 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
378 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
386 * Strip off any extension (dot something) from end of file,
387 * IF one exists. Inserts zero into buffer.
391 void wxStripExtension(wxChar
*buffer
)
393 int len
= wxStrlen(buffer
);
397 if (buffer
[i
] == wxT('.'))
406 void wxStripExtension(wxString
& buffer
)
408 size_t len
= buffer
.Length();
412 if (buffer
.GetChar(i
) == wxT('.'))
414 buffer
= buffer
.Left(i
);
421 // Destructive removal of /./ and /../ stuff
422 wxChar
*wxRealPath (wxChar
*path
)
425 static const wxChar SEP
= wxT('\\');
426 wxUnix2DosFilename(path
);
428 static const wxChar SEP
= wxT('/');
430 if (path
[0] && path
[1]) {
431 /* MATTHEW: special case "/./x" */
433 if (path
[2] == SEP
&& path
[1] == wxT('.'))
441 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
444 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
449 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
450 && (q
- 1 <= path
|| q
[-1] != SEP
))
453 if (path
[0] == wxT('\0'))
459 /* Check that path[2] is NULL! */
460 else if (path
[1] == wxT(':') && !path
[2])
469 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
478 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
480 if (filename
== wxT(""))
481 return (wxChar
*) NULL
;
483 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
484 wxChar buf
[_MAXPATHLEN
];
486 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
487 wxChar ch
= buf
[wxStrlen(buf
) - 1];
489 if (ch
!= wxT('\\') && ch
!= wxT('/'))
490 wxStrcat(buf
, wxT("\\"));
493 wxStrcat(buf
, wxT("/"));
495 wxStrcat(buf
, wxFileFunctionsBuffer
);
496 return copystring( wxRealPath(buf
) );
498 return copystring( wxFileFunctionsBuffer
);
504 ~user/ => user's home dir
505 If the environment variable a = "foo" and b = "bar" then:
522 /* input name in name, pathname output to buf. */
524 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
526 register wxChar
*d
, *s
, *nm
;
527 wxChar lnm
[_MAXPATHLEN
];
530 // Some compilers don't like this line.
531 // const wxChar trimchars[] = wxT("\n \t");
534 trimchars
[0] = wxT('\n');
535 trimchars
[1] = wxT(' ');
536 trimchars
[2] = wxT('\t');
540 const wxChar SEP
= wxT('\\');
542 const wxChar SEP
= wxT('/');
545 if (name
== NULL
|| *name
== wxT('\0'))
547 nm
= copystring(name
); // Make a scratch copy
550 /* Skip leading whitespace and cr */
551 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
553 /* And strip off trailing whitespace and cr */
554 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
555 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
563 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
566 /* Expand inline environment variables */
584 while ((*d
++ = *s
) != 0) {
586 if (*s
== wxT('\\')) {
587 if ((*(d
- 1) = *++s
)) {
596 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
598 if (*s
++ == wxT('$'))
601 register wxChar
*start
= d
;
602 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
603 register wxChar
*value
;
604 while ((*d
++ = *s
) != 0)
605 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
610 value
= wxGetenv(braces
? start
+ 1 : start
);
612 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
624 /* Expand ~ and ~user */
626 if (nm
[0] == wxT('~') && !q
)
629 if (nm
[1] == SEP
|| nm
[1] == 0)
631 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
632 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
637 { /* ~user/filename */
638 register wxChar
*nnm
;
639 register wxChar
*home
;
640 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
644 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
645 was_sep
= (*s
== SEP
);
646 nnm
= *s
? s
+ 1 : s
;
648 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
649 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
650 if (was_sep
) /* replace only if it was there: */
661 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
663 while (wxT('\0') != (*d
++ = *s
++))
666 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
670 while ((*d
++ = *s
++) != 0)
674 delete[] nm_tmp
; // clean up alloc
675 /* Now clean up the buffer */
676 return wxRealPath(buf
);
679 /* Contract Paths to be build upon an environment variable
682 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
684 The call wxExpandPath can convert these back!
687 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
689 static wxChar dest
[_MAXPATHLEN
];
691 if (filename
== wxT(""))
692 return (wxChar
*) NULL
;
694 wxStrcpy (dest
, WXSTRINGCAST filename
);
696 wxUnix2DosFilename(dest
);
699 // Handle environment
700 const wxChar
*val
= (const wxChar
*) NULL
;
701 wxChar
*tcp
= (wxChar
*) NULL
;
702 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
703 (tcp
= wxStrstr (dest
, val
)) != NULL
)
705 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
708 wxStrcpy (tcp
, WXSTRINGCAST envname
);
709 wxStrcat (tcp
, wxT("}"));
710 wxStrcat (tcp
, wxFileFunctionsBuffer
);
713 // Handle User's home (ignore root homes!)
715 if ((val
= wxGetUserHome (user
)) != NULL
&&
716 (len
= wxStrlen(val
)) > 2 &&
717 wxStrncmp(dest
, val
, len
) == 0)
719 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
721 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
722 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
723 wxStrcpy (dest
, wxFileFunctionsBuffer
);
729 // Return just the filename, not the path (basename)
730 wxChar
*wxFileNameFromPath (wxChar
*path
)
733 wxString n
= wxFileNameFromPath(p
);
735 return path
+ p
.length() - n
.length();
738 wxString
wxFileNameFromPath (const wxString
& path
)
741 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
743 wxString fullname
= name
;
746 fullname
<< wxFILE_SEP_EXT
<< ext
;
752 // Return just the directory, or NULL if no directory
754 wxPathOnly (wxChar
*path
)
758 static wxChar buf
[_MAXPATHLEN
];
761 wxStrcpy (buf
, path
);
763 int l
= wxStrlen(path
);
766 // Search backward for a backward or forward slash
769 #if defined(__WXMAC__) && !defined(__DARWIN__)
770 // Classic or Carbon CodeWarrior like
771 // Carbon with Apple DevTools is Unix like
772 if (path
[i
] == wxT(':') )
778 // Unix like or Windows
779 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
786 if (path
[i
] == wxT(']'))
795 #if defined(__WXMSW__) || defined(__WXPM__)
796 // Try Drive specifier
797 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
799 // A:junk --> A:. (since A:.\junk Not A:\junk)
806 return (wxChar
*) NULL
;
809 // Return just the directory, or NULL if no directory
810 wxString
wxPathOnly (const wxString
& path
)
814 wxChar buf
[_MAXPATHLEN
];
817 wxStrcpy (buf
, WXSTRINGCAST path
);
819 int l
= path
.Length();
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(':') )
831 return wxString(buf
);
834 // Unix like or Windows
835 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
838 return wxString(buf
);
842 if (path
[i
] == wxT(']'))
845 return wxString(buf
);
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)
858 return wxString(buf
);
862 return wxString(wxT(""));
865 // Utility for converting delimiters in DOS filenames to UNIX style
866 // and back again - or we get nasty problems with delimiters.
867 // Also, convert to lower case, since case is significant in UNIX.
869 #if defined(__WXMAC__)
870 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
877 Boolean isDirectory
= FALSE
;
878 Str255 theParentPath
= "\p";
879 FSSpec theParentSpec
;
881 char theFileName
[FILENAME_MAX
];
882 char thePath
[FILENAME_MAX
];
886 // GD: Separate file name from path and make a FSRef to the parent
887 // directory. This is necessary since FSRefs cannot reference files
888 // that have not yet been created.
889 // Based on example code from Apple Technical Note TN2022
890 // http://developer.apple.com/technotes/tn/tn2022.html
892 // check whether we are converting a directory
893 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
894 // count length of file name
895 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
897 // prepend path separator since it will later be appended to the path
898 theFileName
[0] = wxFILE_SEP_PATH
;
899 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
900 theFileName
[j
- i
] = spec
->name
[j
];
902 theFileName
[j
- i
] = '\0';
904 for (j
= 1; j
<= i
; j
++) {
905 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
907 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
908 if (theErr
== noErr
) {
909 // convert the FSSpec to an FSRef
910 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
912 if (theErr
== noErr
) {
913 // get the POSIX path associated with the FSRef
914 theStatus
= FSRefMakePath(&theParentRef
,
915 (UInt8
*)thePath
, sizeof(thePath
));
917 if (theStatus
== noErr
) {
918 // append file name to path
919 // includes previously prepended path separator
920 strcat(thePath
, theFileName
);
923 // create path string for return value
924 wxString
result( thePath
) ;
929 // get length of path and allocate handle
930 FSpGetFullPath( spec
, &length
, &myPath
) ;
931 ::SetHandleSize( myPath
, length
+ 1 ) ;
933 (*myPath
)[length
] = 0 ;
934 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
935 (*myPath
)[length
-1] = 0 ;
937 // create path string for return value
938 wxString
result( (char*) *myPath
) ;
940 // free allocated handle
941 ::HUnlock( myPath
) ;
942 ::DisposeHandle( myPath
) ;
948 // Mac file names are POSIX (Unix style) under Darwin
949 // therefore the conversion functions below are not needed
951 static char sMacFileNameConversion
[ 1000 ] ;
954 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
956 OSStatus err
= noErr
;
960 // get the FSRef associated with the POSIX path
961 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
962 // convert the FSRef to an FSSpec
963 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
965 if ( strchr( path
, ':' ) == NULL
)
967 // try whether it is a volume / or a mounted volume
968 strncpy( sMacFileNameConversion
, path
, 1000 ) ;
969 sMacFileNameConversion
[998] = 0 ;
970 strcat( sMacFileNameConversion
, ":" ) ;
971 err
= FSpLocationFromFullPath( strlen(sMacFileNameConversion
) , sMacFileNameConversion
, spec
) ;
975 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
982 wxString
wxMac2UnixFilename (const char *str
)
984 char *s
= sMacFileNameConversion
;
988 memmove( s
+1 , s
,strlen( s
) + 1) ;
999 *s
= wxTolower(*s
); // Case INDEPENDENT
1003 return wxString(sMacFileNameConversion
) ;
1006 wxString
wxUnix2MacFilename (const char *str
)
1008 char *s
= sMacFileNameConversion
;
1014 // relative path , since it goes on with slash which is translated to a :
1015 memmove( s
, s
+1 ,strlen( s
) ) ;
1017 else if ( *s
== '/' )
1019 // absolute path -> on mac just start with the drive name
1020 memmove( s
, s
+1 ,strlen( s
) ) ;
1024 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
1028 if (*s
== '/' || *s
== '\\')
1030 // convert any back-directory situations
1031 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1034 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
1042 return wxString (sMacFileNameConversion
) ;
1045 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1047 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1050 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1052 wxString var
= wxUnix2MacFilename( path
) ;
1053 wxMacFilename2FSSpec( var
, spec
) ;
1055 #endif // ! __DARWIN__
1060 wxDos2UnixFilename (char *s
)
1069 *s
= wxTolower (*s
); // Case INDEPENDENT
1076 #if defined(__WXMSW__) || defined(__WXPM__)
1077 wxUnix2DosFilename (wxChar
*s
)
1079 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1082 // Yes, I really mean this to happen under DOS only! JACS
1083 #if defined(__WXMSW__) || defined(__WXPM__)
1094 // Concatenate two files to form third
1096 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1099 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1102 FILE *fp1
= (FILE *) NULL
;
1103 FILE *fp2
= (FILE *) NULL
;
1104 FILE *fp3
= (FILE *) NULL
;
1105 // Open the inputs and outputs
1106 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1107 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1108 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1120 while ((ch
= getc (fp1
)) != EOF
)
1121 (void) putc (ch
, fp3
);
1124 while ((ch
= getc (fp2
)) != EOF
)
1125 (void) putc (ch
, fp3
);
1129 bool result
= wxRenameFile(outfile
, file3
);
1135 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1137 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1138 // CopyFile() copies file attributes and modification time too, so use it
1139 // instead of our code if available
1141 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1142 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1144 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1145 file1
.c_str(), file2
.c_str());
1149 #elif defined(__WXPM__)
1150 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1155 // get permissions of file1
1156 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1158 // the file probably doesn't exist or we haven't the rights to read
1160 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1165 // open file1 for reading
1166 wxFile
fileIn(file1
, wxFile::read
);
1167 if ( !fileIn
.IsOpened() )
1170 // remove file2, if it exists. This is needed for creating
1171 // file2 with the correct permissions in the next step
1172 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1174 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1180 // reset the umask as we want to create the file with exactly the same
1181 // permissions as the original one
1182 mode_t oldUmask
= umask( 0 );
1185 // create file2 with the same permissions than file1 and open it for
1189 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1193 /// restore the old umask
1197 // copy contents of file1 to file2
1202 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1203 if ( fileIn
.Error() )
1210 if ( fileOut
.Write(buf
, count
) < count
)
1214 // we can expect fileIn to be closed successfully, but we should ensure
1215 // that fileOut was closed as some write errors (disk full) might not be
1216 // detected before doing this
1217 if ( !fileIn
.Close() || !fileOut
.Close() )
1220 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1221 // no chmod in VA. Should be some permission API for HPFS386 partitions
1223 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1225 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1229 #endif // OS/2 || Mac
1230 #endif // __WXMSW__ && __WIN32__
1236 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1238 // Normal system call
1239 if ( wxRename (file1
, file2
) == 0 )
1243 if (wxCopyFile(file1
, file2
)) {
1244 wxRemoveFile(file1
);
1251 bool wxRemoveFile(const wxString
& file
)
1253 #if defined(__VISUALC__) \
1254 || defined(__BORLANDC__) \
1255 || defined(__WATCOMC__) \
1256 || defined(__GNUWIN32__)
1257 int res
= wxRemove(file
);
1259 int res
= unlink(OS_FILENAME(file
));
1265 bool wxMkdir(const wxString
& dir
, int perm
)
1267 #if defined(__WXMAC__) && !defined(__UNIX__)
1268 return (mkdir( dir
, 0 ) == 0);
1270 const wxChar
*dirname
= dir
.c_str();
1272 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1273 // for the GNU compiler
1274 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1276 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1278 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1280 #elif defined(__WXPM__)
1281 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1282 #elif defined(__DOS__)
1283 #if defined(__WATCOMC__)
1285 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1286 #elif defined(__DJGPP__)
1287 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1289 #error "Unsupported DOS compiler!"
1291 #else // !MSW, !DOS and !OS/2 VAC++
1293 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1296 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1305 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1308 return FALSE
; //to be changed since rmdir exists in VMS7.x
1309 #elif defined(__WXPM__)
1310 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1314 return FALSE
; // What to do?
1316 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1322 // does the path exists? (may have or not '/' or '\\' at the end)
1323 bool wxPathExists(const wxChar
*pszPathName
)
1325 wxString
strPath(pszPathName
);
1328 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1329 // so remove all trailing backslashes from the path - but don't do this for
1330 // the pathes "d:\" (which are different from "d:") nor for just "\"
1331 while ( wxEndsWithPathSeparator(strPath
) )
1333 size_t len
= strPath
.length();
1334 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1337 strPath
.Truncate(len
- 1);
1339 #endif // __WINDOWS__
1341 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1342 // stat() can't cope with network paths
1343 DWORD ret
= ::GetFileAttributes(strPath
);
1345 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1349 #ifndef __VISAGECPP__
1350 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1352 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1353 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1356 #endif // __WIN32__/!__WIN32__
1359 // Get a temporary filename, opening and closing the file.
1360 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1362 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1363 if ( filename
.empty() )
1367 wxStrcpy(buf
, filename
);
1369 buf
= copystring(filename
);
1374 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1376 buf
= wxFileName::CreateTempFileName(prefix
);
1378 return !buf
.empty();
1381 // Get first file name matching given wild card.
1383 static wxDir
*gs_dir
= NULL
;
1384 static wxString gs_dirPath
;
1386 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1388 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1389 if ( gs_dirPath
.IsEmpty() )
1390 gs_dirPath
= wxT(".");
1391 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1392 gs_dirPath
<< wxFILE_SEP_PATH
;
1396 gs_dir
= new wxDir(gs_dirPath
);
1398 if ( !gs_dir
->IsOpened() )
1400 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1401 return wxEmptyString
;
1407 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1408 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1409 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1413 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1414 if ( result
.IsEmpty() )
1420 return gs_dirPath
+ result
;
1423 wxString
wxFindNextFile()
1425 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1428 gs_dir
->GetNext(&result
);
1430 if ( result
.IsEmpty() )
1436 return gs_dirPath
+ result
;
1440 // Get current working directory.
1441 // If buf is NULL, allocates space using new, else
1443 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1447 buf
= new wxChar
[sz
+ 1];
1452 // for the compilers which have Unicode version of _getcwd(), call it
1453 // directly, for the others call the ANSI version and do the translation
1456 #else // wxUSE_UNICODE
1457 bool needsANSI
= TRUE
;
1459 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1460 // This is not legal code as the compiler
1461 // is allowed destroy the wxCharBuffer.
1462 // wxCharBuffer c_buffer(sz);
1463 // char *cbuf = (char*)(const char*)c_buffer;
1464 char cbuf
[_MAXPATHLEN
];
1468 #if wxUSE_UNICODE_MSLU
1469 if ( wxGetOsVersion() != wxWIN95
)
1471 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1474 ok
= _wgetcwd(buf
, sz
) != NULL
;
1480 #endif // wxUSE_UNICODE
1483 ok
= _getcwd(cbuf
, sz
) != NULL
;
1484 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1489 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1491 pb
.ioRefNum
= LMGetCurApRefNum();
1493 error
= PBGetFCBInfoSync(&pb
);
1494 if ( error
== noErr
)
1496 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1497 cwdSpec
.parID
= pb
.ioFCBParID
;
1498 cwdSpec
.name
[0] = 0 ;
1499 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1501 strcpy( cbuf
, res
) ;
1502 cbuf
[res
.length()]=0 ;
1510 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1512 rc
= ::DosQueryCurrentDir( 0 // current drive
1517 #else // !Win32/VC++ !Mac !OS2
1518 ok
= getcwd(cbuf
, sz
) != NULL
;
1522 // finally convert the result to Unicode if needed
1523 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1524 #endif // wxUSE_UNICODE
1529 wxLogSysError(_("Failed to get the working directory"));
1531 // VZ: the old code used to return "." on error which didn't make any
1532 // sense at all to me - empty string is a better error indicator
1533 // (NULL might be even better but I'm afraid this could lead to
1534 // problems with the old code assuming the return is never NULL)
1537 else // ok, but we might need to massage the path into the right format
1540 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1541 // with / deliminers. We don't like that.
1542 for (wxChar
*ch
= buf
; *ch
; ch
++)
1544 if (*ch
== wxT('/'))
1549 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1550 // he needs Unix as opposed to Win32 pathnames
1551 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1552 // another example of DOS/Unix mix (Cygwin)
1553 wxString pathUnix
= buf
;
1554 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1555 #endif // __CYGWIN__
1567 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1568 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1569 wxString
str( buffer
);
1575 bool wxSetWorkingDirectory(const wxString
& d
)
1577 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1578 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1579 #elif defined(__WXPM__)
1580 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1581 #elif defined(__WINDOWS__)
1584 return (bool)(SetCurrentDirectory(d
) != 0);
1586 // Must change drive, too.
1587 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1590 wxChar firstChar
= d
[0];
1594 firstChar
= firstChar
- 32;
1596 // To a drive number
1597 unsigned int driveNo
= firstChar
- 64;
1600 unsigned int noDrives
;
1601 _dos_setdrive(driveNo
, &noDrives
);
1604 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1612 // Get the OS directory if appropriate (such as the Windows directory).
1613 // On non-Windows platform, probably just return the empty string.
1614 wxString
wxGetOSDirectory()
1616 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1618 GetWindowsDirectory(buf
, 256);
1619 return wxString(buf
);
1621 return wxEmptyString
;
1625 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1627 size_t len
= wxStrlen(pszFileName
);
1629 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1632 // find a file in a list of directories, returns FALSE if not found
1633 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1635 // we assume that it's not empty
1636 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1637 _T("empty file name in wxFindFileInPath"));
1639 // skip path separator in the beginning of the file name if present
1640 if ( wxIsPathSeparator(*pszFile
) )
1643 // copy the path (strtok will modify it)
1644 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1645 wxStrcpy(szPath
, pszPath
);
1648 wxChar
*pc
, *save_ptr
;
1649 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1651 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1653 // search for the file in this directory
1655 if ( !wxEndsWithPathSeparator(pc
) )
1656 strFile
+= wxFILE_SEP_PATH
;
1659 if ( wxFileExists(strFile
) ) {
1665 // suppress warning about unused variable save_ptr when wxStrtok() is a
1666 // macro which throws away its third argument
1671 return pc
!= NULL
; // if TRUE => we breaked from the loop
1674 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1679 // it can be empty, but it shouldn't be NULL
1680 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1682 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1685 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1688 wxStat( filename
, &buf
);
1690 return buf
.st_mtime
;
1694 //------------------------------------------------------------------------
1695 // wild character routines
1696 //------------------------------------------------------------------------
1698 bool wxIsWild( const wxString
& pattern
)
1700 wxString tmp
= pattern
;
1701 wxChar
*pat
= WXSTRINGCAST(tmp
);
1706 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1717 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1719 * The match procedure is public domain code (from ircII's reg.c)
1722 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1726 /* Match if both are empty. */
1730 const wxChar
*m
= pat
.c_str(),
1741 if (dot_special
&& (*n
== wxT('.')))
1743 /* Never match so that hidden Unix files
1744 * are never found. */
1758 else if (*m
== wxT('?'))
1766 if (*m
== wxT('\\'))
1769 /* Quoting "nothing" is a bad thing */
1776 * If we are out of both strings or we just
1777 * saw a wildcard, then we can say we have a
1788 * We could check for *n == NULL at this point, but
1789 * since it's more common to have a character there,
1790 * check to see if they match first (m and n) and
1791 * then if they don't match, THEN we can check for
1809 * If there are no more characters in the
1810 * string, but we still need to find another
1811 * character (*m != NULL), then it will be
1812 * impossible to match it
1819 if (*np
== wxT(' '))
1845 #pragma warning(default:4706) // assignment within conditional expression