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.
108 #include "wx/setup.h"
111 // No, Cygwin doesn't appear to have fnmatch.h after all.
112 #if defined(HAVE_FNMATCH_H)
118 #include "wx/msw/mslu.h"
120 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
122 // note that it must be included after <windows.h>
125 #include <sys/cygwin.h>
129 #include <sys/unistd.h>
131 #endif // __GNUWIN32__
132 #endif // __WINDOWS__
134 // TODO: Borland probably has _wgetcwd as well?
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
144 #define _MAXPATHLEN 1024
148 # include "MoreFiles.h"
149 # include "MoreFilesExtras.h"
150 # include "FullPath.h"
151 # include "FSpCompat.h"
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
158 // MT-FIXME: get rid of this horror and all code using it
159 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
161 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
163 // VisualAge C++ V4.0 cannot have any external linkage const decs
164 // in headers included by more than one primary source
166 const off_t wxInvalidOffset
= (off_t
)-1;
169 // ----------------------------------------------------------------------------
171 // ----------------------------------------------------------------------------
173 // we need to translate Mac filenames before passing them to OS functions
174 #define OS_FILENAME(s) (s.fn_str())
176 // ============================================================================
178 // ============================================================================
180 #ifdef wxNEED_WX_UNISTD_H
182 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
184 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
187 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
189 return access( wxConvFile
.cWX2MB( pathname
), mode
);
192 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
194 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
198 // wxNEED_WX_UNISTD_H
200 // ----------------------------------------------------------------------------
202 // ----------------------------------------------------------------------------
204 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
206 void wxPathList::Add (const wxString
& path
)
208 wxStringList::Add (WXSTRINGCAST path
);
211 // Add paths e.g. from the PATH environment variable
212 void wxPathList::AddEnvList (const wxString
& envVariable
)
214 static const wxChar PATH_TOKS
[] =
216 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
221 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
224 wxChar
*s
= copystring (val
);
225 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
229 Add (copystring (token
));
232 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
233 Add (wxString(token
));
237 // suppress warning about unused variable save_ptr when wxStrtok() is a
238 // macro which throws away its third argument
245 // Given a full filename (with path), ensure that that file can
246 // be accessed again USING FILENAME ONLY by adding the path
247 // to the list if not already there.
248 void wxPathList::EnsureFileAccessible (const wxString
& path
)
250 wxString
path_only(wxPathOnly(path
));
251 if ( !path_only
.IsEmpty() )
253 if ( !Member(path_only
) )
258 bool wxPathList::Member (const wxString
& path
)
260 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
262 wxString
path2((wxChar
*) node
->Data ());
264 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
266 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
268 // Case sensitive File System
269 path
.CompareTo (path2
) == 0
277 wxString
wxPathList::FindValidPath (const wxString
& file
)
279 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
280 return wxString(wxFileFunctionsBuffer
);
282 wxChar buf
[_MAXPATHLEN
];
283 wxStrcpy(buf
, wxFileFunctionsBuffer
);
285 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
286 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
288 for (wxNode
* node
= First (); node
; node
= node
->Next ())
290 wxChar
*path
= (wxChar
*) node
->Data ();
291 wxStrcpy (wxFileFunctionsBuffer
, path
);
292 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
293 if (ch
!= wxT('\\') && ch
!= wxT('/'))
294 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
295 wxStrcat (wxFileFunctionsBuffer
, filename
);
297 Unix2DosFilename (wxFileFunctionsBuffer
);
299 if (wxFileExists (wxFileFunctionsBuffer
))
301 return wxString(wxFileFunctionsBuffer
); // Found!
305 return wxString(wxT("")); // Not found
308 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
310 wxString f
= FindValidPath(file
);
311 if ( wxIsAbsolutePath(f
) )
315 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
317 if ( !wxEndsWithPathSeparator(buf
) )
319 buf
+= wxFILE_SEP_PATH
;
327 wxFileExists (const wxString
& filename
)
329 // we must use GetFileAttributes() instead of the ANSI C functions because
330 // it can cope with network (UNC) paths unlike them
331 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
332 DWORD ret
= ::GetFileAttributes(filename
);
334 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
337 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
338 #endif // __WIN32__/!__WIN32__
342 wxIsAbsolutePath (const wxString
& filename
)
344 if (filename
!= wxT(""))
346 #if defined(__WXMAC__) && !defined(__DARWIN__)
347 // Classic or Carbon CodeWarrior like
348 // Carbon with Apple DevTools is Unix like
350 // This seems wrong to me, but there is no fix. since
351 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
352 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
353 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
356 // Unix like or Windows
357 if (filename
[0] == wxT('/'))
361 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
366 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
374 * Strip off any extension (dot something) from end of file,
375 * IF one exists. Inserts zero into buffer.
379 void wxStripExtension(wxChar
*buffer
)
381 int len
= wxStrlen(buffer
);
385 if (buffer
[i
] == wxT('.'))
394 void wxStripExtension(wxString
& buffer
)
396 size_t len
= buffer
.Length();
400 if (buffer
.GetChar(i
) == wxT('.'))
402 buffer
= buffer
.Left(i
);
409 // Destructive removal of /./ and /../ stuff
410 wxChar
*wxRealPath (wxChar
*path
)
413 static const wxChar SEP
= wxT('\\');
414 Unix2DosFilename(path
);
416 static const wxChar SEP
= wxT('/');
418 if (path
[0] && path
[1]) {
419 /* MATTHEW: special case "/./x" */
421 if (path
[2] == SEP
&& path
[1] == wxT('.'))
429 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
432 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
433 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
434 && (q
- 1 <= path
|| q
[-1] != SEP
))
437 if (path
[0] == wxT('\0'))
443 /* Check that path[2] is NULL! */
444 else if (path
[1] == wxT(':') && !path
[2])
453 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
462 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
464 if (filename
== wxT(""))
465 return (wxChar
*) NULL
;
467 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
468 wxChar buf
[_MAXPATHLEN
];
470 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
471 wxChar ch
= buf
[wxStrlen(buf
) - 1];
473 if (ch
!= wxT('\\') && ch
!= wxT('/'))
474 wxStrcat(buf
, wxT("\\"));
477 wxStrcat(buf
, wxT("/"));
479 wxStrcat(buf
, wxFileFunctionsBuffer
);
480 return copystring( wxRealPath(buf
) );
482 return copystring( wxFileFunctionsBuffer
);
488 ~user/ => user's home dir
489 If the environment variable a = "foo" and b = "bar" then:
506 /* input name in name, pathname output to buf. */
508 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
510 register wxChar
*d
, *s
, *nm
;
511 wxChar lnm
[_MAXPATHLEN
];
514 // Some compilers don't like this line.
515 // const wxChar trimchars[] = wxT("\n \t");
518 trimchars
[0] = wxT('\n');
519 trimchars
[1] = wxT(' ');
520 trimchars
[2] = wxT('\t');
524 const wxChar SEP
= wxT('\\');
526 const wxChar SEP
= wxT('/');
529 if (name
== NULL
|| *name
== wxT('\0'))
531 nm
= copystring(name
); // Make a scratch copy
534 /* Skip leading whitespace and cr */
535 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
537 /* And strip off trailing whitespace and cr */
538 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
539 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
547 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
550 /* Expand inline environment variables */
568 while ((*d
++ = *s
) != 0) {
570 if (*s
== wxT('\\')) {
571 if ((*(d
- 1) = *++s
)) {
580 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
582 if (*s
++ == wxT('$'))
585 register wxChar
*start
= d
;
586 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
587 register wxChar
*value
;
588 while ((*d
++ = *s
) != 0)
589 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
594 value
= wxGetenv(braces
? start
+ 1 : start
);
596 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
604 /* Expand ~ and ~user */
606 if (nm
[0] == wxT('~') && !q
)
609 if (nm
[1] == SEP
|| nm
[1] == 0)
611 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
612 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
617 { /* ~user/filename */
618 register wxChar
*nnm
;
619 register wxChar
*home
;
620 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
621 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
622 was_sep
= (*s
== SEP
);
623 nnm
= *s
? s
+ 1 : s
;
625 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
626 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
627 if (was_sep
) /* replace only if it was there: */
638 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
640 while (wxT('\0') != (*d
++ = *s
++))
643 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
647 while ((*d
++ = *s
++) != 0);
648 delete[] nm_tmp
; // clean up alloc
649 /* Now clean up the buffer */
650 return wxRealPath(buf
);
653 /* Contract Paths to be build upon an environment variable
656 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
658 The call wxExpandPath can convert these back!
661 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
663 static wxChar dest
[_MAXPATHLEN
];
665 if (filename
== wxT(""))
666 return (wxChar
*) NULL
;
668 wxStrcpy (dest
, WXSTRINGCAST filename
);
670 Unix2DosFilename(dest
);
673 // Handle environment
674 const wxChar
*val
= (const wxChar
*) NULL
;
675 wxChar
*tcp
= (wxChar
*) NULL
;
676 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
677 (tcp
= wxStrstr (dest
, val
)) != NULL
)
679 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
682 wxStrcpy (tcp
, WXSTRINGCAST envname
);
683 wxStrcat (tcp
, wxT("}"));
684 wxStrcat (tcp
, wxFileFunctionsBuffer
);
687 // Handle User's home (ignore root homes!)
689 if ((val
= wxGetUserHome (user
)) != NULL
&&
690 (len
= wxStrlen(val
)) > 2 &&
691 wxStrncmp(dest
, val
, len
) == 0)
693 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
695 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
696 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
697 wxStrcpy (dest
, wxFileFunctionsBuffer
);
703 // Return just the filename, not the path (basename)
704 wxChar
*wxFileNameFromPath (wxChar
*path
)
707 wxString n
= wxFileNameFromPath(p
);
709 return path
+ p
.length() - n
.length();
712 wxString
wxFileNameFromPath (const wxString
& path
)
715 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
717 wxString fullname
= name
;
720 fullname
<< wxFILE_SEP_EXT
<< ext
;
726 // Return just the directory, or NULL if no directory
728 wxPathOnly (wxChar
*path
)
732 static wxChar buf
[_MAXPATHLEN
];
735 wxStrcpy (buf
, path
);
737 int l
= wxStrlen(path
);
740 // Search backward for a backward or forward slash
743 #if defined(__WXMAC__) && !defined(__DARWIN__)
744 // Classic or Carbon CodeWarrior like
745 // Carbon with Apple DevTools is Unix like
746 if (path
[i
] == wxT(':') )
752 // Unix like or Windows
753 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
760 if (path
[i
] == wxT(']'))
769 #if defined(__WXMSW__) || defined(__WXPM__)
770 // Try Drive specifier
771 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
773 // A:junk --> A:. (since A:.\junk Not A:\junk)
780 return (wxChar
*) NULL
;
783 // Return just the directory, or NULL if no directory
784 wxString
wxPathOnly (const wxString
& path
)
788 wxChar buf
[_MAXPATHLEN
];
791 wxStrcpy (buf
, WXSTRINGCAST path
);
793 int l
= path
.Length();
796 // Search backward for a backward or forward slash
799 #if defined(__WXMAC__) && !defined(__DARWIN__)
800 // Classic or Carbon CodeWarrior like
801 // Carbon with Apple DevTools is Unix like
802 if (path
[i
] == wxT(':') )
805 return wxString(buf
);
808 // Unix like or Windows
809 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
812 return wxString(buf
);
816 if (path
[i
] == wxT(']'))
819 return wxString(buf
);
825 #if defined(__WXMSW__) || defined(__WXPM__)
826 // Try Drive specifier
827 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
829 // A:junk --> A:. (since A:.\junk Not A:\junk)
832 return wxString(buf
);
836 return wxString(wxT(""));
839 // Utility for converting delimiters in DOS filenames to UNIX style
840 // and back again - or we get nasty problems with delimiters.
841 // Also, convert to lower case, since case is significant in UNIX.
843 #if defined(__WXMAC__)
844 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
851 Boolean isDirectory
= false;
852 Str255 theParentPath
= "\p";
853 FSSpec theParentSpec
;
855 char theFileName
[FILENAME_MAX
];
856 char thePath
[FILENAME_MAX
];
860 // GD: Separate file name from path and make a FSRef to the parent
861 // directory. This is necessary since FSRefs cannot reference files
862 // that have not yet been created.
863 // Based on example code from Apple Technical Note TN2022
864 // http://developer.apple.com/technotes/tn/tn2022.html
866 // check whether we are converting a directory
867 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
868 // count length of file name
869 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
871 // prepend path separator since it will later be appended to the path
872 theFileName
[0] = wxFILE_SEP_PATH
;
873 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
874 theFileName
[j
- i
] = spec
->name
[j
];
876 theFileName
[j
- i
] = '\0';
878 for (j
= 1; j
<= i
; j
++) {
879 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
881 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
882 if (theErr
== noErr
) {
883 // convert the FSSpec to an FSRef
884 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
886 if (theErr
== noErr
) {
887 // get the POSIX path associated with the FSRef
888 theStatus
= FSRefMakePath(&theParentRef
,
889 (UInt8
*)thePath
, sizeof(thePath
));
891 if (theStatus
== noErr
) {
892 // append file name to path
893 // includes previously prepended path separator
894 strcat(thePath
, theFileName
);
897 // create path string for return value
898 wxString
result( thePath
) ;
903 // get length of path and allocate handle
904 FSpGetFullPath( spec
, &length
, &myPath
) ;
905 ::SetHandleSize( myPath
, length
+ 1 ) ;
907 (*myPath
)[length
] = 0 ;
908 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
909 (*myPath
)[length
-1] = 0 ;
911 // create path string for return value
912 wxString
result( (char*) *myPath
) ;
914 // free allocated handle
915 ::HUnlock( myPath
) ;
916 ::DisposeHandle( myPath
) ;
922 // Mac file names are POSIX (Unix style) under Darwin
923 // therefore the conversion functions below are not needed
925 static char sMacFileNameConversion
[ 1000 ] ;
928 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
930 OSStatus err
= noErr
;
934 // get the FSRef associated with the POSIX path
935 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
936 // convert the FSRef to an FSSpec
937 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
939 if ( strchr( path
, ':' ) == NULL
)
941 // try whether it is a volume / or a mounted volume
942 strncpy( sMacFileNameConversion
, path
, 1000 ) ;
943 sMacFileNameConversion
[998] = 0 ;
944 strcat( sMacFileNameConversion
, ":" ) ;
945 err
= FSpLocationFromFullPath( strlen(sMacFileNameConversion
) , sMacFileNameConversion
, spec
) ;
949 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
956 wxString
wxMac2UnixFilename (const char *str
)
958 char *s
= sMacFileNameConversion
;
962 memmove( s
+1 , s
,strlen( s
) + 1) ;
973 *s
= wxTolower(*s
); // Case INDEPENDENT
977 return wxString(sMacFileNameConversion
) ;
980 wxString
wxUnix2MacFilename (const char *str
)
982 char *s
= sMacFileNameConversion
;
988 // relative path , since it goes on with slash which is translated to a :
989 memmove( s
, s
+1 ,strlen( s
) ) ;
991 else if ( *s
== '/' )
993 // absolute path -> on mac just start with the drive name
994 memmove( s
, s
+1 ,strlen( s
) ) ;
998 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
1002 if (*s
== '/' || *s
== '\\')
1004 // convert any back-directory situations
1005 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1008 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
1016 return wxString (sMacFileNameConversion
) ;
1019 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1021 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1024 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1026 wxString var
= wxUnix2MacFilename( path
) ;
1027 wxMacFilename2FSSpec( var
, spec
) ;
1029 #endif // ! __DARWIN__
1034 wxDos2UnixFilename (char *s
)
1043 *s
= wxTolower (*s
); // Case INDEPENDENT
1050 #if defined(__WXMSW__) || defined(__WXPM__)
1051 wxUnix2DosFilename (wxChar
*s
)
1053 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1056 // Yes, I really mean this to happen under DOS only! JACS
1057 #if defined(__WXMSW__) || defined(__WXPM__)
1068 // Concatenate two files to form third
1070 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1073 if ( !wxGetTempFileName("cat", outfile
) )
1076 FILE *fp1
= (FILE *) NULL
;
1077 FILE *fp2
= (FILE *) NULL
;
1078 FILE *fp3
= (FILE *) NULL
;
1079 // Open the inputs and outputs
1080 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1081 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1082 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1094 while ((ch
= getc (fp1
)) != EOF
)
1095 (void) putc (ch
, fp3
);
1098 while ((ch
= getc (fp2
)) != EOF
)
1099 (void) putc (ch
, fp3
);
1103 bool result
= wxRenameFile(outfile
, file3
);
1109 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1111 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1112 // CopyFile() copies file attributes and modification time too, so use it
1113 // instead of our code if available
1115 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1116 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1118 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1119 file1
.c_str(), file2
.c_str());
1123 #elif defined(__WXPM__)
1124 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1129 // get permissions of file1
1130 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1132 // the file probably doesn't exist or we haven't the rights to read
1134 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1139 // open file1 for reading
1140 wxFile
fileIn(file1
, wxFile::read
);
1141 if ( !fileIn
.IsOpened() )
1144 // remove file2, if it exists. This is needed for creating
1145 // file2 with the correct permissions in the next step
1146 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1148 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1154 // reset the umask as we want to create the file with exactly the same
1155 // permissions as the original one
1156 mode_t oldUmask
= umask( 0 );
1159 // create file2 with the same permissions than file1 and open it for
1163 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1167 /// restore the old umask
1171 // copy contents of file1 to file2
1176 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1177 if ( fileIn
.Error() )
1184 if ( fileOut
.Write(buf
, count
) < count
)
1188 // we can expect fileIn to be closed successfully, but we should ensure
1189 // that fileOut was closed as some write errors (disk full) might not be
1190 // detected before doing this
1191 if ( !fileIn
.Close() || !fileOut
.Close() )
1194 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1195 // no chmod in VA. Should be some permission API for HPFS386 partitions
1197 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1199 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1203 #endif // OS/2 || Mac
1204 #endif // __WXMSW__ && __WIN32__
1210 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1212 // Normal system call
1213 if ( wxRename (file1
, file2
) == 0 )
1217 if (wxCopyFile(file1
, file2
)) {
1218 wxRemoveFile(file1
);
1225 bool wxRemoveFile(const wxString
& file
)
1227 #if defined(__VISUALC__) \
1228 || defined(__BORLANDC__) \
1229 || defined(__WATCOMC__) \
1230 || defined(__GNUWIN32__)
1231 int res
= wxRemove(file
);
1233 int res
= unlink(OS_FILENAME(file
));
1239 bool wxMkdir(const wxString
& dir
, int perm
)
1241 #if defined(__WXMAC__) && !defined(__UNIX__)
1242 return (mkdir( dir
, 0 ) == 0);
1244 const wxChar
*dirname
= dir
.c_str();
1246 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1247 // for the GNU compiler
1248 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1249 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1250 #elif defined(__WXPM__)
1251 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1252 #elif defined(__DOS__)
1253 #if defined(__WATCOMC__)
1255 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1256 #elif defined(__DJGPP__)
1257 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1259 #error "Unsupported DOS compiler!"
1261 #else // !MSW, !DOS and !OS/2 VAC++
1263 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1266 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1275 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1278 return FALSE
; //to be changed since rmdir exists in VMS7.x
1279 #elif defined(__WXPM__)
1280 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1284 return FALSE
; // What to do?
1286 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1292 // does the path exists? (may have or not '/' or '\\' at the end)
1293 bool wxPathExists(const wxChar
*pszPathName
)
1295 wxString
strPath(pszPathName
);
1298 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1299 // so remove all trailing backslashes from the path - but don't do this for
1300 // the pathes "d:\" (which are different from "d:") nor for just "\"
1301 while ( wxEndsWithPathSeparator(strPath
) )
1303 size_t len
= strPath
.length();
1304 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1307 strPath
.Truncate(len
- 1);
1309 #endif // __WINDOWS__
1311 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1312 // stat() can't cope with network paths
1313 DWORD ret
= ::GetFileAttributes(strPath
);
1315 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1319 #ifndef __VISAGECPP__
1320 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1322 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1323 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1326 #endif // __WIN32__/!__WIN32__
1329 // Get a temporary filename, opening and closing the file.
1330 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1332 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1333 if ( filename
.empty() )
1337 wxStrcpy(buf
, filename
);
1339 buf
= copystring(filename
);
1344 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1346 buf
= wxFileName::CreateTempFileName(prefix
);
1348 return !buf
.empty();
1351 // Get first file name matching given wild card.
1353 static wxDir
*gs_dir
= NULL
;
1354 static wxString gs_dirPath
;
1356 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1358 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1359 if ( gs_dirPath
.IsEmpty() )
1360 gs_dirPath
= wxT(".");
1361 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1362 gs_dirPath
<< wxFILE_SEP_PATH
;
1366 gs_dir
= new wxDir(gs_dirPath
);
1368 if ( !gs_dir
->IsOpened() )
1370 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1371 return wxEmptyString
;
1377 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1378 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1379 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1383 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1384 if ( result
.IsEmpty() )
1390 return gs_dirPath
+ result
;
1393 wxString
wxFindNextFile()
1395 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1398 gs_dir
->GetNext(&result
);
1400 if ( result
.IsEmpty() )
1406 return gs_dirPath
+ result
;
1410 // Get current working directory.
1411 // If buf is NULL, allocates space using new, else
1413 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1417 buf
= new wxChar
[sz
+ 1];
1422 // for the compilers which have Unicode version of _getcwd(), call it
1423 // directly, for the others call the ANSI version and do the translation
1426 #else // wxUSE_UNICODE
1427 bool needsANSI
= TRUE
;
1429 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1430 // This is not legal code as the compiler
1431 // is allowed destroy the wxCharBuffer.
1432 // wxCharBuffer c_buffer(sz);
1433 // char *cbuf = (char*)(const char*)c_buffer;
1434 char cbuf
[_MAXPATHLEN
];
1438 #if wxUSE_UNICODE_MSLU
1439 if ( wxGetOsVersion() != wxWIN95
)
1441 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1444 ok
= _wgetcwd(buf
, sz
) != NULL
;
1450 #endif // wxUSE_UNICODE
1453 ok
= _getcwd(cbuf
, sz
) != NULL
;
1454 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1459 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1461 pb
.ioRefNum
= LMGetCurApRefNum();
1463 error
= PBGetFCBInfoSync(&pb
);
1464 if ( error
== noErr
)
1466 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1467 cwdSpec
.parID
= pb
.ioFCBParID
;
1468 cwdSpec
.name
[0] = 0 ;
1469 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1471 strcpy( cbuf
, res
) ;
1472 cbuf
[res
.length()]=0 ;
1480 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1482 rc
= ::DosQueryCurrentDir( 0 // current drive
1487 #else // !Win32/VC++ !Mac !OS2
1488 ok
= getcwd(cbuf
, sz
) != NULL
;
1492 // finally convert the result to Unicode if needed
1493 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1494 #endif // wxUSE_UNICODE
1499 wxLogSysError(_("Failed to get the working directory"));
1501 // VZ: the old code used to return "." on error which didn't make any
1502 // sense at all to me - empty string is a better error indicator
1503 // (NULL might be even better but I'm afraid this could lead to
1504 // problems with the old code assuming the return is never NULL)
1507 else // ok, but we might need to massage the path into the right format
1510 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1511 // with / deliminers. We don't like that.
1512 for (wxChar
*ch
= buf
; *ch
; ch
++)
1514 if (*ch
== wxT('/'))
1519 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1520 // he needs Unix as opposed to Win32 pathnames
1521 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1522 // another example of DOS/Unix mix (Cygwin)
1523 wxString pathUnix
= buf
;
1524 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1525 #endif // __CYGWIN__
1537 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1538 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1539 wxString
str( buffer
);
1545 bool wxSetWorkingDirectory(const wxString
& d
)
1547 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1548 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1549 #elif defined(__WXPM__)
1550 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1551 #elif defined(__WINDOWS__)
1554 return (bool)(SetCurrentDirectory(d
) != 0);
1556 // Must change drive, too.
1557 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1560 wxChar firstChar
= d
[0];
1564 firstChar
= firstChar
- 32;
1566 // To a drive number
1567 unsigned int driveNo
= firstChar
- 64;
1570 unsigned int noDrives
;
1571 _dos_setdrive(driveNo
, &noDrives
);
1574 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1582 // Get the OS directory if appropriate (such as the Windows directory).
1583 // On non-Windows platform, probably just return the empty string.
1584 wxString
wxGetOSDirectory()
1586 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1588 GetWindowsDirectory(buf
, 256);
1589 return wxString(buf
);
1591 return wxEmptyString
;
1595 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1597 size_t len
= wxStrlen(pszFileName
);
1599 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1602 // find a file in a list of directories, returns false if not found
1603 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1605 // we assume that it's not empty
1606 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1607 _T("empty file name in wxFindFileInPath"));
1609 // skip path separator in the beginning of the file name if present
1610 if ( wxIsPathSeparator(*pszFile
) )
1613 // copy the path (strtok will modify it)
1614 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1615 wxStrcpy(szPath
, pszPath
);
1618 wxChar
*pc
, *save_ptr
;
1619 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1621 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1623 // search for the file in this directory
1625 if ( !wxEndsWithPathSeparator(pc
) )
1626 strFile
+= wxFILE_SEP_PATH
;
1629 if ( FileExists(strFile
) ) {
1635 // suppress warning about unused variable save_ptr when wxStrtok() is a
1636 // macro which throws away its third argument
1641 return pc
!= NULL
; // if true => we breaked from the loop
1644 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1649 // it can be empty, but it shouldn't be NULL
1650 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1652 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1655 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1658 wxStat( filename
, &buf
);
1660 return buf
.st_mtime
;
1664 //------------------------------------------------------------------------
1665 // wild character routines
1666 //------------------------------------------------------------------------
1668 bool wxIsWild( const wxString
& pattern
)
1670 wxString tmp
= pattern
;
1671 wxChar
*pat
= WXSTRINGCAST(tmp
);
1674 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1684 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1688 // this probably won't work well for multibyte chars in Unicode mode?
1690 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1692 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1694 #else // !HAVE_FNMATCH
1696 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1699 * WARNING: this code is broken!
1702 wxString tmp1
= pat
;
1703 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1704 wxString tmp2
= text
;
1705 wxChar
*str
= WXSTRINGCAST(tmp2
);
1708 bool done
= FALSE
, ret_code
, ok
;
1709 // Below is for vi fans
1710 const wxChar OB
= wxT('{'), CB
= wxT('}');
1712 // dot_special means '.' only matches '.'
1713 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1716 while ((*pattern
!= wxT('\0')) && (!done
)
1717 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1721 if (*pattern
!= wxT('\0'))
1727 while ((*str
!=wxT('\0'))
1728 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1731 while (*str
!= wxT('\0'))
1733 while (*pattern
!= wxT('\0'))
1740 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1744 if (*pattern
== wxT('\\')) {
1746 if (*pattern
== wxT('\0')) {
1751 if (*(pattern
+ 1) == wxT('-')) {
1754 if (*pattern
== wxT(']')) {
1758 if (*pattern
== wxT('\\')) {
1760 if (*pattern
== wxT('\0')) {
1765 if ((*str
< c
) || (*str
> *pattern
)) {
1769 } else if (*pattern
!= *str
) {
1774 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1775 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1779 if (*pattern
!= wxT('\0')) {
1789 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1792 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1793 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1794 if (*pattern
== wxT('\\'))
1796 ok
= (*pattern
++ == *cp
++);
1798 if (*pattern
== wxT('\0')) {
1804 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1805 if (*++pattern
== wxT('\\')) {
1806 if (*++pattern
== CB
)
1811 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1812 if (*++pattern
== wxT('\\')) {
1813 if (*++pattern
== CB
|| *pattern
== wxT(','))
1818 if (*pattern
!= wxT('\0'))
1823 if (*str
== *pattern
) {
1830 while (*pattern
== wxT('*'))
1832 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1835 #endif // HAVE_FNMATCH/!HAVE_FNMATCH
1838 #pragma warning(default:4706) // assignment within conditional expression