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
148 # include "MoreFilesX.h"
150 # include "MoreFiles.h"
151 # include "MoreFilesExtras.h"
152 # include "FullPath.h"
153 # include "FSpCompat.h"
157 // ----------------------------------------------------------------------------
159 // ----------------------------------------------------------------------------
161 // MT-FIXME: get rid of this horror and all code using it
162 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
164 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
166 // VisualAge C++ V4.0 cannot have any external linkage const decs
167 // in headers included by more than one primary source
169 const off_t wxInvalidOffset
= (off_t
)-1;
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
176 // we need to translate Mac filenames before passing them to OS functions
177 #define OS_FILENAME(s) (s.fn_str())
179 // ============================================================================
181 // ============================================================================
183 #ifdef wxNEED_WX_UNISTD_H
185 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
187 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
190 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
192 return access( wxConvFile
.cWX2MB( pathname
), mode
);
195 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
197 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
201 // wxNEED_WX_UNISTD_H
203 // ----------------------------------------------------------------------------
205 // ----------------------------------------------------------------------------
207 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
209 void wxPathList::Add (const wxString
& path
)
211 wxStringList::Add (WXSTRINGCAST path
);
214 // Add paths e.g. from the PATH environment variable
215 void wxPathList::AddEnvList (const wxString
& envVariable
)
217 static const wxChar PATH_TOKS
[] =
219 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
224 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
227 wxChar
*s
= copystring (val
);
228 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
232 Add (copystring (token
));
235 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
236 Add (wxString(token
));
240 // suppress warning about unused variable save_ptr when wxStrtok() is a
241 // macro which throws away its third argument
248 // Given a full filename (with path), ensure that that file can
249 // be accessed again USING FILENAME ONLY by adding the path
250 // to the list if not already there.
251 void wxPathList::EnsureFileAccessible (const wxString
& path
)
253 wxString
path_only(wxPathOnly(path
));
254 if ( !path_only
.IsEmpty() )
256 if ( !Member(path_only
) )
261 bool wxPathList::Member (const wxString
& path
)
263 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
265 wxString
path2((wxChar
*) node
->Data ());
267 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
269 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
271 // Case sensitive File System
272 path
.CompareTo (path2
) == 0
280 wxString
wxPathList::FindValidPath (const wxString
& file
)
282 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
283 return wxString(wxFileFunctionsBuffer
);
285 wxChar buf
[_MAXPATHLEN
];
286 wxStrcpy(buf
, wxFileFunctionsBuffer
);
288 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
289 filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
291 for (wxNode
* node
= First (); node
; node
= node
->Next ())
293 wxChar
*path
= (wxChar
*) node
->Data ();
294 wxStrcpy (wxFileFunctionsBuffer
, path
);
295 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
296 if (ch
!= wxT('\\') && ch
!= wxT('/'))
297 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
298 wxStrcat (wxFileFunctionsBuffer
, filename
);
300 wxUnix2DosFilename (wxFileFunctionsBuffer
);
302 if (wxFileExists (wxFileFunctionsBuffer
))
304 return wxString(wxFileFunctionsBuffer
); // Found!
308 return wxString(wxT("")); // Not found
311 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
313 wxString f
= FindValidPath(file
);
314 if ( wxIsAbsolutePath(f
) )
318 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
320 if ( !wxEndsWithPathSeparator(buf
) )
322 buf
+= wxFILE_SEP_PATH
;
330 wxFileExists (const wxString
& filename
)
332 // we must use GetFileAttributes() instead of the ANSI C functions because
333 // it can cope with network (UNC) paths unlike them
334 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
335 DWORD ret
= ::GetFileAttributes(filename
);
337 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
340 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
341 #endif // __WIN32__/!__WIN32__
345 wxIsAbsolutePath (const wxString
& filename
)
347 if (filename
!= wxT(""))
349 #if defined(__WXMAC__) && !defined(__DARWIN__)
350 // Classic or Carbon CodeWarrior like
351 // Carbon with Apple DevTools is Unix like
353 // This seems wrong to me, but there is no fix. since
354 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
355 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
356 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
359 // Unix like or Windows
360 if (filename
[0] == wxT('/'))
364 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
369 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
377 * Strip off any extension (dot something) from end of file,
378 * IF one exists. Inserts zero into buffer.
382 void wxStripExtension(wxChar
*buffer
)
384 int len
= wxStrlen(buffer
);
388 if (buffer
[i
] == wxT('.'))
397 void wxStripExtension(wxString
& buffer
)
399 size_t len
= buffer
.Length();
403 if (buffer
.GetChar(i
) == wxT('.'))
405 buffer
= buffer
.Left(i
);
412 // Destructive removal of /./ and /../ stuff
413 wxChar
*wxRealPath (wxChar
*path
)
416 static const wxChar SEP
= wxT('\\');
417 wxUnix2DosFilename(path
);
419 static const wxChar SEP
= wxT('/');
421 if (path
[0] && path
[1]) {
422 /* MATTHEW: special case "/./x" */
424 if (path
[2] == SEP
&& path
[1] == wxT('.'))
432 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
435 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
440 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
441 && (q
- 1 <= path
|| q
[-1] != SEP
))
444 if (path
[0] == wxT('\0'))
450 /* Check that path[2] is NULL! */
451 else if (path
[1] == wxT(':') && !path
[2])
460 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
469 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
471 if (filename
== wxT(""))
472 return (wxChar
*) NULL
;
474 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
475 wxChar buf
[_MAXPATHLEN
];
477 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
478 wxChar ch
= buf
[wxStrlen(buf
) - 1];
480 if (ch
!= wxT('\\') && ch
!= wxT('/'))
481 wxStrcat(buf
, wxT("\\"));
484 wxStrcat(buf
, wxT("/"));
486 wxStrcat(buf
, wxFileFunctionsBuffer
);
487 return copystring( wxRealPath(buf
) );
489 return copystring( wxFileFunctionsBuffer
);
495 ~user/ => user's home dir
496 If the environment variable a = "foo" and b = "bar" then:
513 /* input name in name, pathname output to buf. */
515 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
517 register wxChar
*d
, *s
, *nm
;
518 wxChar lnm
[_MAXPATHLEN
];
521 // Some compilers don't like this line.
522 // const wxChar trimchars[] = wxT("\n \t");
525 trimchars
[0] = wxT('\n');
526 trimchars
[1] = wxT(' ');
527 trimchars
[2] = wxT('\t');
531 const wxChar SEP
= wxT('\\');
533 const wxChar SEP
= wxT('/');
536 if (name
== NULL
|| *name
== wxT('\0'))
538 nm
= copystring(name
); // Make a scratch copy
541 /* Skip leading whitespace and cr */
542 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
544 /* And strip off trailing whitespace and cr */
545 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
546 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
554 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
557 /* Expand inline environment variables */
575 while ((*d
++ = *s
) != 0) {
577 if (*s
== wxT('\\')) {
578 if ((*(d
- 1) = *++s
)) {
587 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
589 if (*s
++ == wxT('$'))
592 register wxChar
*start
= d
;
593 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
594 register wxChar
*value
;
595 while ((*d
++ = *s
) != 0)
596 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
601 value
= wxGetenv(braces
? start
+ 1 : start
);
603 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
615 /* Expand ~ and ~user */
617 if (nm
[0] == wxT('~') && !q
)
620 if (nm
[1] == SEP
|| nm
[1] == 0)
622 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
623 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
628 { /* ~user/filename */
629 register wxChar
*nnm
;
630 register wxChar
*home
;
631 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
635 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
636 was_sep
= (*s
== SEP
);
637 nnm
= *s
? s
+ 1 : s
;
639 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
640 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
641 if (was_sep
) /* replace only if it was there: */
652 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
654 while (wxT('\0') != (*d
++ = *s
++))
657 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
661 while ((*d
++ = *s
++) != 0)
665 delete[] nm_tmp
; // clean up alloc
666 /* Now clean up the buffer */
667 return wxRealPath(buf
);
670 /* Contract Paths to be build upon an environment variable
673 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
675 The call wxExpandPath can convert these back!
678 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
680 static wxChar dest
[_MAXPATHLEN
];
682 if (filename
== wxT(""))
683 return (wxChar
*) NULL
;
685 wxStrcpy (dest
, WXSTRINGCAST filename
);
687 wxUnix2DosFilename(dest
);
690 // Handle environment
691 const wxChar
*val
= (const wxChar
*) NULL
;
692 wxChar
*tcp
= (wxChar
*) NULL
;
693 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
694 (tcp
= wxStrstr (dest
, val
)) != NULL
)
696 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
699 wxStrcpy (tcp
, WXSTRINGCAST envname
);
700 wxStrcat (tcp
, wxT("}"));
701 wxStrcat (tcp
, wxFileFunctionsBuffer
);
704 // Handle User's home (ignore root homes!)
706 if ((val
= wxGetUserHome (user
)) != NULL
&&
707 (len
= wxStrlen(val
)) > 2 &&
708 wxStrncmp(dest
, val
, len
) == 0)
710 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
712 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
713 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
714 wxStrcpy (dest
, wxFileFunctionsBuffer
);
720 // Return just the filename, not the path (basename)
721 wxChar
*wxFileNameFromPath (wxChar
*path
)
724 wxString n
= wxFileNameFromPath(p
);
726 return path
+ p
.length() - n
.length();
729 wxString
wxFileNameFromPath (const wxString
& path
)
732 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
734 wxString fullname
= name
;
737 fullname
<< wxFILE_SEP_EXT
<< ext
;
743 // Return just the directory, or NULL if no directory
745 wxPathOnly (wxChar
*path
)
749 static wxChar buf
[_MAXPATHLEN
];
752 wxStrcpy (buf
, path
);
754 int l
= wxStrlen(path
);
757 // Search backward for a backward or forward slash
760 #if defined(__WXMAC__) && !defined(__DARWIN__)
761 // Classic or Carbon CodeWarrior like
762 // Carbon with Apple DevTools is Unix like
763 if (path
[i
] == wxT(':') )
769 // Unix like or Windows
770 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
777 if (path
[i
] == wxT(']'))
786 #if defined(__WXMSW__) || defined(__WXPM__)
787 // Try Drive specifier
788 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
790 // A:junk --> A:. (since A:.\junk Not A:\junk)
797 return (wxChar
*) NULL
;
800 // Return just the directory, or NULL if no directory
801 wxString
wxPathOnly (const wxString
& path
)
805 wxChar buf
[_MAXPATHLEN
];
808 wxStrcpy (buf
, WXSTRINGCAST path
);
810 int l
= path
.Length();
813 // Search backward for a backward or forward slash
816 #if defined(__WXMAC__) && !defined(__DARWIN__)
817 // Classic or Carbon CodeWarrior like
818 // Carbon with Apple DevTools is Unix like
819 if (path
[i
] == wxT(':') )
822 return wxString(buf
);
825 // Unix like or Windows
826 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
829 return wxString(buf
);
833 if (path
[i
] == wxT(']'))
836 return wxString(buf
);
842 #if defined(__WXMSW__) || defined(__WXPM__)
843 // Try Drive specifier
844 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
846 // A:junk --> A:. (since A:.\junk Not A:\junk)
849 return wxString(buf
);
853 return wxString(wxT(""));
856 // Utility for converting delimiters in DOS filenames to UNIX style
857 // and back again - or we get nasty problems with delimiters.
858 // Also, convert to lower case, since case is significant in UNIX.
860 #if defined(__WXMAC__)
861 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
868 Boolean isDirectory
= false;
869 Str255 theParentPath
= "\p";
870 FSSpec theParentSpec
;
872 char theFileName
[FILENAME_MAX
];
873 char thePath
[FILENAME_MAX
];
877 // GD: Separate file name from path and make a FSRef to the parent
878 // directory. This is necessary since FSRefs cannot reference files
879 // that have not yet been created.
880 // Based on example code from Apple Technical Note TN2022
881 // http://developer.apple.com/technotes/tn/tn2022.html
883 // check whether we are converting a directory
884 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
885 // count length of file name
886 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
888 // prepend path separator since it will later be appended to the path
889 theFileName
[0] = wxFILE_SEP_PATH
;
890 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
891 theFileName
[j
- i
] = spec
->name
[j
];
893 theFileName
[j
- i
] = '\0';
895 for (j
= 1; j
<= i
; j
++) {
896 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
898 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
899 if (theErr
== noErr
) {
900 // convert the FSSpec to an FSRef
901 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
903 if (theErr
== noErr
) {
904 // get the POSIX path associated with the FSRef
905 theStatus
= FSRefMakePath(&theParentRef
,
906 (UInt8
*)thePath
, sizeof(thePath
));
908 if (theStatus
== noErr
) {
909 // append file name to path
910 // includes previously prepended path separator
911 strcat(thePath
, theFileName
);
914 // create path string for return value
915 wxString
result( thePath
) ;
920 // get length of path and allocate handle
921 FSpGetFullPath( spec
, &length
, &myPath
) ;
922 ::SetHandleSize( myPath
, length
+ 1 ) ;
924 (*myPath
)[length
] = 0 ;
925 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
926 (*myPath
)[length
-1] = 0 ;
928 // create path string for return value
929 wxString
result( (char*) *myPath
) ;
931 // free allocated handle
932 ::HUnlock( myPath
) ;
933 ::DisposeHandle( myPath
) ;
939 // Mac file names are POSIX (Unix style) under Darwin
940 // therefore the conversion functions below are not needed
942 static char sMacFileNameConversion
[ 1000 ] ;
945 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
947 OSStatus err
= noErr
;
951 // get the FSRef associated with the POSIX path
952 err
= FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
953 // convert the FSRef to an FSSpec
954 err
= FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
956 if ( strchr( path
, ':' ) == NULL
)
958 // try whether it is a volume / or a mounted volume
959 strncpy( sMacFileNameConversion
, path
, 1000 ) ;
960 sMacFileNameConversion
[998] = 0 ;
961 strcat( sMacFileNameConversion
, ":" ) ;
962 err
= FSpLocationFromFullPath( strlen(sMacFileNameConversion
) , sMacFileNameConversion
, spec
) ;
966 err
= FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
973 wxString
wxMac2UnixFilename (const char *str
)
975 char *s
= sMacFileNameConversion
;
979 memmove( s
+1 , s
,strlen( s
) + 1) ;
990 *s
= wxTolower(*s
); // Case INDEPENDENT
994 return wxString(sMacFileNameConversion
) ;
997 wxString
wxUnix2MacFilename (const char *str
)
999 char *s
= sMacFileNameConversion
;
1005 // relative path , since it goes on with slash which is translated to a :
1006 memmove( s
, s
+1 ,strlen( s
) ) ;
1008 else if ( *s
== '/' )
1010 // absolute path -> on mac just start with the drive name
1011 memmove( s
, s
+1 ,strlen( s
) ) ;
1015 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
1019 if (*s
== '/' || *s
== '\\')
1021 // convert any back-directory situations
1022 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1025 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
1033 return wxString (sMacFileNameConversion
) ;
1036 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1038 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1041 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1043 wxString var
= wxUnix2MacFilename( path
) ;
1044 wxMacFilename2FSSpec( var
, spec
) ;
1046 #endif // ! __DARWIN__
1051 wxDos2UnixFilename (char *s
)
1060 *s
= wxTolower (*s
); // Case INDEPENDENT
1067 #if defined(__WXMSW__) || defined(__WXPM__)
1068 wxUnix2DosFilename (wxChar
*s
)
1070 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1073 // Yes, I really mean this to happen under DOS only! JACS
1074 #if defined(__WXMSW__) || defined(__WXPM__)
1085 // Concatenate two files to form third
1087 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1090 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1093 FILE *fp1
= (FILE *) NULL
;
1094 FILE *fp2
= (FILE *) NULL
;
1095 FILE *fp3
= (FILE *) NULL
;
1096 // Open the inputs and outputs
1097 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1098 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1099 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1111 while ((ch
= getc (fp1
)) != EOF
)
1112 (void) putc (ch
, fp3
);
1115 while ((ch
= getc (fp2
)) != EOF
)
1116 (void) putc (ch
, fp3
);
1120 bool result
= wxRenameFile(outfile
, file3
);
1126 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1128 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1129 // CopyFile() copies file attributes and modification time too, so use it
1130 // instead of our code if available
1132 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1133 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1135 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1136 file1
.c_str(), file2
.c_str());
1140 #elif defined(__WXPM__)
1141 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1146 // get permissions of file1
1147 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1149 // the file probably doesn't exist or we haven't the rights to read
1151 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1156 // open file1 for reading
1157 wxFile
fileIn(file1
, wxFile::read
);
1158 if ( !fileIn
.IsOpened() )
1161 // remove file2, if it exists. This is needed for creating
1162 // file2 with the correct permissions in the next step
1163 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1165 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1171 // reset the umask as we want to create the file with exactly the same
1172 // permissions as the original one
1173 mode_t oldUmask
= umask( 0 );
1176 // create file2 with the same permissions than file1 and open it for
1180 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1184 /// restore the old umask
1188 // copy contents of file1 to file2
1193 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1194 if ( fileIn
.Error() )
1201 if ( fileOut
.Write(buf
, count
) < count
)
1205 // we can expect fileIn to be closed successfully, but we should ensure
1206 // that fileOut was closed as some write errors (disk full) might not be
1207 // detected before doing this
1208 if ( !fileIn
.Close() || !fileOut
.Close() )
1211 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1212 // no chmod in VA. Should be some permission API for HPFS386 partitions
1214 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1216 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1220 #endif // OS/2 || Mac
1221 #endif // __WXMSW__ && __WIN32__
1227 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1229 // Normal system call
1230 if ( wxRename (file1
, file2
) == 0 )
1234 if (wxCopyFile(file1
, file2
)) {
1235 wxRemoveFile(file1
);
1242 bool wxRemoveFile(const wxString
& file
)
1244 #if defined(__VISUALC__) \
1245 || defined(__BORLANDC__) \
1246 || defined(__WATCOMC__) \
1247 || defined(__GNUWIN32__)
1248 int res
= wxRemove(file
);
1250 int res
= unlink(OS_FILENAME(file
));
1256 bool wxMkdir(const wxString
& dir
, int perm
)
1258 #if defined(__WXMAC__) && !defined(__UNIX__)
1259 return (mkdir( dir
, 0 ) == 0);
1261 const wxChar
*dirname
= dir
.c_str();
1263 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1264 // for the GNU compiler
1265 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1266 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1267 #elif defined(__WXPM__)
1268 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1269 #elif defined(__DOS__)
1270 #if defined(__WATCOMC__)
1272 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1273 #elif defined(__DJGPP__)
1274 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1276 #error "Unsupported DOS compiler!"
1278 #else // !MSW, !DOS and !OS/2 VAC++
1280 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1283 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1292 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1295 return FALSE
; //to be changed since rmdir exists in VMS7.x
1296 #elif defined(__WXPM__)
1297 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1301 return FALSE
; // What to do?
1303 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1309 // does the path exists? (may have or not '/' or '\\' at the end)
1310 bool wxPathExists(const wxChar
*pszPathName
)
1312 wxString
strPath(pszPathName
);
1315 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1316 // so remove all trailing backslashes from the path - but don't do this for
1317 // the pathes "d:\" (which are different from "d:") nor for just "\"
1318 while ( wxEndsWithPathSeparator(strPath
) )
1320 size_t len
= strPath
.length();
1321 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1324 strPath
.Truncate(len
- 1);
1326 #endif // __WINDOWS__
1328 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1329 // stat() can't cope with network paths
1330 DWORD ret
= ::GetFileAttributes(strPath
);
1332 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1336 #ifndef __VISAGECPP__
1337 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1339 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1340 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1343 #endif // __WIN32__/!__WIN32__
1346 // Get a temporary filename, opening and closing the file.
1347 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1349 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1350 if ( filename
.empty() )
1354 wxStrcpy(buf
, filename
);
1356 buf
= copystring(filename
);
1361 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1363 buf
= wxFileName::CreateTempFileName(prefix
);
1365 return !buf
.empty();
1368 // Get first file name matching given wild card.
1370 static wxDir
*gs_dir
= NULL
;
1371 static wxString gs_dirPath
;
1373 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1375 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1376 if ( gs_dirPath
.IsEmpty() )
1377 gs_dirPath
= wxT(".");
1378 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1379 gs_dirPath
<< wxFILE_SEP_PATH
;
1383 gs_dir
= new wxDir(gs_dirPath
);
1385 if ( !gs_dir
->IsOpened() )
1387 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1388 return wxEmptyString
;
1394 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1395 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1396 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1400 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1401 if ( result
.IsEmpty() )
1407 return gs_dirPath
+ result
;
1410 wxString
wxFindNextFile()
1412 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1415 gs_dir
->GetNext(&result
);
1417 if ( result
.IsEmpty() )
1423 return gs_dirPath
+ result
;
1427 // Get current working directory.
1428 // If buf is NULL, allocates space using new, else
1430 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1434 buf
= new wxChar
[sz
+ 1];
1439 // for the compilers which have Unicode version of _getcwd(), call it
1440 // directly, for the others call the ANSI version and do the translation
1443 #else // wxUSE_UNICODE
1444 bool needsANSI
= TRUE
;
1446 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1447 // This is not legal code as the compiler
1448 // is allowed destroy the wxCharBuffer.
1449 // wxCharBuffer c_buffer(sz);
1450 // char *cbuf = (char*)(const char*)c_buffer;
1451 char cbuf
[_MAXPATHLEN
];
1455 #if wxUSE_UNICODE_MSLU
1456 if ( wxGetOsVersion() != wxWIN95
)
1458 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1461 ok
= _wgetcwd(buf
, sz
) != NULL
;
1467 #endif // wxUSE_UNICODE
1470 ok
= _getcwd(cbuf
, sz
) != NULL
;
1471 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1476 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1478 pb
.ioRefNum
= LMGetCurApRefNum();
1480 error
= PBGetFCBInfoSync(&pb
);
1481 if ( error
== noErr
)
1483 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1484 cwdSpec
.parID
= pb
.ioFCBParID
;
1485 cwdSpec
.name
[0] = 0 ;
1486 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1488 strcpy( cbuf
, res
) ;
1489 cbuf
[res
.length()]=0 ;
1497 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1499 rc
= ::DosQueryCurrentDir( 0 // current drive
1504 #else // !Win32/VC++ !Mac !OS2
1505 ok
= getcwd(cbuf
, sz
) != NULL
;
1509 // finally convert the result to Unicode if needed
1510 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1511 #endif // wxUSE_UNICODE
1516 wxLogSysError(_("Failed to get the working directory"));
1518 // VZ: the old code used to return "." on error which didn't make any
1519 // sense at all to me - empty string is a better error indicator
1520 // (NULL might be even better but I'm afraid this could lead to
1521 // problems with the old code assuming the return is never NULL)
1524 else // ok, but we might need to massage the path into the right format
1527 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1528 // with / deliminers. We don't like that.
1529 for (wxChar
*ch
= buf
; *ch
; ch
++)
1531 if (*ch
== wxT('/'))
1536 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1537 // he needs Unix as opposed to Win32 pathnames
1538 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1539 // another example of DOS/Unix mix (Cygwin)
1540 wxString pathUnix
= buf
;
1541 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1542 #endif // __CYGWIN__
1554 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1555 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1556 wxString
str( buffer
);
1562 bool wxSetWorkingDirectory(const wxString
& d
)
1564 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1565 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1566 #elif defined(__WXPM__)
1567 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1568 #elif defined(__WINDOWS__)
1571 return (bool)(SetCurrentDirectory(d
) != 0);
1573 // Must change drive, too.
1574 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1577 wxChar firstChar
= d
[0];
1581 firstChar
= firstChar
- 32;
1583 // To a drive number
1584 unsigned int driveNo
= firstChar
- 64;
1587 unsigned int noDrives
;
1588 _dos_setdrive(driveNo
, &noDrives
);
1591 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1599 // Get the OS directory if appropriate (such as the Windows directory).
1600 // On non-Windows platform, probably just return the empty string.
1601 wxString
wxGetOSDirectory()
1603 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1605 GetWindowsDirectory(buf
, 256);
1606 return wxString(buf
);
1608 return wxEmptyString
;
1612 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1614 size_t len
= wxStrlen(pszFileName
);
1616 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1619 // find a file in a list of directories, returns false if not found
1620 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1622 // we assume that it's not empty
1623 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1624 _T("empty file name in wxFindFileInPath"));
1626 // skip path separator in the beginning of the file name if present
1627 if ( wxIsPathSeparator(*pszFile
) )
1630 // copy the path (strtok will modify it)
1631 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1632 wxStrcpy(szPath
, pszPath
);
1635 wxChar
*pc
, *save_ptr
;
1636 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1638 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1640 // search for the file in this directory
1642 if ( !wxEndsWithPathSeparator(pc
) )
1643 strFile
+= wxFILE_SEP_PATH
;
1646 if ( wxFileExists(strFile
) ) {
1652 // suppress warning about unused variable save_ptr when wxStrtok() is a
1653 // macro which throws away its third argument
1658 return pc
!= NULL
; // if true => we breaked from the loop
1661 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1666 // it can be empty, but it shouldn't be NULL
1667 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1669 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1672 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1675 wxStat( filename
, &buf
);
1677 return buf
.st_mtime
;
1681 //------------------------------------------------------------------------
1682 // wild character routines
1683 //------------------------------------------------------------------------
1685 bool wxIsWild( const wxString
& pattern
)
1687 wxString tmp
= pattern
;
1688 wxChar
*pat
= WXSTRINGCAST(tmp
);
1693 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1704 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1706 * The match procedure is public domain code (from ircII's reg.c)
1709 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1713 /* Match if both are empty. */
1717 const wxChar
*m
= pat
.c_str(),
1728 if (dot_special
&& (*n
== wxT('.')))
1730 /* Never match so that hidden Unix files
1731 * are never found. */
1745 else if (*m
== wxT('?'))
1753 if (*m
== wxT('\\'))
1756 /* Quoting "nothing" is a bad thing */
1763 * If we are out of both strings or we just
1764 * saw a wildcard, then we can say we have a
1775 * We could check for *n == NULL at this point, but
1776 * since it's more common to have a character there,
1777 * check to see if they match first (m and n) and
1778 * then if they don't match, THEN we can check for
1796 * If there are no more characters in the
1797 * string, but we still need to find another
1798 * character (*m != NULL), then it will be
1799 * impossible to match it
1806 if (*np
== wxT(' '))
1832 #pragma warning(default:4706) // assignment within conditional expression