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)
118 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
120 // note that it must be included after <windows.h>
122 #include <sys/cygwin.h>
125 #include <sys/unistd.h>
127 #endif // __GNUWIN32__
128 #endif // __WINDOWS__
130 // TODO: Borland probably has _wgetcwd as well?
135 // ----------------------------------------------------------------------------
137 // ----------------------------------------------------------------------------
140 #define _MAXPATHLEN 1024
143 extern wxChar
*wxBuffer
;
146 # include "MoreFiles.h"
147 # include "MoreFilesExtras.h"
148 # include "FullPath.h"
149 # include "FSpCompat.h"
152 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
158 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
160 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
162 // VisualAge C++ V4.0 cannot have any external linkage const decs
163 // in headers included by more than one primary source
165 const off_t wxInvalidOffset
= (off_t
)-1;
168 // ----------------------------------------------------------------------------
170 // ----------------------------------------------------------------------------
172 // we need to translate Mac filenames before passing them to OS functions
173 #define OS_FILENAME(s) (s.fn_str())
175 // ============================================================================
177 // ============================================================================
179 void wxPathList::Add (const wxString
& path
)
181 wxStringList::Add (WXSTRINGCAST path
);
184 // Add paths e.g. from the PATH environment variable
185 void wxPathList::AddEnvList (const wxString
& envVariable
)
187 static const wxChar PATH_TOKS
[] =
189 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
194 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
197 wxChar
*s
= copystring (val
);
198 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
202 Add (copystring (token
));
205 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
206 Add (wxString(token
));
210 // suppress warning about unused variable save_ptr when wxStrtok() is a
211 // macro which throws away its third argument
218 // Given a full filename (with path), ensure that that file can
219 // be accessed again USING FILENAME ONLY by adding the path
220 // to the list if not already there.
221 void wxPathList::EnsureFileAccessible (const wxString
& path
)
223 wxString
path_only(wxPathOnly(path
));
224 if ( !path_only
.IsEmpty() )
226 if ( !Member(path_only
) )
231 bool wxPathList::Member (const wxString
& path
)
233 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
235 wxString
path2((wxChar
*) node
->Data ());
237 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
239 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
241 // Case sensitive File System
242 path
.CompareTo (path2
) == 0
250 wxString
wxPathList::FindValidPath (const wxString
& file
)
252 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
253 return wxString(wxFileFunctionsBuffer
);
255 wxChar buf
[_MAXPATHLEN
];
256 wxStrcpy(buf
, wxFileFunctionsBuffer
);
258 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
259 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
261 for (wxNode
* node
= First (); node
; node
= node
->Next ())
263 wxChar
*path
= (wxChar
*) node
->Data ();
264 wxStrcpy (wxFileFunctionsBuffer
, path
);
265 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
266 if (ch
!= wxT('\\') && ch
!= wxT('/'))
267 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
268 wxStrcat (wxFileFunctionsBuffer
, filename
);
270 Unix2DosFilename (wxFileFunctionsBuffer
);
272 if (wxFileExists (wxFileFunctionsBuffer
))
274 return wxString(wxFileFunctionsBuffer
); // Found!
278 return wxString(wxT("")); // Not found
281 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
283 wxString f
= FindValidPath(file
);
284 if ( wxIsAbsolutePath(f
) )
288 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
290 if ( !wxEndsWithPathSeparator(buf
) )
292 buf
+= wxFILE_SEP_PATH
;
300 wxFileExists (const wxString
& filename
)
302 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
303 // GetFileAttributes can copy with network paths unlike stat()
304 DWORD ret
= ::GetFileAttributes(filename
);
305 if ( ret
== (DWORD
)-1 )
307 wxLogLastError(_T("GetFileAttributes"));
312 return !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
315 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
323 wxIsAbsolutePath (const wxString
& filename
)
325 if (filename
!= wxT(""))
327 #if defined(__WXMAC__) && !defined(__DARWIN__)
328 // Classic or Carbon CodeWarrior like
329 // Carbon with Apple DevTools is Unix like
331 // This seems wrong to me, but there is no fix. since
332 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
333 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
334 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
337 // Unix like or Windows
338 if (filename
[0] == wxT('/'))
342 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
347 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
355 * Strip off any extension (dot something) from end of file,
356 * IF one exists. Inserts zero into buffer.
360 void wxStripExtension(wxChar
*buffer
)
362 int len
= wxStrlen(buffer
);
366 if (buffer
[i
] == wxT('.'))
375 void wxStripExtension(wxString
& buffer
)
377 size_t len
= buffer
.Length();
381 if (buffer
.GetChar(i
) == wxT('.'))
383 buffer
= buffer
.Left(i
);
390 // Destructive removal of /./ and /../ stuff
391 wxChar
*wxRealPath (wxChar
*path
)
394 static const wxChar SEP
= wxT('\\');
395 Unix2DosFilename(path
);
397 static const wxChar SEP
= wxT('/');
399 if (path
[0] && path
[1]) {
400 /* MATTHEW: special case "/./x" */
402 if (path
[2] == SEP
&& path
[1] == wxT('.'))
410 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
413 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
414 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
415 && (q
- 1 <= path
|| q
[-1] != SEP
))
418 if (path
[0] == wxT('\0'))
424 /* Check that path[2] is NULL! */
425 else if (path
[1] == wxT(':') && !path
[2])
434 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
443 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
445 if (filename
== wxT(""))
446 return (wxChar
*) NULL
;
448 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
449 wxChar buf
[_MAXPATHLEN
];
451 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
452 wxChar ch
= buf
[wxStrlen(buf
) - 1];
454 if (ch
!= wxT('\\') && ch
!= wxT('/'))
455 wxStrcat(buf
, wxT("\\"));
458 wxStrcat(buf
, wxT("/"));
460 wxStrcat(buf
, wxFileFunctionsBuffer
);
461 return copystring( wxRealPath(buf
) );
463 return copystring( wxFileFunctionsBuffer
);
469 ~user/ => user's home dir
470 If the environment variable a = "foo" and b = "bar" then:
487 /* input name in name, pathname output to buf. */
489 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
491 register wxChar
*d
, *s
, *nm
;
492 wxChar lnm
[_MAXPATHLEN
];
495 // Some compilers don't like this line.
496 // const wxChar trimchars[] = wxT("\n \t");
499 trimchars
[0] = wxT('\n');
500 trimchars
[1] = wxT(' ');
501 trimchars
[2] = wxT('\t');
505 const wxChar SEP
= wxT('\\');
507 const wxChar SEP
= wxT('/');
510 if (name
== NULL
|| *name
== wxT('\0'))
512 nm
= copystring(name
); // Make a scratch copy
515 /* Skip leading whitespace and cr */
516 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
518 /* And strip off trailing whitespace and cr */
519 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
520 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
528 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
531 /* Expand inline environment variables */
549 while ((*d
++ = *s
) != 0) {
551 if (*s
== wxT('\\')) {
552 if ((*(d
- 1) = *++s
)) {
561 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
563 if (*s
++ == wxT('$'))
566 register wxChar
*start
= d
;
567 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
568 register wxChar
*value
;
569 while ((*d
++ = *s
) != 0)
570 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
575 value
= wxGetenv(braces
? start
+ 1 : start
);
577 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
585 /* Expand ~ and ~user */
587 if (nm
[0] == wxT('~') && !q
)
590 if (nm
[1] == SEP
|| nm
[1] == 0)
592 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
593 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
598 { /* ~user/filename */
599 register wxChar
*nnm
;
600 register wxChar
*home
;
601 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
602 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
603 was_sep
= (*s
== SEP
);
604 nnm
= *s
? s
+ 1 : s
;
606 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
607 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
608 if (was_sep
) /* replace only if it was there: */
619 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
621 while (wxT('\0') != (*d
++ = *s
++))
624 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
628 while ((*d
++ = *s
++) != 0);
629 delete[] nm_tmp
; // clean up alloc
630 /* Now clean up the buffer */
631 return wxRealPath(buf
);
634 /* Contract Paths to be build upon an environment variable
637 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
639 The call wxExpandPath can convert these back!
642 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
644 static wxChar dest
[_MAXPATHLEN
];
646 if (filename
== wxT(""))
647 return (wxChar
*) NULL
;
649 wxStrcpy (dest
, WXSTRINGCAST filename
);
651 Unix2DosFilename(dest
);
654 // Handle environment
655 const wxChar
*val
= (const wxChar
*) NULL
;
656 wxChar
*tcp
= (wxChar
*) NULL
;
657 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
658 (tcp
= wxStrstr (dest
, val
)) != NULL
)
660 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
663 wxStrcpy (tcp
, WXSTRINGCAST envname
);
664 wxStrcat (tcp
, wxT("}"));
665 wxStrcat (tcp
, wxFileFunctionsBuffer
);
668 // Handle User's home (ignore root homes!)
670 if ((val
= wxGetUserHome (user
)) != NULL
&&
671 (len
= wxStrlen(val
)) > 2 &&
672 wxStrncmp(dest
, val
, len
) == 0)
674 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
676 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
678 // strcat(wxFileFunctionsBuffer, "\\");
680 // strcat(wxFileFunctionsBuffer, "/");
682 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
683 wxStrcpy (dest
, wxFileFunctionsBuffer
);
689 // Return just the filename, not the path
691 wxChar
*wxFileNameFromPath (wxChar
*path
)
695 register wxChar
*tcp
;
697 tcp
= path
+ wxStrlen (path
);
698 while (--tcp
>= path
)
700 #if defined(__WXMAC__) && !defined(__DARWIN__)
701 // Classic or Carbon CodeWarrior like
702 // Carbon with Apple DevTools is Unix like
703 if (*tcp
== wxT(':'))
706 // Unix like or Windows
707 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
711 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
715 #if defined(__WXMSW__) || defined(__WXPM__)
717 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
724 wxString
wxFileNameFromPath (const wxString
& path1
)
726 if (path1
!= wxT(""))
728 wxChar
*path
= WXSTRINGCAST path1
;
729 register wxChar
*tcp
;
731 tcp
= path
+ wxStrlen (path
);
732 while (--tcp
>= path
)
734 #if defined(__WXMAC__) && !defined(__DARWIN__)
735 // Classic or Carbon CodeWarrior like
736 // Carbon with Apple DevTools is Unix like
737 if (*tcp
== wxT(':') )
738 return wxString(tcp
+ 1);
740 // Unix like or Windows
741 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
742 return wxString(tcp
+ 1);
745 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
746 return wxString(tcp
+ 1);
749 #if defined(__WXMSW__) || defined(__WXPM__)
751 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
752 return wxString(path
+ 2);
755 // Yes, this should return the path, not an empty string, otherwise
756 // we get "thing.txt" -> "".
760 // Return just the directory, or NULL if no directory
762 wxPathOnly (wxChar
*path
)
766 static wxChar buf
[_MAXPATHLEN
];
769 wxStrcpy (buf
, path
);
771 int l
= wxStrlen(path
);
774 // Search backward for a backward or forward slash
777 #if defined(__WXMAC__) && !defined(__DARWIN__)
778 // Classic or Carbon CodeWarrior like
779 // Carbon with Apple DevTools is Unix like
780 if (path
[i
] == wxT(':') )
786 // Unix like or Windows
787 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
794 if (path
[i
] == wxT(']'))
803 #if defined(__WXMSW__) || defined(__WXPM__)
804 // Try Drive specifier
805 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
807 // A:junk --> A:. (since A:.\junk Not A:\junk)
814 return (wxChar
*) NULL
;
817 // Return just the directory, or NULL if no directory
818 wxString
wxPathOnly (const wxString
& path
)
822 wxChar buf
[_MAXPATHLEN
];
825 wxStrcpy (buf
, WXSTRINGCAST path
);
827 int l
= path
.Length();
830 // Search backward for a backward or forward slash
833 #if defined(__WXMAC__) && !defined(__DARWIN__)
834 // Classic or Carbon CodeWarrior like
835 // Carbon with Apple DevTools is Unix like
836 if (path
[i
] == wxT(':') )
839 return wxString(buf
);
842 // Unix like or Windows
843 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
846 return wxString(buf
);
850 if (path
[i
] == wxT(']'))
853 return wxString(buf
);
859 #if defined(__WXMSW__) || defined(__WXPM__)
860 // Try Drive specifier
861 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
863 // A:junk --> A:. (since A:.\junk Not A:\junk)
866 return wxString(buf
);
870 return wxString(wxT(""));
873 // Utility for converting delimiters in DOS filenames to UNIX style
874 // and back again - or we get nasty problems with delimiters.
875 // Also, convert to lower case, since case is significant in UNIX.
877 #if defined(__WXMAC__)
878 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
882 char thePath
[FILENAME_MAX
];
884 // convert the FSSpec to an FSRef
885 (void) FSpMakeFSRef( spec
, &theRef
);
886 // get the POSIX path associated with the FSRef
887 (void) FSRefMakePath( &theRef
, (UInt8
*)thePath
, sizeof(thePath
) );
889 // create path string for return value
890 wxString
result( thePath
) ;
895 // get length of path and allocate handle
896 FSpGetFullPath( spec
, &length
, &myPath
) ;
897 ::SetHandleSize( myPath
, length
+ 1 ) ;
899 (*myPath
)[length
] = 0 ;
900 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
901 (*myPath
)[length
-1] = 0 ;
903 // create path string for return value
904 wxString
result( (char*) *myPath
) ;
906 // free allocated handle
907 ::HUnlock( myPath
) ;
908 ::DisposeHandle( myPath
) ;
914 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
919 // get the FSRef associated with the POSIX path
920 (void) FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
921 // convert the FSRef to an FSSpec
922 (void) FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
924 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
929 // Mac file names are POSIX (Unix style) under Darwin
930 // therefore the conversion functions below are not needed
932 static char sMacFileNameConversion
[ 1000 ] ;
934 wxString
wxMac2UnixFilename (const char *str
)
936 char *s
= sMacFileNameConversion
;
940 memmove( s
+1 , s
,strlen( s
) + 1) ;
951 *s
= wxTolower(*s
); // Case INDEPENDENT
955 return wxString(sMacFileNameConversion
) ;
958 wxString
wxUnix2MacFilename (const char *str
)
960 char *s
= sMacFileNameConversion
;
966 // relative path , since it goes on with slash which is translated to a :
967 memmove( s
, s
+1 ,strlen( s
) ) ;
969 else if ( *s
== '/' )
971 // absolute path -> on mac just start with the drive name
972 memmove( s
, s
+1 ,strlen( s
) ) ;
976 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
980 if (*s
== '/' || *s
== '\\')
982 // convert any back-directory situations
983 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
986 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
994 return wxString (sMacFileNameConversion
) ;
997 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
999 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1002 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1004 wxString var
= wxUnix2MacFilename( path
) ;
1005 wxMacFilename2FSSpec( var
, spec
) ;
1007 #endif // ! __DARWIN__
1012 wxDos2UnixFilename (char *s
)
1021 *s
= wxTolower (*s
); // Case INDEPENDENT
1028 #if defined(__WXMSW__) || defined(__WXPM__)
1029 wxUnix2DosFilename (wxChar
*s
)
1031 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1034 // Yes, I really mean this to happen under DOS only! JACS
1035 #if defined(__WXMSW__) || defined(__WXPM__)
1046 // Concatenate two files to form third
1048 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1051 if ( !wxGetTempFileName("cat", outfile
) )
1054 FILE *fp1
= (FILE *) NULL
;
1055 FILE *fp2
= (FILE *) NULL
;
1056 FILE *fp3
= (FILE *) NULL
;
1057 // Open the inputs and outputs
1058 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
1059 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
1060 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
1072 while ((ch
= getc (fp1
)) != EOF
)
1073 (void) putc (ch
, fp3
);
1076 while ((ch
= getc (fp2
)) != EOF
)
1077 (void) putc (ch
, fp3
);
1081 bool result
= wxRenameFile(outfile
, file3
);
1087 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1089 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1090 // CopyFile() copies file attributes and modification time too, so use it
1091 // instead of our code if available
1093 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1094 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1095 #elif defined(__WXPM__)
1096 if (::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) == 0)
1103 // get permissions of file1
1104 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1106 // the file probably doesn't exist or we haven't the rights to read
1108 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1113 // open file1 for reading
1114 wxFile
fileIn(file1
, wxFile::read
);
1115 if ( !fileIn
.IsOpened() )
1118 // remove file2, if it exists. This is needed for creating
1119 // file2 with the correct permissions in the next step
1120 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1122 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1128 // reset the umask as we want to create the file with exactly the same
1129 // permissions as the original one
1130 mode_t oldUmask
= umask( 0 );
1133 // create file2 with the same permissions than file1 and open it for
1136 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1140 /// restore the old umask
1144 // copy contents of file1 to file2
1149 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1150 if ( fileIn
.Error() )
1157 if ( fileOut
.Write(buf
, count
) < count
)
1161 // we can expect fileIn to be closed successfully, but we should ensure
1162 // that fileOut was closed as some write errors (disk full) might not be
1163 // detected before doing this
1164 if ( !fileIn
.Close() || !fileOut
.Close() )
1167 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1168 // no chmod in VA. Should be some permission API for HPFS386 partitions
1170 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1172 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1176 #endif // OS/2 || Mac
1179 #endif // __WXMSW__ && __WIN32__
1183 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1185 // Normal system call
1186 if ( wxRename (file1
, file2
) == 0 )
1190 if (wxCopyFile(file1
, file2
)) {
1191 wxRemoveFile(file1
);
1198 bool wxRemoveFile(const wxString
& file
)
1200 #if defined(__VISUALC__) \
1201 || defined(__BORLANDC__) \
1202 || defined(__WATCOMC__) \
1203 || defined(__GNUWIN32__)
1204 int res
= wxRemove(file
);
1206 int res
= unlink(OS_FILENAME(file
));
1212 bool wxMkdir(const wxString
& dir
, int perm
)
1214 #if defined(__WXMAC__) && !defined(__UNIX__)
1215 return (mkdir( dir
, 0 ) == 0);
1217 const wxChar
*dirname
= dir
.c_str();
1219 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1220 // for the GNU compiler
1221 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1222 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1223 #elif defined(__WXPM__)
1224 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1225 #elif defined(__DOS__)
1226 #if defined(__WATCOMC__)
1228 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1229 #elif defined(__DJGPP__)
1230 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1232 #error "Unsupported DOS compiler!"
1234 #else // !MSW, !DOS and !OS/2 VAC++
1236 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1239 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1248 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1251 return FALSE
; //to be changed since rmdir exists in VMS7.x
1252 #elif defined(__WXPM__)
1253 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1257 return FALSE
; // What to do?
1259 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1265 // does the path exists? (may have or not '/' or '\\' at the end)
1266 bool wxPathExists(const wxChar
*pszPathName
)
1268 wxString
strPath(pszPathName
);
1271 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1272 // so remove all trailing backslashes from the path - but don't do this for
1273 // the pathes "d:\" (which are different from "d:") nor for just "\"
1274 while ( wxEndsWithPathSeparator(strPath
) )
1276 size_t len
= strPath
.length();
1277 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1280 strPath
.Truncate(len
- 1);
1282 #endif // __WINDOWS__
1284 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1285 // stat() can't cope with network paths
1286 DWORD ret
= ::GetFileAttributes(strPath
);
1287 if ( ret
== (DWORD
)-1 )
1289 wxLogLastError(_T("GetFileAttributes"));
1294 return (ret
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
1298 #ifndef __VISAGECPP__
1299 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1300 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1302 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1303 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1304 (st
.st_mode
== S_IFDIR
);
1307 #endif // __WIN32__/!__WIN32__
1310 // Get a temporary filename, opening and closing the file.
1311 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1313 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1314 if ( filename
.empty() )
1318 wxStrcpy(buf
, filename
);
1320 buf
= copystring(filename
);
1325 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1327 buf
= wxFileName::CreateTempFileName(prefix
);
1329 return !buf
.empty();
1332 // Get first file name matching given wild card.
1334 static wxDir
*gs_dir
= NULL
;
1335 static wxString gs_dirPath
;
1337 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1339 gs_dirPath
= wxPathOnly(spec
);
1340 if ( gs_dirPath
.IsEmpty() )
1341 gs_dirPath
= wxT(".");
1342 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1343 gs_dirPath
<< wxFILE_SEP_PATH
;
1347 gs_dir
= new wxDir(gs_dirPath
);
1349 if ( !gs_dir
->IsOpened() )
1351 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1352 return wxEmptyString
;
1358 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1359 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1360 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1364 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1365 if ( result
.IsEmpty() )
1371 return gs_dirPath
+ result
;
1374 wxString
wxFindNextFile()
1376 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1379 gs_dir
->GetNext(&result
);
1381 if ( result
.IsEmpty() )
1387 return gs_dirPath
+ result
;
1391 // Get current working directory.
1392 // If buf is NULL, allocates space using new, else
1394 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1398 buf
= new wxChar
[sz
+ 1];
1403 // for the compilers which have Unicode version of _getcwd(), call it
1404 // directly, for the others call the ANSI version and do the translation
1407 ok
= _wgetcwd(buf
, sz
) != NULL
;
1408 #else // !HAVE_WGETCWD
1409 wxCharBuffer
cbuf(sz
);
1413 #if !wxUSE_UNICODE || !defined(HAVE_WGETCWD)
1415 ok
= _getcwd(buf
, sz
) != NULL
;
1416 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1421 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1423 pb
.ioRefNum
= LMGetCurApRefNum();
1425 error
= PBGetFCBInfoSync(&pb
);
1426 if ( error
== noErr
)
1428 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1429 cwdSpec
.parID
= pb
.ioFCBParID
;
1430 cwdSpec
.name
[0] = 0 ;
1431 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1433 strcpy( buf
, res
) ;
1434 buf
[res
.length()]=0 ;
1442 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1444 rc
= ::DosQueryCurrentDir( 0 // current drive
1449 #else // !Win32/VC++ !Mac !OS2
1450 ok
= getcwd(buf
, sz
) != NULL
;
1452 #endif // !wxUSE_UNICODE || !HAVE_WGETCWD
1456 wxLogSysError(_("Failed to get the working directory"));
1458 // VZ: the old code used to return "." on error which didn't make any
1459 // sense at all to me - empty string is a better error indicator
1460 // (NULL might be even better but I'm afraid this could lead to
1461 // problems with the old code assuming the return is never NULL)
1464 else // ok, but we might need to massage the path into the right format
1467 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1468 // with / deliminers. We don't like that.
1469 for (wxChar
*ch
= buf
; *ch
; ch
++)
1471 if (*ch
== wxT('/'))
1477 // another example of DOS/Unix mix (Cygwin)
1478 wxString pathUnix
= buf
;
1479 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1480 #endif // __GNUWIN32__
1482 // finally convert the result to Unicode if needed
1483 #if wxUSE_UNICODE && !defined(HAVE_WGETCWD)
1484 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1485 #endif // wxUSE_UNICODE
1495 // we can't create wxStringBuffer object inline: Sun CC generates buggy
1496 // code in this case!
1498 wxStringBuffer
buf(str
, _MAXPATHLEN
);
1499 wxGetWorkingDirectory(buf
, _MAXPATHLEN
);
1505 bool wxSetWorkingDirectory(const wxString
& d
)
1507 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1508 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1509 #elif defined(__WXPM__)
1510 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1511 #elif defined(__WINDOWS__)
1514 return (bool)(SetCurrentDirectory(d
) != 0);
1516 // Must change drive, too.
1517 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1520 wxChar firstChar
= d
[0];
1524 firstChar
= firstChar
- 32;
1526 // To a drive number
1527 unsigned int driveNo
= firstChar
- 64;
1530 unsigned int noDrives
;
1531 _dos_setdrive(driveNo
, &noDrives
);
1534 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1542 // Get the OS directory if appropriate (such as the Windows directory).
1543 // On non-Windows platform, probably just return the empty string.
1544 wxString
wxGetOSDirectory()
1546 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1548 GetWindowsDirectory(buf
, 256);
1549 return wxString(buf
);
1551 return wxEmptyString
;
1555 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1557 size_t len
= wxStrlen(pszFileName
);
1559 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1562 // find a file in a list of directories, returns false if not found
1563 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1565 // we assume that it's not empty
1566 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1567 _T("empty file name in wxFindFileInPath"));
1569 // skip path separator in the beginning of the file name if present
1570 if ( wxIsPathSeparator(*pszFile
) )
1573 // copy the path (strtok will modify it)
1574 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1575 wxStrcpy(szPath
, pszPath
);
1578 wxChar
*pc
, *save_ptr
;
1579 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1581 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1583 // search for the file in this directory
1585 if ( !wxEndsWithPathSeparator(pc
) )
1586 strFile
+= wxFILE_SEP_PATH
;
1589 if ( FileExists(strFile
) ) {
1595 // suppress warning about unused variable save_ptr when wxStrtok() is a
1596 // macro which throws away its third argument
1601 return pc
!= NULL
; // if true => we breaked from the loop
1604 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1609 // it can be empty, but it shouldn't be NULL
1610 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1612 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1615 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1619 wxStat(filename
.fn_str(), &buf
);
1620 return buf
.st_mtime
;
1624 //------------------------------------------------------------------------
1625 // wild character routines
1626 //------------------------------------------------------------------------
1628 bool wxIsWild( const wxString
& pattern
)
1630 wxString tmp
= pattern
;
1631 wxChar
*pat
= WXSTRINGCAST(tmp
);
1634 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1644 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1646 #if defined(HAVE_FNMATCH_H)
1648 // this probably won't work well for multibyte chars in Unicode mode?
1650 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1652 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1656 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1659 * WARNING: this code is broken!
1662 wxString tmp1
= pat
;
1663 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1664 wxString tmp2
= text
;
1665 wxChar
*str
= WXSTRINGCAST(tmp2
);
1668 bool done
= FALSE
, ret_code
, ok
;
1669 // Below is for vi fans
1670 const wxChar OB
= wxT('{'), CB
= wxT('}');
1672 // dot_special means '.' only matches '.'
1673 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1676 while ((*pattern
!= wxT('\0')) && (!done
)
1677 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1681 if (*pattern
!= wxT('\0'))
1687 while ((*str
!=wxT('\0'))
1688 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1691 while (*str
!= wxT('\0'))
1693 while (*pattern
!= wxT('\0'))
1700 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1704 if (*pattern
== wxT('\\')) {
1706 if (*pattern
== wxT('\0')) {
1711 if (*(pattern
+ 1) == wxT('-')) {
1714 if (*pattern
== wxT(']')) {
1718 if (*pattern
== wxT('\\')) {
1720 if (*pattern
== wxT('\0')) {
1725 if ((*str
< c
) || (*str
> *pattern
)) {
1729 } else if (*pattern
!= *str
) {
1734 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1735 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1739 if (*pattern
!= wxT('\0')) {
1749 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1752 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1753 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1754 if (*pattern
== wxT('\\'))
1756 ok
= (*pattern
++ == *cp
++);
1758 if (*pattern
== wxT('\0')) {
1764 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1765 if (*++pattern
== wxT('\\')) {
1766 if (*++pattern
== CB
)
1771 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1772 if (*++pattern
== wxT('\\')) {
1773 if (*++pattern
== CB
|| *pattern
== wxT(','))
1778 if (*pattern
!= wxT('\0'))
1783 if (*str
== *pattern
) {
1790 while (*pattern
== wxT('*'))
1792 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1798 #pragma warning(default:4706) // assignment within conditional expression
1801 //------------------------------------------------------------------------
1802 // Missing functions in Unicode for Win9x
1803 //------------------------------------------------------------------------
1805 // NB: MSLU only covers Win32 API, it doesn't provide Unicode implementation of
1806 // libc functions. Unfortunately, some of MSVCRT wchar_t functions
1807 // (e.g. _wopen) don't work on Windows 9x, so we have to workaround it
1808 // by calling the char version. We still want to use wchar_t version on
1809 // NT/2000/XP, though, because they allow for Unicode file names.
1810 #if wxUSE_UNICODE_MSLU
1812 #if defined( __VISUALC__ ) \
1813 || ( defined(__MINGW32__) && wxCHECK_W32API_VERSION( 0, 5 ) ) \
1814 || ( defined(__MWERKS__) && defined(__WXMSW__) )
1815 WXDLLEXPORT
int wxOpen(const wxChar
*name
, int flags
, int mode
)
1817 if ( wxGetOsVersion() == wxWINDOWS_NT
)
1818 return _wopen(name
, flags
, mode
);
1820 return _open(wxConvFile
.cWX2MB(name
), flags
, mode
);
1824 #endif // wxUSE_UNICODE_MSLU