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>
75 #include "wx/os2/private.h"
77 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
78 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
83 #endif // native Win compiler
96 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
97 // this (3.1 I believe) and how to test for it.
98 // If this works for Borland 4.0 as well, then no worries.
107 #include "wx/setup.h"
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 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
155 // ----------------------------------------------------------------------------
157 // ----------------------------------------------------------------------------
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 void wxPathList::Add (const wxString
& path
)
182 wxStringList::Add (WXSTRINGCAST path
);
185 // Add paths e.g. from the PATH environment variable
186 void wxPathList::AddEnvList (const wxString
& envVariable
)
188 static const wxChar PATH_TOKS
[] =
190 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
195 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
198 wxChar
*s
= copystring (val
);
199 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
203 Add (copystring (token
));
206 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
207 Add (wxString(token
));
211 // suppress warning about unused variable save_ptr when wxStrtok() is a
212 // macro which throws away its third argument
219 // Given a full filename (with path), ensure that that file can
220 // be accessed again USING FILENAME ONLY by adding the path
221 // to the list if not already there.
222 void wxPathList::EnsureFileAccessible (const wxString
& path
)
224 wxString
path_only(wxPathOnly(path
));
225 if ( !path_only
.IsEmpty() )
227 if ( !Member(path_only
) )
232 bool wxPathList::Member (const wxString
& path
)
234 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
236 wxString
path2((wxChar
*) node
->Data ());
238 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
240 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
242 // Case sensitive File System
243 path
.CompareTo (path2
) == 0
251 wxString
wxPathList::FindValidPath (const wxString
& file
)
253 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
254 return wxString(wxFileFunctionsBuffer
);
256 wxChar buf
[_MAXPATHLEN
];
257 wxStrcpy(buf
, wxFileFunctionsBuffer
);
259 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
260 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
262 for (wxNode
* node
= First (); node
; node
= node
->Next ())
264 wxChar
*path
= (wxChar
*) node
->Data ();
265 wxStrcpy (wxFileFunctionsBuffer
, path
);
266 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
267 if (ch
!= wxT('\\') && ch
!= wxT('/'))
268 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
269 wxStrcat (wxFileFunctionsBuffer
, filename
);
271 Unix2DosFilename (wxFileFunctionsBuffer
);
273 if (wxFileExists (wxFileFunctionsBuffer
))
275 return wxString(wxFileFunctionsBuffer
); // Found!
279 return wxString(wxT("")); // Not found
282 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
284 wxString f
= FindValidPath(file
);
285 if ( wxIsAbsolutePath(f
) )
289 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
291 if ( !wxEndsWithPathSeparator(buf
) )
293 buf
+= wxFILE_SEP_PATH
;
301 wxFileExists (const wxString
& filename
)
303 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
304 // GetFileAttributes can copy with network paths unlike stat()
305 DWORD ret
= ::GetFileAttributes(filename
);
307 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
310 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
318 wxIsAbsolutePath (const wxString
& filename
)
320 if (filename
!= wxT(""))
322 #if defined(__WXMAC__) && !defined(__DARWIN__)
323 // Classic or Carbon CodeWarrior like
324 // Carbon with Apple DevTools is Unix like
326 // This seems wrong to me, but there is no fix. since
327 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
328 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
329 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
332 // Unix like or Windows
333 if (filename
[0] == wxT('/'))
337 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
342 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
350 * Strip off any extension (dot something) from end of file,
351 * IF one exists. Inserts zero into buffer.
355 void wxStripExtension(wxChar
*buffer
)
357 int len
= wxStrlen(buffer
);
361 if (buffer
[i
] == wxT('.'))
370 void wxStripExtension(wxString
& buffer
)
372 size_t len
= buffer
.Length();
376 if (buffer
.GetChar(i
) == wxT('.'))
378 buffer
= buffer
.Left(i
);
385 // Destructive removal of /./ and /../ stuff
386 wxChar
*wxRealPath (wxChar
*path
)
389 static const wxChar SEP
= wxT('\\');
390 Unix2DosFilename(path
);
392 static const wxChar SEP
= wxT('/');
394 if (path
[0] && path
[1]) {
395 /* MATTHEW: special case "/./x" */
397 if (path
[2] == SEP
&& path
[1] == wxT('.'))
405 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
408 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
409 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
410 && (q
- 1 <= path
|| q
[-1] != SEP
))
413 if (path
[0] == wxT('\0'))
419 /* Check that path[2] is NULL! */
420 else if (path
[1] == wxT(':') && !path
[2])
429 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
438 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
440 if (filename
== wxT(""))
441 return (wxChar
*) NULL
;
443 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
444 wxChar buf
[_MAXPATHLEN
];
446 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
447 wxChar ch
= buf
[wxStrlen(buf
) - 1];
449 if (ch
!= wxT('\\') && ch
!= wxT('/'))
450 wxStrcat(buf
, wxT("\\"));
453 wxStrcat(buf
, wxT("/"));
455 wxStrcat(buf
, wxFileFunctionsBuffer
);
456 return copystring( wxRealPath(buf
) );
458 return copystring( wxFileFunctionsBuffer
);
464 ~user/ => user's home dir
465 If the environment variable a = "foo" and b = "bar" then:
482 /* input name in name, pathname output to buf. */
484 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
486 register wxChar
*d
, *s
, *nm
;
487 wxChar lnm
[_MAXPATHLEN
];
490 // Some compilers don't like this line.
491 // const wxChar trimchars[] = wxT("\n \t");
494 trimchars
[0] = wxT('\n');
495 trimchars
[1] = wxT(' ');
496 trimchars
[2] = wxT('\t');
500 const wxChar SEP
= wxT('\\');
502 const wxChar SEP
= wxT('/');
505 if (name
== NULL
|| *name
== wxT('\0'))
507 nm
= copystring(name
); // Make a scratch copy
510 /* Skip leading whitespace and cr */
511 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
513 /* And strip off trailing whitespace and cr */
514 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
515 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
523 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
526 /* Expand inline environment variables */
544 while ((*d
++ = *s
) != 0) {
546 if (*s
== wxT('\\')) {
547 if ((*(d
- 1) = *++s
)) {
556 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
558 if (*s
++ == wxT('$'))
561 register wxChar
*start
= d
;
562 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
563 register wxChar
*value
;
564 while ((*d
++ = *s
) != 0)
565 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
570 value
= wxGetenv(braces
? start
+ 1 : start
);
572 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
580 /* Expand ~ and ~user */
582 if (nm
[0] == wxT('~') && !q
)
585 if (nm
[1] == SEP
|| nm
[1] == 0)
587 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
588 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
593 { /* ~user/filename */
594 register wxChar
*nnm
;
595 register wxChar
*home
;
596 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
597 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
598 was_sep
= (*s
== SEP
);
599 nnm
= *s
? s
+ 1 : s
;
601 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
602 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
603 if (was_sep
) /* replace only if it was there: */
614 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
616 while (wxT('\0') != (*d
++ = *s
++))
619 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
623 while ((*d
++ = *s
++) != 0);
624 delete[] nm_tmp
; // clean up alloc
625 /* Now clean up the buffer */
626 return wxRealPath(buf
);
629 /* Contract Paths to be build upon an environment variable
632 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
634 The call wxExpandPath can convert these back!
637 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
639 static wxChar dest
[_MAXPATHLEN
];
641 if (filename
== wxT(""))
642 return (wxChar
*) NULL
;
644 wxStrcpy (dest
, WXSTRINGCAST filename
);
646 Unix2DosFilename(dest
);
649 // Handle environment
650 const wxChar
*val
= (const wxChar
*) NULL
;
651 wxChar
*tcp
= (wxChar
*) NULL
;
652 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
653 (tcp
= wxStrstr (dest
, val
)) != NULL
)
655 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
658 wxStrcpy (tcp
, WXSTRINGCAST envname
);
659 wxStrcat (tcp
, wxT("}"));
660 wxStrcat (tcp
, wxFileFunctionsBuffer
);
663 // Handle User's home (ignore root homes!)
665 if ((val
= wxGetUserHome (user
)) != NULL
&&
666 (len
= wxStrlen(val
)) > 2 &&
667 wxStrncmp(dest
, val
, len
) == 0)
669 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
671 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
673 // strcat(wxFileFunctionsBuffer, "\\");
675 // strcat(wxFileFunctionsBuffer, "/");
677 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
678 wxStrcpy (dest
, wxFileFunctionsBuffer
);
684 // Return just the filename, not the path
686 wxChar
*wxFileNameFromPath (wxChar
*path
)
690 register wxChar
*tcp
;
692 tcp
= path
+ wxStrlen (path
);
693 while (--tcp
>= path
)
695 #if defined(__WXMAC__) && !defined(__DARWIN__)
696 // Classic or Carbon CodeWarrior like
697 // Carbon with Apple DevTools is Unix like
698 if (*tcp
== wxT(':'))
701 // Unix like or Windows
702 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
706 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
710 #if defined(__WXMSW__) || defined(__WXPM__)
712 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
719 wxString
wxFileNameFromPath (const wxString
& path1
)
721 if (path1
!= wxT(""))
723 wxChar
*path
= WXSTRINGCAST path1
;
724 register wxChar
*tcp
;
726 tcp
= path
+ wxStrlen (path
);
727 while (--tcp
>= path
)
729 #if defined(__WXMAC__) && !defined(__DARWIN__)
730 // Classic or Carbon CodeWarrior like
731 // Carbon with Apple DevTools is Unix like
732 if (*tcp
== wxT(':') )
733 return wxString(tcp
+ 1);
735 // Unix like or Windows
736 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
737 return wxString(tcp
+ 1);
740 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
741 return wxString(tcp
+ 1);
744 #if defined(__WXMSW__) || defined(__WXPM__)
746 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
747 return wxString(path
+ 2);
750 // Yes, this should return the path, not an empty string, otherwise
751 // we get "thing.txt" -> "".
755 // Return just the directory, or NULL if no directory
757 wxPathOnly (wxChar
*path
)
761 static wxChar buf
[_MAXPATHLEN
];
764 wxStrcpy (buf
, path
);
766 int l
= wxStrlen(path
);
769 // Search backward for a backward or forward slash
772 #if defined(__WXMAC__) && !defined(__DARWIN__)
773 // Classic or Carbon CodeWarrior like
774 // Carbon with Apple DevTools is Unix like
775 if (path
[i
] == wxT(':') )
781 // Unix like or Windows
782 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
789 if (path
[i
] == wxT(']'))
798 #if defined(__WXMSW__) || defined(__WXPM__)
799 // Try Drive specifier
800 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
802 // A:junk --> A:. (since A:.\junk Not A:\junk)
809 return (wxChar
*) NULL
;
812 // Return just the directory, or NULL if no directory
813 wxString
wxPathOnly (const wxString
& path
)
817 wxChar buf
[_MAXPATHLEN
];
820 wxStrcpy (buf
, WXSTRINGCAST path
);
822 int l
= path
.Length();
825 // Search backward for a backward or forward slash
828 #if defined(__WXMAC__) && !defined(__DARWIN__)
829 // Classic or Carbon CodeWarrior like
830 // Carbon with Apple DevTools is Unix like
831 if (path
[i
] == wxT(':') )
834 return wxString(buf
);
837 // Unix like or Windows
838 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
841 return wxString(buf
);
845 if (path
[i
] == wxT(']'))
848 return wxString(buf
);
854 #if defined(__WXMSW__) || defined(__WXPM__)
855 // Try Drive specifier
856 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
858 // A:junk --> A:. (since A:.\junk Not A:\junk)
861 return wxString(buf
);
865 return wxString(wxT(""));
868 // Utility for converting delimiters in DOS filenames to UNIX style
869 // and back again - or we get nasty problems with delimiters.
870 // Also, convert to lower case, since case is significant in UNIX.
872 #if defined(__WXMAC__)
873 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
880 Boolean isDirectory
= false;
881 Str255 theParentPath
= "\p";
882 FSSpec theParentSpec
;
884 char theFileName
[FILENAME_MAX
];
885 char thePath
[FILENAME_MAX
];
889 // GD: Separate file name from path and make a FSRef to the parent
890 // directory. This is necessary since FSRefs cannot reference files
891 // that have not yet been created.
892 // Based on example code from Apple Technical Note TN2022
893 // http://developer.apple.com/technotes/tn/tn2022.html
895 // check whether we are converting a directory
896 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
897 // count length of file name
898 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
900 // prepend path separator since it will later be appended to the path
901 theFileName
[0] = wxFILE_SEP_PATH
;
902 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
903 theFileName
[j
- i
] = spec
->name
[j
];
905 theFileName
[j
- i
] = '\0';
907 for (j
= 1; j
<= i
; j
++) {
908 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
910 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
911 if (theErr
== noErr
) {
912 // convert the FSSpec to an FSRef
913 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
915 if (theErr
== noErr
) {
916 // get the POSIX path associated with the FSRef
917 theStatus
= FSRefMakePath(&theParentRef
,
918 (UInt8
*)thePath
, sizeof(thePath
));
920 if (theStatus
== noErr
) {
921 // append file name to path
922 // includes previously prepended path separator
923 strcat(thePath
, theFileName
);
926 // create path string for return value
927 wxString
result( thePath
) ;
932 // get length of path and allocate handle
933 FSpGetFullPath( spec
, &length
, &myPath
) ;
934 ::SetHandleSize( myPath
, length
+ 1 ) ;
936 (*myPath
)[length
] = 0 ;
937 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
938 (*myPath
)[length
-1] = 0 ;
940 // create path string for return value
941 wxString
result( (char*) *myPath
) ;
943 // free allocated handle
944 ::HUnlock( myPath
) ;
945 ::DisposeHandle( myPath
) ;
951 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
956 // get the FSRef associated with the POSIX path
957 (void) FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
958 // convert the FSRef to an FSSpec
959 (void) FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
961 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
966 // Mac file names are POSIX (Unix style) under Darwin
967 // therefore the conversion functions below are not needed
969 static char sMacFileNameConversion
[ 1000 ] ;
971 wxString
wxMac2UnixFilename (const char *str
)
973 char *s
= sMacFileNameConversion
;
977 memmove( s
+1 , s
,strlen( s
) + 1) ;
988 *s
= wxTolower(*s
); // Case INDEPENDENT
992 return wxString(sMacFileNameConversion
) ;
995 wxString
wxUnix2MacFilename (const char *str
)
997 char *s
= sMacFileNameConversion
;
1003 // relative path , since it goes on with slash which is translated to a :
1004 memmove( s
, s
+1 ,strlen( s
) ) ;
1006 else if ( *s
== '/' )
1008 // absolute path -> on mac just start with the drive name
1009 memmove( s
, s
+1 ,strlen( s
) ) ;
1013 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
1017 if (*s
== '/' || *s
== '\\')
1019 // convert any back-directory situations
1020 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
1023 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
1031 return wxString (sMacFileNameConversion
) ;
1034 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1036 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1039 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1041 wxString var
= wxUnix2MacFilename( path
) ;
1042 wxMacFilename2FSSpec( var
, spec
) ;
1044 #endif // ! __DARWIN__
1049 wxDos2UnixFilename (char *s
)
1058 *s
= wxTolower (*s
); // Case INDEPENDENT
1065 #if defined(__WXMSW__) || defined(__WXPM__)
1066 wxUnix2DosFilename (wxChar
*s
)
1068 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1071 // Yes, I really mean this to happen under DOS only! JACS
1072 #if defined(__WXMSW__) || defined(__WXPM__)
1083 // Concatenate two files to form third
1085 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1088 if ( !wxGetTempFileName("cat", outfile
) )
1091 FILE *fp1
= (FILE *) NULL
;
1092 FILE *fp2
= (FILE *) NULL
;
1093 FILE *fp3
= (FILE *) NULL
;
1094 // Open the inputs and outputs
1095 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
1096 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
1097 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
1109 while ((ch
= getc (fp1
)) != EOF
)
1110 (void) putc (ch
, fp3
);
1113 while ((ch
= getc (fp2
)) != EOF
)
1114 (void) putc (ch
, fp3
);
1118 bool result
= wxRenameFile(outfile
, file3
);
1124 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1126 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1127 // CopyFile() copies file attributes and modification time too, so use it
1128 // instead of our code if available
1130 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1131 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1133 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1134 file1
.c_str(), file2
.c_str());
1138 #elif defined(__WXPM__)
1139 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1144 // get permissions of file1
1145 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1147 // the file probably doesn't exist or we haven't the rights to read
1149 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1154 // open file1 for reading
1155 wxFile
fileIn(file1
, wxFile::read
);
1156 if ( !fileIn
.IsOpened() )
1159 // remove file2, if it exists. This is needed for creating
1160 // file2 with the correct permissions in the next step
1161 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1163 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1169 // reset the umask as we want to create the file with exactly the same
1170 // permissions as the original one
1171 mode_t oldUmask
= umask( 0 );
1174 // create file2 with the same permissions than file1 and open it for
1177 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1181 /// restore the old umask
1185 // copy contents of file1 to file2
1190 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1191 if ( fileIn
.Error() )
1198 if ( fileOut
.Write(buf
, count
) < count
)
1202 // we can expect fileIn to be closed successfully, but we should ensure
1203 // that fileOut was closed as some write errors (disk full) might not be
1204 // detected before doing this
1205 if ( !fileIn
.Close() || !fileOut
.Close() )
1208 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1209 // no chmod in VA. Should be some permission API for HPFS386 partitions
1211 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1213 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1217 #endif // OS/2 || Mac
1218 #endif // __WXMSW__ && __WIN32__
1224 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1226 // Normal system call
1227 if ( wxRename (file1
, file2
) == 0 )
1231 if (wxCopyFile(file1
, file2
)) {
1232 wxRemoveFile(file1
);
1239 bool wxRemoveFile(const wxString
& file
)
1241 #if defined(__VISUALC__) \
1242 || defined(__BORLANDC__) \
1243 || defined(__WATCOMC__) \
1244 || defined(__GNUWIN32__)
1245 int res
= wxRemove(file
);
1247 int res
= unlink(OS_FILENAME(file
));
1253 bool wxMkdir(const wxString
& dir
, int perm
)
1255 #if defined(__WXMAC__) && !defined(__UNIX__)
1256 return (mkdir( dir
, 0 ) == 0);
1258 const wxChar
*dirname
= dir
.c_str();
1260 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1261 // for the GNU compiler
1262 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1263 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1264 #elif defined(__WXPM__)
1265 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1266 #elif defined(__DOS__)
1267 #if defined(__WATCOMC__)
1269 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1270 #elif defined(__DJGPP__)
1271 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1273 #error "Unsupported DOS compiler!"
1275 #else // !MSW, !DOS and !OS/2 VAC++
1277 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1280 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1289 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1292 return FALSE
; //to be changed since rmdir exists in VMS7.x
1293 #elif defined(__WXPM__)
1294 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1298 return FALSE
; // What to do?
1300 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1306 // does the path exists? (may have or not '/' or '\\' at the end)
1307 bool wxPathExists(const wxChar
*pszPathName
)
1309 wxString
strPath(pszPathName
);
1312 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1313 // so remove all trailing backslashes from the path - but don't do this for
1314 // the pathes "d:\" (which are different from "d:") nor for just "\"
1315 while ( wxEndsWithPathSeparator(strPath
) )
1317 size_t len
= strPath
.length();
1318 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1321 strPath
.Truncate(len
- 1);
1323 #endif // __WINDOWS__
1325 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1326 // stat() can't cope with network paths
1327 DWORD ret
= ::GetFileAttributes(strPath
);
1329 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1333 #ifndef __VISAGECPP__
1334 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1335 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1337 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1338 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1339 (st
.st_mode
== S_IFDIR
);
1342 #endif // __WIN32__/!__WIN32__
1345 // Get a temporary filename, opening and closing the file.
1346 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1348 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1349 if ( filename
.empty() )
1353 wxStrcpy(buf
, filename
);
1355 buf
= copystring(filename
);
1360 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1362 buf
= wxFileName::CreateTempFileName(prefix
);
1364 return !buf
.empty();
1367 // Get first file name matching given wild card.
1369 static wxDir
*gs_dir
= NULL
;
1370 static wxString gs_dirPath
;
1372 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1374 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1375 if ( gs_dirPath
.IsEmpty() )
1376 gs_dirPath
= wxT(".");
1377 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1378 gs_dirPath
<< wxFILE_SEP_PATH
;
1382 gs_dir
= new wxDir(gs_dirPath
);
1384 if ( !gs_dir
->IsOpened() )
1386 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1387 return wxEmptyString
;
1393 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1394 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1395 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1399 gs_dir
->GetFirst(&result
, wxFileNameFromPath((wxChar
) spec
), dirFlags
);
1400 if ( result
.IsEmpty() )
1406 return gs_dirPath
+ result
;
1409 wxString
wxFindNextFile()
1411 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1414 gs_dir
->GetNext(&result
);
1416 if ( result
.IsEmpty() )
1422 return gs_dirPath
+ result
;
1426 // Get current working directory.
1427 // If buf is NULL, allocates space using new, else
1429 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1433 buf
= new wxChar
[sz
+ 1];
1438 // for the compilers which have Unicode version of _getcwd(), call it
1439 // directly, for the others call the ANSI version and do the translation
1442 #else // wxUSE_UNICODE
1443 bool needsANSI
= TRUE
;
1445 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1446 wxCharBuffer
c_buffer(sz
);
1447 char *cbuf
= (char*)(const char*)c_buffer
;
1451 #if wxUSE_UNICODE_MSLU
1452 if ( wxGetOsVersion() != wxWIN95
)
1454 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1457 ok
= _wgetcwd(buf
, sz
) != NULL
;
1463 #endif // wxUSE_UNICODE
1466 ok
= _getcwd(cbuf
, sz
) != NULL
;
1467 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1472 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1474 pb
.ioRefNum
= LMGetCurApRefNum();
1476 error
= PBGetFCBInfoSync(&pb
);
1477 if ( error
== noErr
)
1479 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1480 cwdSpec
.parID
= pb
.ioFCBParID
;
1481 cwdSpec
.name
[0] = 0 ;
1482 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1484 strcpy( cbuf
, res
) ;
1485 cbuf
[res
.length()]=0 ;
1493 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1495 rc
= ::DosQueryCurrentDir( 0 // current drive
1500 #else // !Win32/VC++ !Mac !OS2
1501 ok
= getcwd(cbuf
, sz
) != NULL
;
1505 // finally convert the result to Unicode if needed
1506 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1507 #endif // wxUSE_UNICODE
1512 wxLogSysError(_("Failed to get the working directory"));
1514 // VZ: the old code used to return "." on error which didn't make any
1515 // sense at all to me - empty string is a better error indicator
1516 // (NULL might be even better but I'm afraid this could lead to
1517 // problems with the old code assuming the return is never NULL)
1520 else // ok, but we might need to massage the path into the right format
1523 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1524 // with / deliminers. We don't like that.
1525 for (wxChar
*ch
= buf
; *ch
; ch
++)
1527 if (*ch
== wxT('/'))
1533 // another example of DOS/Unix mix (Cygwin)
1534 wxString pathUnix
= buf
;
1535 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1536 #endif // __CYGWIN__
1550 // we can't create wxStringBuffer object inline: Sun CC generates buggy
1551 // code in this case!
1553 wxStringBuffer
buf(str
, _MAXPATHLEN
);
1554 wxGetWorkingDirectory(buf
, _MAXPATHLEN
);
1560 bool wxSetWorkingDirectory(const wxString
& d
)
1562 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1563 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1564 #elif defined(__WXPM__)
1565 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1566 #elif defined(__WINDOWS__)
1569 return (bool)(SetCurrentDirectory(d
) != 0);
1571 // Must change drive, too.
1572 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1575 wxChar firstChar
= d
[0];
1579 firstChar
= firstChar
- 32;
1581 // To a drive number
1582 unsigned int driveNo
= firstChar
- 64;
1585 unsigned int noDrives
;
1586 _dos_setdrive(driveNo
, &noDrives
);
1589 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1597 // Get the OS directory if appropriate (such as the Windows directory).
1598 // On non-Windows platform, probably just return the empty string.
1599 wxString
wxGetOSDirectory()
1601 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1603 GetWindowsDirectory(buf
, 256);
1604 return wxString(buf
);
1606 return wxEmptyString
;
1610 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1612 size_t len
= wxStrlen(pszFileName
);
1614 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1617 // find a file in a list of directories, returns false if not found
1618 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1620 // we assume that it's not empty
1621 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1622 _T("empty file name in wxFindFileInPath"));
1624 // skip path separator in the beginning of the file name if present
1625 if ( wxIsPathSeparator(*pszFile
) )
1628 // copy the path (strtok will modify it)
1629 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1630 wxStrcpy(szPath
, pszPath
);
1633 wxChar
*pc
, *save_ptr
;
1634 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1636 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1638 // search for the file in this directory
1640 if ( !wxEndsWithPathSeparator(pc
) )
1641 strFile
+= wxFILE_SEP_PATH
;
1644 if ( FileExists(strFile
) ) {
1650 // suppress warning about unused variable save_ptr when wxStrtok() is a
1651 // macro which throws away its third argument
1656 return pc
!= NULL
; // if true => we breaked from the loop
1659 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1664 // it can be empty, but it shouldn't be NULL
1665 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1667 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1670 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1674 wxStat(filename
.fn_str(), &buf
);
1675 return buf
.st_mtime
;
1679 //------------------------------------------------------------------------
1680 // wild character routines
1681 //------------------------------------------------------------------------
1683 bool wxIsWild( const wxString
& pattern
)
1685 wxString tmp
= pattern
;
1686 wxChar
*pat
= WXSTRINGCAST(tmp
);
1689 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1699 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1703 // this probably won't work well for multibyte chars in Unicode mode?
1705 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1707 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1709 #else // !HAVE_FNMATCH
1711 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1714 * WARNING: this code is broken!
1717 wxString tmp1
= pat
;
1718 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1719 wxString tmp2
= text
;
1720 wxChar
*str
= WXSTRINGCAST(tmp2
);
1723 bool done
= FALSE
, ret_code
, ok
;
1724 // Below is for vi fans
1725 const wxChar OB
= wxT('{'), CB
= wxT('}');
1727 // dot_special means '.' only matches '.'
1728 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1731 while ((*pattern
!= wxT('\0')) && (!done
)
1732 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1736 if (*pattern
!= wxT('\0'))
1742 while ((*str
!=wxT('\0'))
1743 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1746 while (*str
!= wxT('\0'))
1748 while (*pattern
!= wxT('\0'))
1755 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1759 if (*pattern
== wxT('\\')) {
1761 if (*pattern
== wxT('\0')) {
1766 if (*(pattern
+ 1) == wxT('-')) {
1769 if (*pattern
== wxT(']')) {
1773 if (*pattern
== wxT('\\')) {
1775 if (*pattern
== wxT('\0')) {
1780 if ((*str
< c
) || (*str
> *pattern
)) {
1784 } else if (*pattern
!= *str
) {
1789 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1790 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1794 if (*pattern
!= wxT('\0')) {
1804 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1807 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1808 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1809 if (*pattern
== wxT('\\'))
1811 ok
= (*pattern
++ == *cp
++);
1813 if (*pattern
== wxT('\0')) {
1819 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1820 if (*++pattern
== wxT('\\')) {
1821 if (*++pattern
== CB
)
1826 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1827 if (*++pattern
== wxT('\\')) {
1828 if (*++pattern
== CB
|| *pattern
== wxT(','))
1833 if (*pattern
!= wxT('\0'))
1838 if (*str
== *pattern
) {
1845 while (*pattern
== wxT('*'))
1847 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1850 #endif // HAVE_FNMATCH/!HAVE_FNMATCH
1853 #pragma warning(default:4706) // assignment within conditional expression