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
--);
432 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
433 && (q
- 1 <= path
|| q
[-1] != SEP
))
436 if (path
[0] == wxT('\0'))
442 /* Check that path[2] is NULL! */
443 else if (path
[1] == wxT(':') && !path
[2])
452 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
461 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
463 if (filename
== wxT(""))
464 return (wxChar
*) NULL
;
466 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
467 wxChar buf
[_MAXPATHLEN
];
469 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
470 wxChar ch
= buf
[wxStrlen(buf
) - 1];
472 if (ch
!= wxT('\\') && ch
!= wxT('/'))
473 wxStrcat(buf
, wxT("\\"));
476 wxStrcat(buf
, wxT("/"));
478 wxStrcat(buf
, wxFileFunctionsBuffer
);
479 return copystring( wxRealPath(buf
) );
481 return copystring( wxFileFunctionsBuffer
);
487 ~user/ => user's home dir
488 If the environment variable a = "foo" and b = "bar" then:
505 /* input name in name, pathname output to buf. */
507 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
509 register wxChar
*d
, *s
, *nm
;
510 wxChar lnm
[_MAXPATHLEN
];
513 // Some compilers don't like this line.
514 // const wxChar trimchars[] = wxT("\n \t");
517 trimchars
[0] = wxT('\n');
518 trimchars
[1] = wxT(' ');
519 trimchars
[2] = wxT('\t');
523 const wxChar SEP
= wxT('\\');
525 const wxChar SEP
= wxT('/');
528 if (name
== NULL
|| *name
== wxT('\0'))
530 nm
= copystring(name
); // Make a scratch copy
533 /* Skip leading whitespace and cr */
534 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
536 /* And strip off trailing whitespace and cr */
537 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
538 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
546 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
549 /* Expand inline environment variables */
567 while ((*d
++ = *s
) != 0) {
569 if (*s
== wxT('\\')) {
570 if ((*(d
- 1) = *++s
)) {
579 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
581 if (*s
++ == wxT('$'))
584 register wxChar
*start
= d
;
585 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
586 register wxChar
*value
;
587 while ((*d
++ = *s
) != 0)
588 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
593 value
= wxGetenv(braces
? start
+ 1 : start
);
595 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
603 /* Expand ~ and ~user */
605 if (nm
[0] == wxT('~') && !q
)
608 if (nm
[1] == SEP
|| nm
[1] == 0)
610 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
611 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
616 { /* ~user/filename */
617 register wxChar
*nnm
;
618 register wxChar
*home
;
619 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
620 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
621 was_sep
= (*s
== SEP
);
622 nnm
= *s
? s
+ 1 : s
;
624 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
625 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
626 if (was_sep
) /* replace only if it was there: */
637 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
639 while (wxT('\0') != (*d
++ = *s
++))
642 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
646 while ((*d
++ = *s
++) != 0);
647 delete[] nm_tmp
; // clean up alloc
648 /* Now clean up the buffer */
649 return wxRealPath(buf
);
652 /* Contract Paths to be build upon an environment variable
655 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
657 The call wxExpandPath can convert these back!
660 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
662 static wxChar dest
[_MAXPATHLEN
];
664 if (filename
== wxT(""))
665 return (wxChar
*) NULL
;
667 wxStrcpy (dest
, WXSTRINGCAST filename
);
669 wxUnix2DosFilename(dest
);
672 // Handle environment
673 const wxChar
*val
= (const wxChar
*) NULL
;
674 wxChar
*tcp
= (wxChar
*) NULL
;
675 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
676 (tcp
= wxStrstr (dest
, val
)) != NULL
)
678 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
681 wxStrcpy (tcp
, WXSTRINGCAST envname
);
682 wxStrcat (tcp
, wxT("}"));
683 wxStrcat (tcp
, wxFileFunctionsBuffer
);
686 // Handle User's home (ignore root homes!)
688 if ((val
= wxGetUserHome (user
)) != NULL
&&
689 (len
= wxStrlen(val
)) > 2 &&
690 wxStrncmp(dest
, val
, len
) == 0)
692 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
694 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
695 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
696 wxStrcpy (dest
, wxFileFunctionsBuffer
);
702 // Return just the filename, not the path (basename)
703 wxChar
*wxFileNameFromPath (wxChar
*path
)
706 wxString n
= wxFileNameFromPath(p
);
708 return path
+ p
.length() - n
.length();
711 wxString
wxFileNameFromPath (const wxString
& path
)
714 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
716 wxString fullname
= name
;
719 fullname
<< wxFILE_SEP_EXT
<< ext
;
725 // Return just the directory, or NULL if no directory
727 wxPathOnly (wxChar
*path
)
731 static wxChar buf
[_MAXPATHLEN
];
734 wxStrcpy (buf
, path
);
736 int l
= wxStrlen(path
);
739 // Search backward for a backward or forward slash
742 #if defined(__WXMAC__) && !defined(__DARWIN__)
743 // Classic or Carbon CodeWarrior like
744 // Carbon with Apple DevTools is Unix like
745 if (path
[i
] == wxT(':') )
751 // Unix like or Windows
752 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
759 if (path
[i
] == wxT(']'))
768 #if defined(__WXMSW__) || defined(__WXPM__)
769 // Try Drive specifier
770 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
772 // A:junk --> A:. (since A:.\junk Not A:\junk)
779 return (wxChar
*) NULL
;
782 // Return just the directory, or NULL if no directory
783 wxString
wxPathOnly (const wxString
& path
)
787 wxChar buf
[_MAXPATHLEN
];
790 wxStrcpy (buf
, WXSTRINGCAST path
);
792 int l
= path
.Length();
795 // Search backward for a backward or forward slash
798 #if defined(__WXMAC__) && !defined(__DARWIN__)
799 // Classic or Carbon CodeWarrior like
800 // Carbon with Apple DevTools is Unix like
801 if (path
[i
] == wxT(':') )
804 return wxString(buf
);
807 // Unix like or Windows
808 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
811 return wxString(buf
);
815 if (path
[i
] == wxT(']'))
818 return wxString(buf
);
824 #if defined(__WXMSW__) || defined(__WXPM__)
825 // Try Drive specifier
826 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
828 // A:junk --> A:. (since A:.\junk Not A:\junk)
831 return wxString(buf
);
835 return wxString(wxT(""));
838 // Utility for converting delimiters in DOS filenames to UNIX style
839 // and back again - or we get nasty problems with delimiters.
840 // Also, convert to lower case, since case is significant in UNIX.
842 #if defined(__WXMAC__)
843 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
850 Boolean isDirectory
= false;
851 Str255 theParentPath
= "\p";
852 FSSpec theParentSpec
;
854 char theFileName
[FILENAME_MAX
];
855 char thePath
[FILENAME_MAX
];
859 // GD: Separate file name from path and make a FSRef to the parent
860 // directory. This is necessary since FSRefs cannot reference files
861 // that have not yet been created.
862 // Based on example code from Apple Technical Note TN2022
863 // http://developer.apple.com/technotes/tn/tn2022.html
865 // check whether we are converting a directory
866 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
867 // count length of file name
868 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
870 // prepend path separator since it will later be appended to the path
871 theFileName
[0] = wxFILE_SEP_PATH
;
872 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
873 theFileName
[j
- i
] = spec
->name
[j
];
875 theFileName
[j
- i
] = '\0';
877 for (j
= 1; j
<= i
; j
++) {
878 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
880 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
881 if (theErr
== noErr
) {
882 // convert the FSSpec to an FSRef
883 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
885 if (theErr
== noErr
) {
886 // get the POSIX path associated with the FSRef
887 theStatus
= FSRefMakePath(&theParentRef
,
888 (UInt8
*)thePath
, sizeof(thePath
));
890 if (theStatus
== noErr
) {
891 // append file name to path
892 // includes previously prepended path separator
893 strcat(thePath
, theFileName
);
896 // create path string for return value
897 wxString
result( thePath
) ;
902 // get length of path and allocate handle
903 FSpGetFullPath( spec
, &length
, &myPath
) ;
904 ::SetHandleSize( myPath
, length
+ 1 ) ;
906 (*myPath
)[length
] = 0 ;
907 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
908 (*myPath
)[length
-1] = 0 ;
910 // create path string for return value
911 wxString
result( (char*) *myPath
) ;
913 // free allocated handle
914 ::HUnlock( myPath
) ;
915 ::DisposeHandle( myPath
) ;
921 // Mac file names are POSIX (Unix style) under Darwin
922 // therefore the conversion functions below are not needed
924 static char sMacFileNameConversion
[ 1000 ] ;
927 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
929 OSStatus err
= noErr
;
933 // get the FSRef associated with the POSIX path
934 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
935 // convert the FSRef to an FSSpec
936 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
938 if ( strchr( path
, ':' ) == NULL
)
940 // try whether it is a volume / or a mounted volume
941 strncpy( sMacFileNameConversion
, path
, 1000 ) ;
942 sMacFileNameConversion
[998] = 0 ;
943 strcat( sMacFileNameConversion
, ":" ) ;
944 err
= FSpLocationFromFullPath( strlen(sMacFileNameConversion
) , sMacFileNameConversion
, spec
) ;
948 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
955 wxString
wxMac2UnixFilename (const char *str
)
957 char *s
= sMacFileNameConversion
;
961 memmove( s
+1 , s
,strlen( s
) + 1) ;
972 *s
= wxTolower(*s
); // Case INDEPENDENT
976 return wxString(sMacFileNameConversion
) ;
979 wxString
wxUnix2MacFilename (const char *str
)
981 char *s
= sMacFileNameConversion
;
987 // relative path , since it goes on with slash which is translated to a :
988 memmove( s
, s
+1 ,strlen( s
) ) ;
990 else if ( *s
== '/' )
992 // absolute path -> on mac just start with the drive name
993 memmove( s
, s
+1 ,strlen( s
) ) ;
997 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
1001 if (*s
== '/' || *s
== '\\')
1003 // convert any back-directory situations
1004 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1007 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
1015 return wxString (sMacFileNameConversion
) ;
1018 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1020 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1023 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1025 wxString var
= wxUnix2MacFilename( path
) ;
1026 wxMacFilename2FSSpec( var
, spec
) ;
1028 #endif // ! __DARWIN__
1033 wxDos2UnixFilename (char *s
)
1042 *s
= wxTolower (*s
); // Case INDEPENDENT
1049 #if defined(__WXMSW__) || defined(__WXPM__)
1050 wxUnix2DosFilename (wxChar
*s
)
1052 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1055 // Yes, I really mean this to happen under DOS only! JACS
1056 #if defined(__WXMSW__) || defined(__WXPM__)
1067 // Concatenate two files to form third
1069 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1072 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1075 FILE *fp1
= (FILE *) NULL
;
1076 FILE *fp2
= (FILE *) NULL
;
1077 FILE *fp3
= (FILE *) NULL
;
1078 // Open the inputs and outputs
1079 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1080 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1081 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1093 while ((ch
= getc (fp1
)) != EOF
)
1094 (void) putc (ch
, fp3
);
1097 while ((ch
= getc (fp2
)) != EOF
)
1098 (void) putc (ch
, fp3
);
1102 bool result
= wxRenameFile(outfile
, file3
);
1108 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1110 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1111 // CopyFile() copies file attributes and modification time too, so use it
1112 // instead of our code if available
1114 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1115 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1117 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1118 file1
.c_str(), file2
.c_str());
1122 #elif defined(__WXPM__)
1123 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1128 // get permissions of file1
1129 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1131 // the file probably doesn't exist or we haven't the rights to read
1133 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1138 // open file1 for reading
1139 wxFile
fileIn(file1
, wxFile::read
);
1140 if ( !fileIn
.IsOpened() )
1143 // remove file2, if it exists. This is needed for creating
1144 // file2 with the correct permissions in the next step
1145 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1147 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1153 // reset the umask as we want to create the file with exactly the same
1154 // permissions as the original one
1155 mode_t oldUmask
= umask( 0 );
1158 // create file2 with the same permissions than file1 and open it for
1162 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1166 /// restore the old umask
1170 // copy contents of file1 to file2
1175 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1176 if ( fileIn
.Error() )
1183 if ( fileOut
.Write(buf
, count
) < count
)
1187 // we can expect fileIn to be closed successfully, but we should ensure
1188 // that fileOut was closed as some write errors (disk full) might not be
1189 // detected before doing this
1190 if ( !fileIn
.Close() || !fileOut
.Close() )
1193 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1194 // no chmod in VA. Should be some permission API for HPFS386 partitions
1196 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1198 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1202 #endif // OS/2 || Mac
1203 #endif // __WXMSW__ && __WIN32__
1209 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1211 // Normal system call
1212 if ( wxRename (file1
, file2
) == 0 )
1216 if (wxCopyFile(file1
, file2
)) {
1217 wxRemoveFile(file1
);
1224 bool wxRemoveFile(const wxString
& file
)
1226 #if defined(__VISUALC__) \
1227 || defined(__BORLANDC__) \
1228 || defined(__WATCOMC__) \
1229 || defined(__GNUWIN32__)
1230 int res
= wxRemove(file
);
1232 int res
= unlink(OS_FILENAME(file
));
1238 bool wxMkdir(const wxString
& dir
, int perm
)
1240 #if defined(__WXMAC__) && !defined(__UNIX__)
1241 return (mkdir( dir
, 0 ) == 0);
1243 const wxChar
*dirname
= dir
.c_str();
1245 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1246 // for the GNU compiler
1247 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1248 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1249 #elif defined(__WXPM__)
1250 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1251 #elif defined(__DOS__)
1252 #if defined(__WATCOMC__)
1254 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1255 #elif defined(__DJGPP__)
1256 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1258 #error "Unsupported DOS compiler!"
1260 #else // !MSW, !DOS and !OS/2 VAC++
1262 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1265 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1274 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1277 return FALSE
; //to be changed since rmdir exists in VMS7.x
1278 #elif defined(__WXPM__)
1279 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1283 return FALSE
; // What to do?
1285 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1291 // does the path exists? (may have or not '/' or '\\' at the end)
1292 bool wxPathExists(const wxChar
*pszPathName
)
1294 wxString
strPath(pszPathName
);
1297 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1298 // so remove all trailing backslashes from the path - but don't do this for
1299 // the pathes "d:\" (which are different from "d:") nor for just "\"
1300 while ( wxEndsWithPathSeparator(strPath
) )
1302 size_t len
= strPath
.length();
1303 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1306 strPath
.Truncate(len
- 1);
1308 #endif // __WINDOWS__
1310 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1311 // stat() can't cope with network paths
1312 DWORD ret
= ::GetFileAttributes(strPath
);
1314 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1318 #ifndef __VISAGECPP__
1319 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1321 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1322 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1325 #endif // __WIN32__/!__WIN32__
1328 // Get a temporary filename, opening and closing the file.
1329 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1331 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1332 if ( filename
.empty() )
1336 wxStrcpy(buf
, filename
);
1338 buf
= copystring(filename
);
1343 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1345 buf
= wxFileName::CreateTempFileName(prefix
);
1347 return !buf
.empty();
1350 // Get first file name matching given wild card.
1352 static wxDir
*gs_dir
= NULL
;
1353 static wxString gs_dirPath
;
1355 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1357 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1358 if ( gs_dirPath
.IsEmpty() )
1359 gs_dirPath
= wxT(".");
1360 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1361 gs_dirPath
<< wxFILE_SEP_PATH
;
1365 gs_dir
= new wxDir(gs_dirPath
);
1367 if ( !gs_dir
->IsOpened() )
1369 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1370 return wxEmptyString
;
1376 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1377 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1378 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1382 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1383 if ( result
.IsEmpty() )
1389 return gs_dirPath
+ result
;
1392 wxString
wxFindNextFile()
1394 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1397 gs_dir
->GetNext(&result
);
1399 if ( result
.IsEmpty() )
1405 return gs_dirPath
+ result
;
1409 // Get current working directory.
1410 // If buf is NULL, allocates space using new, else
1412 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1416 buf
= new wxChar
[sz
+ 1];
1421 // for the compilers which have Unicode version of _getcwd(), call it
1422 // directly, for the others call the ANSI version and do the translation
1425 #else // wxUSE_UNICODE
1426 bool needsANSI
= TRUE
;
1428 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1429 // This is not legal code as the compiler
1430 // is allowed destroy the wxCharBuffer.
1431 // wxCharBuffer c_buffer(sz);
1432 // char *cbuf = (char*)(const char*)c_buffer;
1433 char cbuf
[_MAXPATHLEN
];
1437 #if wxUSE_UNICODE_MSLU
1438 if ( wxGetOsVersion() != wxWIN95
)
1440 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1443 ok
= _wgetcwd(buf
, sz
) != NULL
;
1449 #endif // wxUSE_UNICODE
1452 ok
= _getcwd(cbuf
, sz
) != NULL
;
1453 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1458 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1460 pb
.ioRefNum
= LMGetCurApRefNum();
1462 error
= PBGetFCBInfoSync(&pb
);
1463 if ( error
== noErr
)
1465 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1466 cwdSpec
.parID
= pb
.ioFCBParID
;
1467 cwdSpec
.name
[0] = 0 ;
1468 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1470 strcpy( cbuf
, res
) ;
1471 cbuf
[res
.length()]=0 ;
1479 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1481 rc
= ::DosQueryCurrentDir( 0 // current drive
1486 #else // !Win32/VC++ !Mac !OS2
1487 ok
= getcwd(cbuf
, sz
) != NULL
;
1491 // finally convert the result to Unicode if needed
1492 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1493 #endif // wxUSE_UNICODE
1498 wxLogSysError(_("Failed to get the working directory"));
1500 // VZ: the old code used to return "." on error which didn't make any
1501 // sense at all to me - empty string is a better error indicator
1502 // (NULL might be even better but I'm afraid this could lead to
1503 // problems with the old code assuming the return is never NULL)
1506 else // ok, but we might need to massage the path into the right format
1509 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1510 // with / deliminers. We don't like that.
1511 for (wxChar
*ch
= buf
; *ch
; ch
++)
1513 if (*ch
== wxT('/'))
1518 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1519 // he needs Unix as opposed to Win32 pathnames
1520 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1521 // another example of DOS/Unix mix (Cygwin)
1522 wxString pathUnix
= buf
;
1523 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1524 #endif // __CYGWIN__
1536 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1537 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1538 wxString
str( buffer
);
1544 bool wxSetWorkingDirectory(const wxString
& d
)
1546 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1547 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1548 #elif defined(__WXPM__)
1549 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1550 #elif defined(__WINDOWS__)
1553 return (bool)(SetCurrentDirectory(d
) != 0);
1555 // Must change drive, too.
1556 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1559 wxChar firstChar
= d
[0];
1563 firstChar
= firstChar
- 32;
1565 // To a drive number
1566 unsigned int driveNo
= firstChar
- 64;
1569 unsigned int noDrives
;
1570 _dos_setdrive(driveNo
, &noDrives
);
1573 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1581 // Get the OS directory if appropriate (such as the Windows directory).
1582 // On non-Windows platform, probably just return the empty string.
1583 wxString
wxGetOSDirectory()
1585 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1587 GetWindowsDirectory(buf
, 256);
1588 return wxString(buf
);
1590 return wxEmptyString
;
1594 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1596 size_t len
= wxStrlen(pszFileName
);
1598 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1601 // find a file in a list of directories, returns false if not found
1602 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1604 // we assume that it's not empty
1605 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1606 _T("empty file name in wxFindFileInPath"));
1608 // skip path separator in the beginning of the file name if present
1609 if ( wxIsPathSeparator(*pszFile
) )
1612 // copy the path (strtok will modify it)
1613 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1614 wxStrcpy(szPath
, pszPath
);
1617 wxChar
*pc
, *save_ptr
;
1618 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1620 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1622 // search for the file in this directory
1624 if ( !wxEndsWithPathSeparator(pc
) )
1625 strFile
+= wxFILE_SEP_PATH
;
1628 if ( wxFileExists(strFile
) ) {
1634 // suppress warning about unused variable save_ptr when wxStrtok() is a
1635 // macro which throws away its third argument
1640 return pc
!= NULL
; // if true => we breaked from the loop
1643 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1648 // it can be empty, but it shouldn't be NULL
1649 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1651 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1654 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1657 wxStat( filename
, &buf
);
1659 return buf
.st_mtime
;
1663 //------------------------------------------------------------------------
1664 // wild character routines
1665 //------------------------------------------------------------------------
1667 bool wxIsWild( const wxString
& pattern
)
1669 wxString tmp
= pattern
;
1670 wxChar
*pat
= WXSTRINGCAST(tmp
);
1675 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1686 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1688 * The match procedure is public domain code (from ircII's reg.c)
1691 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1695 /* Match if both are empty. */
1699 const wxChar
*m
= pat
.c_str(),
1710 if (dot_special
&& (*n
== wxT('.')))
1712 /* Never match so that hidden Unix files
1713 * are never found. */
1727 else if (*m
== wxT('?'))
1735 if (*m
== wxT('\\'))
1738 /* Quoting "nothing" is a bad thing */
1745 * If we are out of both strings or we just
1746 * saw a wildcard, then we can say we have a
1757 * We could check for *n == NULL at this point, but
1758 * since it's more common to have a character there,
1759 * check to see if they match first (m and n) and
1760 * then if they don't match, THEN we can check for
1778 * If there are no more characters in the
1779 * string, but we still need to find another
1780 * character (*m != NULL), then it will be
1781 * impossible to match it
1788 if (*np
== wxT(' '))
1814 #pragma warning(default:4706) // assignment within conditional expression