1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows license
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__) && !defined(__WXWINE__)
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
147 # include "MoreFiles.h"
148 # include "MoreFilesExtras.h"
149 # include "FullPath.h"
150 # include "FSpCompat.h"
153 // ----------------------------------------------------------------------------
155 // ----------------------------------------------------------------------------
157 // MT-FIXME: get rid of this horror and all code using it
158 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
160 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
162 // VisualAge C++ V4.0 cannot have any external linkage const decs
163 // in headers included by more than one primary source
165 const off_t wxInvalidOffset
= (off_t
)-1;
168 // ----------------------------------------------------------------------------
170 // ----------------------------------------------------------------------------
172 // we need to translate Mac filenames before passing them to OS functions
173 #define OS_FILENAME(s) (s.fn_str())
175 // ============================================================================
177 // ============================================================================
179 #ifdef wxNEED_WX_UNISTD_H
181 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
183 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
186 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
188 return access( wxConvFile
.cWX2MB( pathname
), mode
);
191 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
193 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
197 // wxNEED_WX_UNISTD_H
199 // ----------------------------------------------------------------------------
201 // ----------------------------------------------------------------------------
203 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
205 void wxPathList::Add (const wxString
& path
)
207 wxStringList::Add (WXSTRINGCAST path
);
210 // Add paths e.g. from the PATH environment variable
211 void wxPathList::AddEnvList (const wxString
& envVariable
)
213 static const wxChar PATH_TOKS
[] =
215 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
220 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
223 wxChar
*s
= copystring (val
);
224 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
228 Add (copystring (token
));
231 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
232 Add (wxString(token
));
236 // suppress warning about unused variable save_ptr when wxStrtok() is a
237 // macro which throws away its third argument
244 // Given a full filename (with path), ensure that that file can
245 // be accessed again USING FILENAME ONLY by adding the path
246 // to the list if not already there.
247 void wxPathList::EnsureFileAccessible (const wxString
& path
)
249 wxString
path_only(wxPathOnly(path
));
250 if ( !path_only
.IsEmpty() )
252 if ( !Member(path_only
) )
257 bool wxPathList::Member (const wxString
& path
)
259 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
261 wxString
path2((wxChar
*) node
->Data ());
263 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
265 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
267 // Case sensitive File System
268 path
.CompareTo (path2
) == 0
276 wxString
wxPathList::FindValidPath (const wxString
& file
)
278 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
279 return wxString(wxFileFunctionsBuffer
);
281 wxChar buf
[_MAXPATHLEN
];
282 wxStrcpy(buf
, wxFileFunctionsBuffer
);
284 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
285 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
287 for (wxNode
* node
= First (); node
; node
= node
->Next ())
289 wxChar
*path
= (wxChar
*) node
->Data ();
290 wxStrcpy (wxFileFunctionsBuffer
, path
);
291 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
292 if (ch
!= wxT('\\') && ch
!= wxT('/'))
293 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
294 wxStrcat (wxFileFunctionsBuffer
, filename
);
296 wxUnix2DosFilename (wxFileFunctionsBuffer
);
298 if (wxFileExists (wxFileFunctionsBuffer
))
300 return wxString(wxFileFunctionsBuffer
); // Found!
304 return wxString(wxT("")); // Not found
307 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
309 wxString f
= FindValidPath(file
);
310 if ( wxIsAbsolutePath(f
) )
314 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
316 if ( !wxEndsWithPathSeparator(buf
) )
318 buf
+= wxFILE_SEP_PATH
;
326 wxFileExists (const wxString
& filename
)
328 // we must use GetFileAttributes() instead of the ANSI C functions because
329 // it can cope with network (UNC) paths unlike them
330 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
331 DWORD ret
= ::GetFileAttributes(filename
);
333 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
336 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
337 #endif // __WIN32__/!__WIN32__
341 wxIsAbsolutePath (const wxString
& filename
)
343 if (filename
!= wxT(""))
345 #if defined(__WXMAC__) && !defined(__DARWIN__)
346 // Classic or Carbon CodeWarrior like
347 // Carbon with Apple DevTools is Unix like
349 // This seems wrong to me, but there is no fix. since
350 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
351 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
352 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
355 // Unix like or Windows
356 if (filename
[0] == wxT('/'))
360 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
365 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
373 * Strip off any extension (dot something) from end of file,
374 * IF one exists. Inserts zero into buffer.
378 void wxStripExtension(wxChar
*buffer
)
380 int len
= wxStrlen(buffer
);
384 if (buffer
[i
] == wxT('.'))
393 void wxStripExtension(wxString
& buffer
)
395 size_t len
= buffer
.Length();
399 if (buffer
.GetChar(i
) == wxT('.'))
401 buffer
= buffer
.Left(i
);
408 // Destructive removal of /./ and /../ stuff
409 wxChar
*wxRealPath (wxChar
*path
)
412 static const wxChar SEP
= wxT('\\');
413 wxUnix2DosFilename(path
);
415 static const wxChar SEP
= wxT('/');
417 if (path
[0] && path
[1]) {
418 /* MATTHEW: special case "/./x" */
420 if (path
[2] == SEP
&& path
[1] == wxT('.'))
428 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
431 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
436 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
437 && (q
- 1 <= path
|| q
[-1] != SEP
))
440 if (path
[0] == wxT('\0'))
446 /* Check that path[2] is NULL! */
447 else if (path
[1] == wxT(':') && !path
[2])
456 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
465 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
467 if (filename
== wxT(""))
468 return (wxChar
*) NULL
;
470 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
471 wxChar buf
[_MAXPATHLEN
];
473 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
474 wxChar ch
= buf
[wxStrlen(buf
) - 1];
476 if (ch
!= wxT('\\') && ch
!= wxT('/'))
477 wxStrcat(buf
, wxT("\\"));
480 wxStrcat(buf
, wxT("/"));
482 wxStrcat(buf
, wxFileFunctionsBuffer
);
483 return copystring( wxRealPath(buf
) );
485 return copystring( wxFileFunctionsBuffer
);
491 ~user/ => user's home dir
492 If the environment variable a = "foo" and b = "bar" then:
509 /* input name in name, pathname output to buf. */
511 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
513 register wxChar
*d
, *s
, *nm
;
514 wxChar lnm
[_MAXPATHLEN
];
517 // Some compilers don't like this line.
518 // const wxChar trimchars[] = wxT("\n \t");
521 trimchars
[0] = wxT('\n');
522 trimchars
[1] = wxT(' ');
523 trimchars
[2] = wxT('\t');
527 const wxChar SEP
= wxT('\\');
529 const wxChar SEP
= wxT('/');
532 if (name
== NULL
|| *name
== wxT('\0'))
534 nm
= copystring(name
); // Make a scratch copy
537 /* Skip leading whitespace and cr */
538 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
540 /* And strip off trailing whitespace and cr */
541 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
542 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
550 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
553 /* Expand inline environment variables */
571 while ((*d
++ = *s
) != 0) {
573 if (*s
== wxT('\\')) {
574 if ((*(d
- 1) = *++s
)) {
583 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
585 if (*s
++ == wxT('$'))
588 register wxChar
*start
= d
;
589 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
590 register wxChar
*value
;
591 while ((*d
++ = *s
) != 0)
592 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
597 value
= wxGetenv(braces
? start
+ 1 : start
);
599 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
611 /* Expand ~ and ~user */
613 if (nm
[0] == wxT('~') && !q
)
616 if (nm
[1] == SEP
|| nm
[1] == 0)
618 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
619 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
624 { /* ~user/filename */
625 register wxChar
*nnm
;
626 register wxChar
*home
;
627 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
631 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
632 was_sep
= (*s
== SEP
);
633 nnm
= *s
? s
+ 1 : s
;
635 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
636 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
637 if (was_sep
) /* replace only if it was there: */
648 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
650 while (wxT('\0') != (*d
++ = *s
++))
653 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
657 while ((*d
++ = *s
++) != 0)
661 delete[] nm_tmp
; // clean up alloc
662 /* Now clean up the buffer */
663 return wxRealPath(buf
);
666 /* Contract Paths to be build upon an environment variable
669 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
671 The call wxExpandPath can convert these back!
674 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
676 static wxChar dest
[_MAXPATHLEN
];
678 if (filename
== wxT(""))
679 return (wxChar
*) NULL
;
681 wxStrcpy (dest
, WXSTRINGCAST filename
);
683 wxUnix2DosFilename(dest
);
686 // Handle environment
687 const wxChar
*val
= (const wxChar
*) NULL
;
688 wxChar
*tcp
= (wxChar
*) NULL
;
689 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
690 (tcp
= wxStrstr (dest
, val
)) != NULL
)
692 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
695 wxStrcpy (tcp
, WXSTRINGCAST envname
);
696 wxStrcat (tcp
, wxT("}"));
697 wxStrcat (tcp
, wxFileFunctionsBuffer
);
700 // Handle User's home (ignore root homes!)
702 if ((val
= wxGetUserHome (user
)) != NULL
&&
703 (len
= wxStrlen(val
)) > 2 &&
704 wxStrncmp(dest
, val
, len
) == 0)
706 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
708 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
709 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
710 wxStrcpy (dest
, wxFileFunctionsBuffer
);
716 // Return just the filename, not the path (basename)
717 wxChar
*wxFileNameFromPath (wxChar
*path
)
720 wxString n
= wxFileNameFromPath(p
);
722 return path
+ p
.length() - n
.length();
725 wxString
wxFileNameFromPath (const wxString
& path
)
728 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
730 wxString fullname
= name
;
733 fullname
<< wxFILE_SEP_EXT
<< ext
;
739 // Return just the directory, or NULL if no directory
741 wxPathOnly (wxChar
*path
)
745 static wxChar buf
[_MAXPATHLEN
];
748 wxStrcpy (buf
, path
);
750 int l
= wxStrlen(path
);
753 // Search backward for a backward or forward slash
756 #if defined(__WXMAC__) && !defined(__DARWIN__)
757 // Classic or Carbon CodeWarrior like
758 // Carbon with Apple DevTools is Unix like
759 if (path
[i
] == wxT(':') )
765 // Unix like or Windows
766 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
773 if (path
[i
] == wxT(']'))
782 #if defined(__WXMSW__) || defined(__WXPM__)
783 // Try Drive specifier
784 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
786 // A:junk --> A:. (since A:.\junk Not A:\junk)
793 return (wxChar
*) NULL
;
796 // Return just the directory, or NULL if no directory
797 wxString
wxPathOnly (const wxString
& path
)
801 wxChar buf
[_MAXPATHLEN
];
804 wxStrcpy (buf
, WXSTRINGCAST path
);
806 int l
= path
.Length();
809 // Search backward for a backward or forward slash
812 #if defined(__WXMAC__) && !defined(__DARWIN__)
813 // Classic or Carbon CodeWarrior like
814 // Carbon with Apple DevTools is Unix like
815 if (path
[i
] == wxT(':') )
818 return wxString(buf
);
821 // Unix like or Windows
822 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
825 return wxString(buf
);
829 if (path
[i
] == wxT(']'))
832 return wxString(buf
);
838 #if defined(__WXMSW__) || defined(__WXPM__)
839 // Try Drive specifier
840 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
842 // A:junk --> A:. (since A:.\junk Not A:\junk)
845 return wxString(buf
);
849 return wxString(wxT(""));
852 // Utility for converting delimiters in DOS filenames to UNIX style
853 // and back again - or we get nasty problems with delimiters.
854 // Also, convert to lower case, since case is significant in UNIX.
856 #if defined(__WXMAC__)
857 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
864 Boolean isDirectory
= false;
865 Str255 theParentPath
= "\p";
866 FSSpec theParentSpec
;
868 char theFileName
[FILENAME_MAX
];
869 char thePath
[FILENAME_MAX
];
873 // GD: Separate file name from path and make a FSRef to the parent
874 // directory. This is necessary since FSRefs cannot reference files
875 // that have not yet been created.
876 // Based on example code from Apple Technical Note TN2022
877 // http://developer.apple.com/technotes/tn/tn2022.html
879 // check whether we are converting a directory
880 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
881 // count length of file name
882 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
884 // prepend path separator since it will later be appended to the path
885 theFileName
[0] = wxFILE_SEP_PATH
;
886 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
887 theFileName
[j
- i
] = spec
->name
[j
];
889 theFileName
[j
- i
] = '\0';
891 for (j
= 1; j
<= i
; j
++) {
892 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
894 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
895 if (theErr
== noErr
) {
896 // convert the FSSpec to an FSRef
897 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
899 if (theErr
== noErr
) {
900 // get the POSIX path associated with the FSRef
901 theStatus
= FSRefMakePath(&theParentRef
,
902 (UInt8
*)thePath
, sizeof(thePath
));
904 if (theStatus
== noErr
) {
905 // append file name to path
906 // includes previously prepended path separator
907 strcat(thePath
, theFileName
);
910 // create path string for return value
911 wxString
result( thePath
) ;
916 // get length of path and allocate handle
917 FSpGetFullPath( spec
, &length
, &myPath
) ;
918 ::SetHandleSize( myPath
, length
+ 1 ) ;
920 (*myPath
)[length
] = 0 ;
921 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
922 (*myPath
)[length
-1] = 0 ;
924 // create path string for return value
925 wxString
result( (char*) *myPath
) ;
927 // free allocated handle
928 ::HUnlock( myPath
) ;
929 ::DisposeHandle( myPath
) ;
935 // Mac file names are POSIX (Unix style) under Darwin
936 // therefore the conversion functions below are not needed
938 static char sMacFileNameConversion
[ 1000 ] ;
941 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
943 OSStatus err
= noErr
;
947 // get the FSRef associated with the POSIX path
948 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
949 // convert the FSRef to an FSSpec
950 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
952 if ( strchr( path
, ':' ) == NULL
)
954 // try whether it is a volume / or a mounted volume
955 strncpy( sMacFileNameConversion
, path
, 1000 ) ;
956 sMacFileNameConversion
[998] = 0 ;
957 strcat( sMacFileNameConversion
, ":" ) ;
958 err
= FSpLocationFromFullPath( strlen(sMacFileNameConversion
) , sMacFileNameConversion
, spec
) ;
962 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
969 wxString
wxMac2UnixFilename (const char *str
)
971 char *s
= sMacFileNameConversion
;
975 memmove( s
+1 , s
,strlen( s
) + 1) ;
986 *s
= wxTolower(*s
); // Case INDEPENDENT
990 return wxString(sMacFileNameConversion
) ;
993 wxString
wxUnix2MacFilename (const char *str
)
995 char *s
= sMacFileNameConversion
;
1001 // relative path , since it goes on with slash which is translated to a :
1002 memmove( s
, s
+1 ,strlen( s
) ) ;
1004 else if ( *s
== '/' )
1006 // absolute path -> on mac just start with the drive name
1007 memmove( s
, s
+1 ,strlen( s
) ) ;
1011 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
1015 if (*s
== '/' || *s
== '\\')
1017 // convert any back-directory situations
1018 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1021 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
1029 return wxString (sMacFileNameConversion
) ;
1032 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1034 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1037 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1039 wxString var
= wxUnix2MacFilename( path
) ;
1040 wxMacFilename2FSSpec( var
, spec
) ;
1042 #endif // ! __DARWIN__
1047 wxDos2UnixFilename (char *s
)
1056 *s
= wxTolower (*s
); // Case INDEPENDENT
1063 #if defined(__WXMSW__) || defined(__WXPM__)
1064 wxUnix2DosFilename (wxChar
*s
)
1066 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1069 // Yes, I really mean this to happen under DOS only! JACS
1070 #if defined(__WXMSW__) || defined(__WXPM__)
1081 // Concatenate two files to form third
1083 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1086 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1089 FILE *fp1
= (FILE *) NULL
;
1090 FILE *fp2
= (FILE *) NULL
;
1091 FILE *fp3
= (FILE *) NULL
;
1092 // Open the inputs and outputs
1093 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1094 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1095 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1107 while ((ch
= getc (fp1
)) != EOF
)
1108 (void) putc (ch
, fp3
);
1111 while ((ch
= getc (fp2
)) != EOF
)
1112 (void) putc (ch
, fp3
);
1116 bool result
= wxRenameFile(outfile
, file3
);
1122 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1124 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1125 // CopyFile() copies file attributes and modification time too, so use it
1126 // instead of our code if available
1128 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1129 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1131 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1132 file1
.c_str(), file2
.c_str());
1136 #elif defined(__WXPM__)
1137 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1142 // get permissions of file1
1143 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1145 // the file probably doesn't exist or we haven't the rights to read
1147 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1152 // open file1 for reading
1153 wxFile
fileIn(file1
, wxFile::read
);
1154 if ( !fileIn
.IsOpened() )
1157 // remove file2, if it exists. This is needed for creating
1158 // file2 with the correct permissions in the next step
1159 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1161 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1167 // reset the umask as we want to create the file with exactly the same
1168 // permissions as the original one
1169 mode_t oldUmask
= umask( 0 );
1172 // create file2 with the same permissions than file1 and open it for
1176 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1180 /// restore the old umask
1184 // copy contents of file1 to file2
1189 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1190 if ( fileIn
.Error() )
1197 if ( fileOut
.Write(buf
, count
) < count
)
1201 // we can expect fileIn to be closed successfully, but we should ensure
1202 // that fileOut was closed as some write errors (disk full) might not be
1203 // detected before doing this
1204 if ( !fileIn
.Close() || !fileOut
.Close() )
1207 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1208 // no chmod in VA. Should be some permission API for HPFS386 partitions
1210 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1212 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1216 #endif // OS/2 || Mac
1217 #endif // __WXMSW__ && __WIN32__
1223 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1225 // Normal system call
1226 if ( wxRename (file1
, file2
) == 0 )
1230 if (wxCopyFile(file1
, file2
)) {
1231 wxRemoveFile(file1
);
1238 bool wxRemoveFile(const wxString
& file
)
1240 #if defined(__VISUALC__) \
1241 || defined(__BORLANDC__) \
1242 || defined(__WATCOMC__) \
1243 || defined(__GNUWIN32__)
1244 int res
= wxRemove(file
);
1246 int res
= unlink(OS_FILENAME(file
));
1252 bool wxMkdir(const wxString
& dir
, int perm
)
1254 #if defined(__WXMAC__) && !defined(__UNIX__)
1255 return (mkdir( dir
, 0 ) == 0);
1257 const wxChar
*dirname
= dir
.c_str();
1259 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1260 // for the GNU compiler
1261 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1262 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1263 #elif defined(__WXPM__)
1264 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1265 #elif defined(__DOS__)
1266 #if defined(__WATCOMC__)
1268 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1269 #elif defined(__DJGPP__)
1270 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1272 #error "Unsupported DOS compiler!"
1274 #else // !MSW, !DOS and !OS/2 VAC++
1276 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1279 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1288 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1291 return FALSE
; //to be changed since rmdir exists in VMS7.x
1292 #elif defined(__WXPM__)
1293 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1297 return FALSE
; // What to do?
1299 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1305 // does the path exists? (may have or not '/' or '\\' at the end)
1306 bool wxPathExists(const wxChar
*pszPathName
)
1308 wxString
strPath(pszPathName
);
1311 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1312 // so remove all trailing backslashes from the path - but don't do this for
1313 // the pathes "d:\" (which are different from "d:") nor for just "\"
1314 while ( wxEndsWithPathSeparator(strPath
) )
1316 size_t len
= strPath
.length();
1317 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1320 strPath
.Truncate(len
- 1);
1322 #endif // __WINDOWS__
1324 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1325 // stat() can't cope with network paths
1326 DWORD ret
= ::GetFileAttributes(strPath
);
1328 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1332 #ifndef __VISAGECPP__
1333 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1335 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1336 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1339 #endif // __WIN32__/!__WIN32__
1342 // Get a temporary filename, opening and closing the file.
1343 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1345 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1346 if ( filename
.empty() )
1350 wxStrcpy(buf
, filename
);
1352 buf
= copystring(filename
);
1357 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1359 buf
= wxFileName::CreateTempFileName(prefix
);
1361 return !buf
.empty();
1364 // Get first file name matching given wild card.
1366 static wxDir
*gs_dir
= NULL
;
1367 static wxString gs_dirPath
;
1369 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1371 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1372 if ( gs_dirPath
.IsEmpty() )
1373 gs_dirPath
= wxT(".");
1374 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1375 gs_dirPath
<< wxFILE_SEP_PATH
;
1379 gs_dir
= new wxDir(gs_dirPath
);
1381 if ( !gs_dir
->IsOpened() )
1383 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1384 return wxEmptyString
;
1390 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1391 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1392 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1396 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1397 if ( result
.IsEmpty() )
1403 return gs_dirPath
+ result
;
1406 wxString
wxFindNextFile()
1408 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1411 gs_dir
->GetNext(&result
);
1413 if ( result
.IsEmpty() )
1419 return gs_dirPath
+ result
;
1423 // Get current working directory.
1424 // If buf is NULL, allocates space using new, else
1426 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1430 buf
= new wxChar
[sz
+ 1];
1435 // for the compilers which have Unicode version of _getcwd(), call it
1436 // directly, for the others call the ANSI version and do the translation
1439 #else // wxUSE_UNICODE
1440 bool needsANSI
= TRUE
;
1442 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1443 // This is not legal code as the compiler
1444 // is allowed destroy the wxCharBuffer.
1445 // wxCharBuffer c_buffer(sz);
1446 // char *cbuf = (char*)(const char*)c_buffer;
1447 char cbuf
[_MAXPATHLEN
];
1451 #if wxUSE_UNICODE_MSLU
1452 if ( wxGetOsVersion() != wxWIN95
)
1454 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1457 ok
= _wgetcwd(buf
, sz
) != NULL
;
1463 #endif // wxUSE_UNICODE
1466 ok
= _getcwd(cbuf
, sz
) != NULL
;
1467 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1472 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1474 pb
.ioRefNum
= LMGetCurApRefNum();
1476 error
= PBGetFCBInfoSync(&pb
);
1477 if ( error
== noErr
)
1479 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1480 cwdSpec
.parID
= pb
.ioFCBParID
;
1481 cwdSpec
.name
[0] = 0 ;
1482 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1484 strcpy( cbuf
, res
) ;
1485 cbuf
[res
.length()]=0 ;
1493 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1495 rc
= ::DosQueryCurrentDir( 0 // current drive
1500 #else // !Win32/VC++ !Mac !OS2
1501 ok
= getcwd(cbuf
, sz
) != NULL
;
1505 // finally convert the result to Unicode if needed
1506 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1507 #endif // wxUSE_UNICODE
1512 wxLogSysError(_("Failed to get the working directory"));
1514 // VZ: the old code used to return "." on error which didn't make any
1515 // sense at all to me - empty string is a better error indicator
1516 // (NULL might be even better but I'm afraid this could lead to
1517 // problems with the old code assuming the return is never NULL)
1520 else // ok, but we might need to massage the path into the right format
1523 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1524 // with / deliminers. We don't like that.
1525 for (wxChar
*ch
= buf
; *ch
; ch
++)
1527 if (*ch
== wxT('/'))
1532 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1533 // he needs Unix as opposed to Win32 pathnames
1534 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1535 // another example of DOS/Unix mix (Cygwin)
1536 wxString pathUnix
= buf
;
1537 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1538 #endif // __CYGWIN__
1550 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1551 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1552 wxString
str( buffer
);
1558 bool wxSetWorkingDirectory(const wxString
& d
)
1560 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1561 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1562 #elif defined(__WXPM__)
1563 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1564 #elif defined(__WINDOWS__)
1567 return (bool)(SetCurrentDirectory(d
) != 0);
1569 // Must change drive, too.
1570 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1573 wxChar firstChar
= d
[0];
1577 firstChar
= firstChar
- 32;
1579 // To a drive number
1580 unsigned int driveNo
= firstChar
- 64;
1583 unsigned int noDrives
;
1584 _dos_setdrive(driveNo
, &noDrives
);
1587 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1595 // Get the OS directory if appropriate (such as the Windows directory).
1596 // On non-Windows platform, probably just return the empty string.
1597 wxString
wxGetOSDirectory()
1599 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1601 GetWindowsDirectory(buf
, 256);
1602 return wxString(buf
);
1604 return wxEmptyString
;
1608 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1610 size_t len
= wxStrlen(pszFileName
);
1612 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1615 // find a file in a list of directories, returns false if not found
1616 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1618 // we assume that it's not empty
1619 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1620 _T("empty file name in wxFindFileInPath"));
1622 // skip path separator in the beginning of the file name if present
1623 if ( wxIsPathSeparator(*pszFile
) )
1626 // copy the path (strtok will modify it)
1627 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1628 wxStrcpy(szPath
, pszPath
);
1631 wxChar
*pc
, *save_ptr
;
1632 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1634 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1636 // search for the file in this directory
1638 if ( !wxEndsWithPathSeparator(pc
) )
1639 strFile
+= wxFILE_SEP_PATH
;
1642 if ( wxFileExists(strFile
) ) {
1648 // suppress warning about unused variable save_ptr when wxStrtok() is a
1649 // macro which throws away its third argument
1654 return pc
!= NULL
; // if true => we breaked from the loop
1657 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1662 // it can be empty, but it shouldn't be NULL
1663 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1665 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1668 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1671 wxStat( filename
, &buf
);
1673 return buf
.st_mtime
;
1677 //------------------------------------------------------------------------
1678 // wild character routines
1679 //------------------------------------------------------------------------
1681 bool wxIsWild( const wxString
& pattern
)
1683 wxString tmp
= pattern
;
1684 wxChar
*pat
= WXSTRINGCAST(tmp
);
1689 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1700 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1702 * The match procedure is public domain code (from ircII's reg.c)
1705 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1709 /* Match if both are empty. */
1713 const wxChar
*m
= pat
.c_str(),
1724 if (dot_special
&& (*n
== wxT('.')))
1726 /* Never match so that hidden Unix files
1727 * are never found. */
1741 else if (*m
== wxT('?'))
1749 if (*m
== wxT('\\'))
1752 /* Quoting "nothing" is a bad thing */
1759 * If we are out of both strings or we just
1760 * saw a wildcard, then we can say we have a
1771 * We could check for *n == NULL at this point, but
1772 * since it's more common to have a character there,
1773 * check to see if they match first (m and n) and
1774 * then if they don't match, THEN we can check for
1792 * If there are no more characters in the
1793 * string, but we still need to find another
1794 * character (*m != NULL), then it will be
1795 * impossible to match it
1802 if (*np
== wxT(' '))
1828 #pragma warning(default:4706) // assignment within conditional expression