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
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
);
1270 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1271 // so remove all trailing backslashes from the path - but don't do this for
1272 // the pathes "d:\" (which are different from "d:") nor for just "\"
1273 while ( wxEndsWithPathSeparator(strPath
) )
1275 size_t len
= strPath
.length();
1276 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1279 strPath
.Truncate(len
- 1);
1281 #endif // __WINDOWS__
1283 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1284 // Stat can't cope with network paths
1285 DWORD ret
= ::GetFileAttributes(filename
);
1286 if ( ret
== (DWORD
)-1 )
1288 wxLogLastError(_T("GetFileAttributes"));
1293 return (ret
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
1297 #ifndef __VISAGECPP__
1298 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1299 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1301 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1302 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1303 (st
.st_mode
== S_IFDIR
);
1309 // Get a temporary filename, opening and closing the file.
1310 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1312 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1313 if ( filename
.empty() )
1317 wxStrcpy(buf
, filename
);
1319 buf
= copystring(filename
);
1324 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1326 buf
= wxFileName::CreateTempFileName(prefix
);
1328 return !buf
.empty();
1331 // Get first file name matching given wild card.
1333 static wxDir
*gs_dir
= NULL
;
1334 static wxString gs_dirPath
;
1336 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1338 gs_dirPath
= wxPathOnly(spec
);
1339 if ( gs_dirPath
.IsEmpty() )
1340 gs_dirPath
= wxT(".");
1341 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1342 gs_dirPath
<< wxFILE_SEP_PATH
;
1346 gs_dir
= new wxDir(gs_dirPath
);
1348 if ( !gs_dir
->IsOpened() )
1350 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1351 return wxEmptyString
;
1357 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1358 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1359 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1363 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1364 if ( result
.IsEmpty() )
1370 return gs_dirPath
+ result
;
1373 wxString
wxFindNextFile()
1375 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1378 gs_dir
->GetNext(&result
);
1380 if ( result
.IsEmpty() )
1386 return gs_dirPath
+ result
;
1390 // Get current working directory.
1391 // If buf is NULL, allocates space using new, else
1393 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1397 buf
= new wxChar
[sz
+ 1];
1402 // for the compilers which have Unicode version of _getcwd(), call it
1403 // directly, for the others call the ANSI version and do the translation
1406 ok
= _wgetcwd(buf
, sz
) != NULL
;
1407 #else // !HAVE_WGETCWD
1408 wxCharBuffer
cbuf(sz
);
1412 #if !wxUSE_UNICODE || !defined(HAVE_WGETCWD)
1414 ok
= _getcwd(buf
, sz
) != NULL
;
1415 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1420 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1422 pb
.ioRefNum
= LMGetCurApRefNum();
1424 error
= PBGetFCBInfoSync(&pb
);
1425 if ( error
== noErr
)
1427 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1428 cwdSpec
.parID
= pb
.ioFCBParID
;
1429 cwdSpec
.name
[0] = 0 ;
1430 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1432 strcpy( buf
, res
) ;
1433 buf
[res
.length()]=0 ;
1441 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1443 rc
= ::DosQueryCurrentDir( 0 // current drive
1448 #else // !Win32/VC++ !Mac !OS2
1449 ok
= getcwd(buf
, sz
) != NULL
;
1451 #endif // !wxUSE_UNICODE || !HAVE_WGETCWD
1455 wxLogSysError(_("Failed to get the working directory"));
1457 // VZ: the old code used to return "." on error which didn't make any
1458 // sense at all to me - empty string is a better error indicator
1459 // (NULL might be even better but I'm afraid this could lead to
1460 // problems with the old code assuming the return is never NULL)
1463 else // ok, but we might need to massage the path into the right format
1466 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1467 // with / deliminers. We don't like that.
1468 for (wxChar
*ch
= buf
; *ch
; ch
++)
1470 if (*ch
== wxT('/'))
1476 // another example of DOS/Unix mix (Cygwin)
1477 wxString pathUnix
= buf
;
1478 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1479 #endif // __GNUWIN32__
1481 // finally convert the result to Unicode if needed
1482 #if wxUSE_UNICODE && !defined(HAVE_WGETCWD)
1483 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1484 #endif // wxUSE_UNICODE
1494 // we can't create wxStringBuffer object inline: Sun CC generates buggy
1495 // code in this case!
1497 wxStringBuffer
buf(str
, _MAXPATHLEN
);
1498 wxGetWorkingDirectory(buf
, _MAXPATHLEN
);
1504 bool wxSetWorkingDirectory(const wxString
& d
)
1506 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1507 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1508 #elif defined(__WXPM__)
1509 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1510 #elif defined(__WINDOWS__)
1513 return (bool)(SetCurrentDirectory(d
) != 0);
1515 // Must change drive, too.
1516 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1519 wxChar firstChar
= d
[0];
1523 firstChar
= firstChar
- 32;
1525 // To a drive number
1526 unsigned int driveNo
= firstChar
- 64;
1529 unsigned int noDrives
;
1530 _dos_setdrive(driveNo
, &noDrives
);
1533 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1541 // Get the OS directory if appropriate (such as the Windows directory).
1542 // On non-Windows platform, probably just return the empty string.
1543 wxString
wxGetOSDirectory()
1545 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1547 GetWindowsDirectory(buf
, 256);
1548 return wxString(buf
);
1550 return wxEmptyString
;
1554 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1556 size_t len
= wxStrlen(pszFileName
);
1558 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1561 // find a file in a list of directories, returns false if not found
1562 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1564 // we assume that it's not empty
1565 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1566 _T("empty file name in wxFindFileInPath"));
1568 // skip path separator in the beginning of the file name if present
1569 if ( wxIsPathSeparator(*pszFile
) )
1572 // copy the path (strtok will modify it)
1573 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1574 wxStrcpy(szPath
, pszPath
);
1577 wxChar
*pc
, *save_ptr
;
1578 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1580 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1582 // search for the file in this directory
1584 if ( !wxEndsWithPathSeparator(pc
) )
1585 strFile
+= wxFILE_SEP_PATH
;
1588 if ( FileExists(strFile
) ) {
1594 // suppress warning about unused variable save_ptr when wxStrtok() is a
1595 // macro which throws away its third argument
1600 return pc
!= NULL
; // if true => we breaked from the loop
1603 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1608 // it can be empty, but it shouldn't be NULL
1609 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1611 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1614 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1618 wxStat(filename
.fn_str(), &buf
);
1619 return buf
.st_mtime
;
1623 //------------------------------------------------------------------------
1624 // wild character routines
1625 //------------------------------------------------------------------------
1627 bool wxIsWild( const wxString
& pattern
)
1629 wxString tmp
= pattern
;
1630 wxChar
*pat
= WXSTRINGCAST(tmp
);
1633 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1643 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1645 #if defined(HAVE_FNMATCH_H)
1647 // this probably won't work well for multibyte chars in Unicode mode?
1649 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1651 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1655 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1658 * WARNING: this code is broken!
1661 wxString tmp1
= pat
;
1662 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1663 wxString tmp2
= text
;
1664 wxChar
*str
= WXSTRINGCAST(tmp2
);
1667 bool done
= FALSE
, ret_code
, ok
;
1668 // Below is for vi fans
1669 const wxChar OB
= wxT('{'), CB
= wxT('}');
1671 // dot_special means '.' only matches '.'
1672 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1675 while ((*pattern
!= wxT('\0')) && (!done
)
1676 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1680 if (*pattern
!= wxT('\0'))
1686 while ((*str
!=wxT('\0'))
1687 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1690 while (*str
!= wxT('\0'))
1692 while (*pattern
!= wxT('\0'))
1699 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1703 if (*pattern
== wxT('\\')) {
1705 if (*pattern
== wxT('\0')) {
1710 if (*(pattern
+ 1) == wxT('-')) {
1713 if (*pattern
== wxT(']')) {
1717 if (*pattern
== wxT('\\')) {
1719 if (*pattern
== wxT('\0')) {
1724 if ((*str
< c
) || (*str
> *pattern
)) {
1728 } else if (*pattern
!= *str
) {
1733 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1734 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1738 if (*pattern
!= wxT('\0')) {
1748 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1751 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1752 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1753 if (*pattern
== wxT('\\'))
1755 ok
= (*pattern
++ == *cp
++);
1757 if (*pattern
== wxT('\0')) {
1763 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1764 if (*++pattern
== wxT('\\')) {
1765 if (*++pattern
== CB
)
1770 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1771 if (*++pattern
== wxT('\\')) {
1772 if (*++pattern
== CB
|| *pattern
== wxT(','))
1777 if (*pattern
!= wxT('\0'))
1782 if (*str
== *pattern
) {
1789 while (*pattern
== wxT('*'))
1791 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1797 #pragma warning(default:4706) // assignment within conditional expression
1800 //------------------------------------------------------------------------
1801 // Missing functions in Unicode for Win9x
1802 //------------------------------------------------------------------------
1804 // NB: MSLU only covers Win32 API, it doesn't provide Unicode implementation of
1805 // libc functions. Unfortunately, some of MSVCRT wchar_t functions
1806 // (e.g. _wopen) don't work on Windows 9x, so we have to workaround it
1807 // by calling the char version. We still want to use wchar_t version on
1808 // NT/2000/XP, though, because they allow for Unicode file names.
1809 #if wxUSE_UNICODE_MSLU
1811 #if defined( __VISUALC__ ) \
1812 || ( defined(__MINGW32__) && wxCHECK_W32API_VERSION( 0, 5 ) ) \
1813 || ( defined(__MWERKS__) && defined(__WXMSW__) )
1814 WXDLLEXPORT
int wxOpen(const wxChar
*name
, int flags
, int mode
)
1816 if ( wxGetOsVersion() == wxWINDOWS_NT
)
1817 return _wopen(name
, flags
, mode
);
1819 return _open(wxConvFile
.cWX2MB(name
), flags
, mode
);
1823 #endif // wxUSE_UNICODE_MSLU