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>
123 #include <sys/cygwin.h>
127 #include <sys/unistd.h>
129 #endif // __GNUWIN32__
130 #endif // __WINDOWS__
132 // TODO: Borland probably has _wgetcwd as well?
137 // ----------------------------------------------------------------------------
139 // ----------------------------------------------------------------------------
142 #define _MAXPATHLEN 1024
145 extern wxChar
*wxBuffer
;
148 # include "MoreFiles.h"
149 # include "MoreFilesExtras.h"
150 # include "FullPath.h"
151 # include "FSpCompat.h"
154 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
156 // ----------------------------------------------------------------------------
158 // ----------------------------------------------------------------------------
160 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
162 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
164 // VisualAge C++ V4.0 cannot have any external linkage const decs
165 // in headers included by more than one primary source
167 const off_t wxInvalidOffset
= (off_t
)-1;
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 // we need to translate Mac filenames before passing them to OS functions
175 #define OS_FILENAME(s) (s.fn_str())
177 // ============================================================================
179 // ============================================================================
181 void wxPathList::Add (const wxString
& path
)
183 wxStringList::Add (WXSTRINGCAST path
);
186 // Add paths e.g. from the PATH environment variable
187 void wxPathList::AddEnvList (const wxString
& envVariable
)
189 static const wxChar PATH_TOKS
[] =
191 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
196 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
199 wxChar
*s
= copystring (val
);
200 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
204 Add (copystring (token
));
207 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
208 Add (wxString(token
));
212 // suppress warning about unused variable save_ptr when wxStrtok() is a
213 // macro which throws away its third argument
220 // Given a full filename (with path), ensure that that file can
221 // be accessed again USING FILENAME ONLY by adding the path
222 // to the list if not already there.
223 void wxPathList::EnsureFileAccessible (const wxString
& path
)
225 wxString
path_only(wxPathOnly(path
));
226 if ( !path_only
.IsEmpty() )
228 if ( !Member(path_only
) )
233 bool wxPathList::Member (const wxString
& path
)
235 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
237 wxString
path2((wxChar
*) node
->Data ());
239 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
241 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
243 // Case sensitive File System
244 path
.CompareTo (path2
) == 0
252 wxString
wxPathList::FindValidPath (const wxString
& file
)
254 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
255 return wxString(wxFileFunctionsBuffer
);
257 wxChar buf
[_MAXPATHLEN
];
258 wxStrcpy(buf
, wxFileFunctionsBuffer
);
260 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
261 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
263 for (wxNode
* node
= First (); node
; node
= node
->Next ())
265 wxChar
*path
= (wxChar
*) node
->Data ();
266 wxStrcpy (wxFileFunctionsBuffer
, path
);
267 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
268 if (ch
!= wxT('\\') && ch
!= wxT('/'))
269 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
270 wxStrcat (wxFileFunctionsBuffer
, filename
);
272 Unix2DosFilename (wxFileFunctionsBuffer
);
274 if (wxFileExists (wxFileFunctionsBuffer
))
276 return wxString(wxFileFunctionsBuffer
); // Found!
280 return wxString(wxT("")); // Not found
283 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
285 wxString f
= FindValidPath(file
);
286 if ( wxIsAbsolutePath(f
) )
290 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
292 if ( !wxEndsWithPathSeparator(buf
) )
294 buf
+= wxFILE_SEP_PATH
;
302 wxFileExists (const wxString
& filename
)
304 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
305 // GetFileAttributes can copy with network paths unlike stat()
306 DWORD ret
= ::GetFileAttributes(filename
);
308 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
311 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
319 wxIsAbsolutePath (const wxString
& filename
)
321 if (filename
!= wxT(""))
323 #if defined(__WXMAC__) && !defined(__DARWIN__)
324 // Classic or Carbon CodeWarrior like
325 // Carbon with Apple DevTools is Unix like
327 // This seems wrong to me, but there is no fix. since
328 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
329 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
330 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
333 // Unix like or Windows
334 if (filename
[0] == wxT('/'))
338 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
343 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
351 * Strip off any extension (dot something) from end of file,
352 * IF one exists. Inserts zero into buffer.
356 void wxStripExtension(wxChar
*buffer
)
358 int len
= wxStrlen(buffer
);
362 if (buffer
[i
] == wxT('.'))
371 void wxStripExtension(wxString
& buffer
)
373 size_t len
= buffer
.Length();
377 if (buffer
.GetChar(i
) == wxT('.'))
379 buffer
= buffer
.Left(i
);
386 // Destructive removal of /./ and /../ stuff
387 wxChar
*wxRealPath (wxChar
*path
)
390 static const wxChar SEP
= wxT('\\');
391 Unix2DosFilename(path
);
393 static const wxChar SEP
= wxT('/');
395 if (path
[0] && path
[1]) {
396 /* MATTHEW: special case "/./x" */
398 if (path
[2] == SEP
&& path
[1] == wxT('.'))
406 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
409 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
410 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
411 && (q
- 1 <= path
|| q
[-1] != SEP
))
414 if (path
[0] == wxT('\0'))
420 /* Check that path[2] is NULL! */
421 else if (path
[1] == wxT(':') && !path
[2])
430 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
439 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
441 if (filename
== wxT(""))
442 return (wxChar
*) NULL
;
444 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
445 wxChar buf
[_MAXPATHLEN
];
447 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
448 wxChar ch
= buf
[wxStrlen(buf
) - 1];
450 if (ch
!= wxT('\\') && ch
!= wxT('/'))
451 wxStrcat(buf
, wxT("\\"));
454 wxStrcat(buf
, wxT("/"));
456 wxStrcat(buf
, wxFileFunctionsBuffer
);
457 return copystring( wxRealPath(buf
) );
459 return copystring( wxFileFunctionsBuffer
);
465 ~user/ => user's home dir
466 If the environment variable a = "foo" and b = "bar" then:
483 /* input name in name, pathname output to buf. */
485 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
487 register wxChar
*d
, *s
, *nm
;
488 wxChar lnm
[_MAXPATHLEN
];
491 // Some compilers don't like this line.
492 // const wxChar trimchars[] = wxT("\n \t");
495 trimchars
[0] = wxT('\n');
496 trimchars
[1] = wxT(' ');
497 trimchars
[2] = wxT('\t');
501 const wxChar SEP
= wxT('\\');
503 const wxChar SEP
= wxT('/');
506 if (name
== NULL
|| *name
== wxT('\0'))
508 nm
= copystring(name
); // Make a scratch copy
511 /* Skip leading whitespace and cr */
512 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
514 /* And strip off trailing whitespace and cr */
515 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
516 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
524 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
527 /* Expand inline environment variables */
545 while ((*d
++ = *s
) != 0) {
547 if (*s
== wxT('\\')) {
548 if ((*(d
- 1) = *++s
)) {
557 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
559 if (*s
++ == wxT('$'))
562 register wxChar
*start
= d
;
563 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
564 register wxChar
*value
;
565 while ((*d
++ = *s
) != 0)
566 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
571 value
= wxGetenv(braces
? start
+ 1 : start
);
573 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
581 /* Expand ~ and ~user */
583 if (nm
[0] == wxT('~') && !q
)
586 if (nm
[1] == SEP
|| nm
[1] == 0)
588 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
589 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
594 { /* ~user/filename */
595 register wxChar
*nnm
;
596 register wxChar
*home
;
597 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
598 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
599 was_sep
= (*s
== SEP
);
600 nnm
= *s
? s
+ 1 : s
;
602 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
603 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
604 if (was_sep
) /* replace only if it was there: */
615 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
617 while (wxT('\0') != (*d
++ = *s
++))
620 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
624 while ((*d
++ = *s
++) != 0);
625 delete[] nm_tmp
; // clean up alloc
626 /* Now clean up the buffer */
627 return wxRealPath(buf
);
630 /* Contract Paths to be build upon an environment variable
633 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
635 The call wxExpandPath can convert these back!
638 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
640 static wxChar dest
[_MAXPATHLEN
];
642 if (filename
== wxT(""))
643 return (wxChar
*) NULL
;
645 wxStrcpy (dest
, WXSTRINGCAST filename
);
647 Unix2DosFilename(dest
);
650 // Handle environment
651 const wxChar
*val
= (const wxChar
*) NULL
;
652 wxChar
*tcp
= (wxChar
*) NULL
;
653 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
654 (tcp
= wxStrstr (dest
, val
)) != NULL
)
656 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
659 wxStrcpy (tcp
, WXSTRINGCAST envname
);
660 wxStrcat (tcp
, wxT("}"));
661 wxStrcat (tcp
, wxFileFunctionsBuffer
);
664 // Handle User's home (ignore root homes!)
666 if ((val
= wxGetUserHome (user
)) != NULL
&&
667 (len
= wxStrlen(val
)) > 2 &&
668 wxStrncmp(dest
, val
, len
) == 0)
670 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
672 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
674 // strcat(wxFileFunctionsBuffer, "\\");
676 // strcat(wxFileFunctionsBuffer, "/");
678 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
679 wxStrcpy (dest
, wxFileFunctionsBuffer
);
685 // Return just the filename, not the path
687 wxChar
*wxFileNameFromPath (wxChar
*path
)
691 register wxChar
*tcp
;
693 tcp
= path
+ wxStrlen (path
);
694 while (--tcp
>= path
)
696 #if defined(__WXMAC__) && !defined(__DARWIN__)
697 // Classic or Carbon CodeWarrior like
698 // Carbon with Apple DevTools is Unix like
699 if (*tcp
== wxT(':'))
702 // Unix like or Windows
703 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
707 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
711 #if defined(__WXMSW__) || defined(__WXPM__)
713 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
720 wxString
wxFileNameFromPath (const wxString
& path1
)
722 if (path1
!= wxT(""))
724 wxChar
*path
= WXSTRINGCAST path1
;
725 register wxChar
*tcp
;
727 tcp
= path
+ wxStrlen (path
);
728 while (--tcp
>= path
)
730 #if defined(__WXMAC__) && !defined(__DARWIN__)
731 // Classic or Carbon CodeWarrior like
732 // Carbon with Apple DevTools is Unix like
733 if (*tcp
== wxT(':') )
734 return wxString(tcp
+ 1);
736 // Unix like or Windows
737 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
738 return wxString(tcp
+ 1);
741 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
742 return wxString(tcp
+ 1);
745 #if defined(__WXMSW__) || defined(__WXPM__)
747 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
748 return wxString(path
+ 2);
751 // Yes, this should return the path, not an empty string, otherwise
752 // we get "thing.txt" -> "".
756 // Return just the directory, or NULL if no directory
758 wxPathOnly (wxChar
*path
)
762 static wxChar buf
[_MAXPATHLEN
];
765 wxStrcpy (buf
, path
);
767 int l
= wxStrlen(path
);
770 // Search backward for a backward or forward slash
773 #if defined(__WXMAC__) && !defined(__DARWIN__)
774 // Classic or Carbon CodeWarrior like
775 // Carbon with Apple DevTools is Unix like
776 if (path
[i
] == wxT(':') )
782 // Unix like or Windows
783 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
790 if (path
[i
] == wxT(']'))
799 #if defined(__WXMSW__) || defined(__WXPM__)
800 // Try Drive specifier
801 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
803 // A:junk --> A:. (since A:.\junk Not A:\junk)
810 return (wxChar
*) NULL
;
813 // Return just the directory, or NULL if no directory
814 wxString
wxPathOnly (const wxString
& path
)
818 wxChar buf
[_MAXPATHLEN
];
821 wxStrcpy (buf
, WXSTRINGCAST path
);
823 int l
= path
.Length();
826 // Search backward for a backward or forward slash
829 #if defined(__WXMAC__) && !defined(__DARWIN__)
830 // Classic or Carbon CodeWarrior like
831 // Carbon with Apple DevTools is Unix like
832 if (path
[i
] == wxT(':') )
835 return wxString(buf
);
838 // Unix like or Windows
839 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
842 return wxString(buf
);
846 if (path
[i
] == wxT(']'))
849 return wxString(buf
);
855 #if defined(__WXMSW__) || defined(__WXPM__)
856 // Try Drive specifier
857 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
859 // A:junk --> A:. (since A:.\junk Not A:\junk)
862 return wxString(buf
);
866 return wxString(wxT(""));
869 // Utility for converting delimiters in DOS filenames to UNIX style
870 // and back again - or we get nasty problems with delimiters.
871 // Also, convert to lower case, since case is significant in UNIX.
873 #if defined(__WXMAC__)
874 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
878 char thePath
[FILENAME_MAX
];
880 // convert the FSSpec to an FSRef
881 (void) FSpMakeFSRef( spec
, &theRef
);
882 // get the POSIX path associated with the FSRef
883 (void) FSRefMakePath( &theRef
, (UInt8
*)thePath
, sizeof(thePath
) );
885 // create path string for return value
886 wxString
result( thePath
) ;
891 // get length of path and allocate handle
892 FSpGetFullPath( spec
, &length
, &myPath
) ;
893 ::SetHandleSize( myPath
, length
+ 1 ) ;
895 (*myPath
)[length
] = 0 ;
896 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
897 (*myPath
)[length
-1] = 0 ;
899 // create path string for return value
900 wxString
result( (char*) *myPath
) ;
902 // free allocated handle
903 ::HUnlock( myPath
) ;
904 ::DisposeHandle( myPath
) ;
910 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
915 // get the FSRef associated with the POSIX path
916 (void) FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
917 // convert the FSRef to an FSSpec
918 (void) FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
920 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
925 // Mac file names are POSIX (Unix style) under Darwin
926 // therefore the conversion functions below are not needed
928 static char sMacFileNameConversion
[ 1000 ] ;
930 wxString
wxMac2UnixFilename (const char *str
)
932 char *s
= sMacFileNameConversion
;
936 memmove( s
+1 , s
,strlen( s
) + 1) ;
947 *s
= wxTolower(*s
); // Case INDEPENDENT
951 return wxString(sMacFileNameConversion
) ;
954 wxString
wxUnix2MacFilename (const char *str
)
956 char *s
= sMacFileNameConversion
;
962 // relative path , since it goes on with slash which is translated to a :
963 memmove( s
, s
+1 ,strlen( s
) ) ;
965 else if ( *s
== '/' )
967 // absolute path -> on mac just start with the drive name
968 memmove( s
, s
+1 ,strlen( s
) ) ;
972 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
976 if (*s
== '/' || *s
== '\\')
978 // convert any back-directory situations
979 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
982 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
990 return wxString (sMacFileNameConversion
) ;
993 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
995 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
998 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1000 wxString var
= wxUnix2MacFilename( path
) ;
1001 wxMacFilename2FSSpec( var
, spec
) ;
1003 #endif // ! __DARWIN__
1008 wxDos2UnixFilename (char *s
)
1017 *s
= wxTolower (*s
); // Case INDEPENDENT
1024 #if defined(__WXMSW__) || defined(__WXPM__)
1025 wxUnix2DosFilename (wxChar
*s
)
1027 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1030 // Yes, I really mean this to happen under DOS only! JACS
1031 #if defined(__WXMSW__) || defined(__WXPM__)
1042 // Concatenate two files to form third
1044 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1047 if ( !wxGetTempFileName("cat", outfile
) )
1050 FILE *fp1
= (FILE *) NULL
;
1051 FILE *fp2
= (FILE *) NULL
;
1052 FILE *fp3
= (FILE *) NULL
;
1053 // Open the inputs and outputs
1054 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
1055 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
1056 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
1068 while ((ch
= getc (fp1
)) != EOF
)
1069 (void) putc (ch
, fp3
);
1072 while ((ch
= getc (fp2
)) != EOF
)
1073 (void) putc (ch
, fp3
);
1077 bool result
= wxRenameFile(outfile
, file3
);
1083 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1085 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1086 // CopyFile() copies file attributes and modification time too, so use it
1087 // instead of our code if available
1089 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1090 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1091 #elif defined(__WXPM__)
1092 if (::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) == 0)
1099 // get permissions of file1
1100 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1102 // the file probably doesn't exist or we haven't the rights to read
1104 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1109 // open file1 for reading
1110 wxFile
fileIn(file1
, wxFile::read
);
1111 if ( !fileIn
.IsOpened() )
1114 // remove file2, if it exists. This is needed for creating
1115 // file2 with the correct permissions in the next step
1116 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1118 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1124 // reset the umask as we want to create the file with exactly the same
1125 // permissions as the original one
1126 mode_t oldUmask
= umask( 0 );
1129 // create file2 with the same permissions than file1 and open it for
1132 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1136 /// restore the old umask
1140 // copy contents of file1 to file2
1145 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1146 if ( fileIn
.Error() )
1153 if ( fileOut
.Write(buf
, count
) < count
)
1157 // we can expect fileIn to be closed successfully, but we should ensure
1158 // that fileOut was closed as some write errors (disk full) might not be
1159 // detected before doing this
1160 if ( !fileIn
.Close() || !fileOut
.Close() )
1163 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1164 // no chmod in VA. Should be some permission API for HPFS386 partitions
1166 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1168 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1172 #endif // OS/2 || Mac
1175 #endif // __WXMSW__ && __WIN32__
1179 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1181 // Normal system call
1182 if ( wxRename (file1
, file2
) == 0 )
1186 if (wxCopyFile(file1
, file2
)) {
1187 wxRemoveFile(file1
);
1194 bool wxRemoveFile(const wxString
& file
)
1196 #if defined(__VISUALC__) \
1197 || defined(__BORLANDC__) \
1198 || defined(__WATCOMC__) \
1199 || defined(__GNUWIN32__)
1200 int res
= wxRemove(file
);
1202 int res
= unlink(OS_FILENAME(file
));
1208 bool wxMkdir(const wxString
& dir
, int perm
)
1210 #if defined(__WXMAC__) && !defined(__UNIX__)
1211 return (mkdir( dir
, 0 ) == 0);
1213 const wxChar
*dirname
= dir
.c_str();
1215 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1216 // for the GNU compiler
1217 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1218 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1219 #elif defined(__WXPM__)
1220 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1221 #elif defined(__DOS__)
1222 #if defined(__WATCOMC__)
1224 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1225 #elif defined(__DJGPP__)
1226 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1228 #error "Unsupported DOS compiler!"
1230 #else // !MSW, !DOS and !OS/2 VAC++
1232 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1235 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1244 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1247 return FALSE
; //to be changed since rmdir exists in VMS7.x
1248 #elif defined(__WXPM__)
1249 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1253 return FALSE
; // What to do?
1255 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1261 // does the path exists? (may have or not '/' or '\\' at the end)
1262 bool wxPathExists(const wxChar
*pszPathName
)
1264 wxString
strPath(pszPathName
);
1267 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1268 // so remove all trailing backslashes from the path - but don't do this for
1269 // the pathes "d:\" (which are different from "d:") nor for just "\"
1270 while ( wxEndsWithPathSeparator(strPath
) )
1272 size_t len
= strPath
.length();
1273 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1276 strPath
.Truncate(len
- 1);
1278 #endif // __WINDOWS__
1280 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1281 // stat() can't cope with network paths
1282 DWORD ret
= ::GetFileAttributes(strPath
);
1284 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1288 #ifndef __VISAGECPP__
1289 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1290 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1292 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1293 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1294 (st
.st_mode
== S_IFDIR
);
1297 #endif // __WIN32__/!__WIN32__
1300 // Get a temporary filename, opening and closing the file.
1301 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1303 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1304 if ( filename
.empty() )
1308 wxStrcpy(buf
, filename
);
1310 buf
= copystring(filename
);
1315 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1317 buf
= wxFileName::CreateTempFileName(prefix
);
1319 return !buf
.empty();
1322 // Get first file name matching given wild card.
1324 static wxDir
*gs_dir
= NULL
;
1325 static wxString gs_dirPath
;
1327 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1329 gs_dirPath
= wxPathOnly(spec
);
1330 if ( gs_dirPath
.IsEmpty() )
1331 gs_dirPath
= wxT(".");
1332 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1333 gs_dirPath
<< wxFILE_SEP_PATH
;
1337 gs_dir
= new wxDir(gs_dirPath
);
1339 if ( !gs_dir
->IsOpened() )
1341 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1342 return wxEmptyString
;
1348 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1349 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1350 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1354 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1355 if ( result
.IsEmpty() )
1361 return gs_dirPath
+ result
;
1364 wxString
wxFindNextFile()
1366 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1369 gs_dir
->GetNext(&result
);
1371 if ( result
.IsEmpty() )
1377 return gs_dirPath
+ result
;
1381 // Get current working directory.
1382 // If buf is NULL, allocates space using new, else
1384 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1388 buf
= new wxChar
[sz
+ 1];
1393 // for the compilers which have Unicode version of _getcwd(), call it
1394 // directly, for the others call the ANSI version and do the translation
1397 ok
= _wgetcwd(buf
, sz
) != NULL
;
1398 #else // !HAVE_WGETCWD
1399 wxCharBuffer
cbuf(sz
);
1403 #if !wxUSE_UNICODE || !defined(HAVE_WGETCWD)
1405 ok
= _getcwd(buf
, sz
) != NULL
;
1406 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1411 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1413 pb
.ioRefNum
= LMGetCurApRefNum();
1415 error
= PBGetFCBInfoSync(&pb
);
1416 if ( error
== noErr
)
1418 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1419 cwdSpec
.parID
= pb
.ioFCBParID
;
1420 cwdSpec
.name
[0] = 0 ;
1421 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1423 strcpy( buf
, res
) ;
1424 buf
[res
.length()]=0 ;
1432 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1434 rc
= ::DosQueryCurrentDir( 0 // current drive
1439 #else // !Win32/VC++ !Mac !OS2
1440 ok
= getcwd(buf
, sz
) != NULL
;
1442 #endif // !wxUSE_UNICODE || !HAVE_WGETCWD
1446 wxLogSysError(_("Failed to get the working directory"));
1448 // VZ: the old code used to return "." on error which didn't make any
1449 // sense at all to me - empty string is a better error indicator
1450 // (NULL might be even better but I'm afraid this could lead to
1451 // problems with the old code assuming the return is never NULL)
1454 else // ok, but we might need to massage the path into the right format
1457 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1458 // with / deliminers. We don't like that.
1459 for (wxChar
*ch
= buf
; *ch
; ch
++)
1461 if (*ch
== wxT('/'))
1467 // another example of DOS/Unix mix (Cygwin)
1468 wxString pathUnix
= buf
;
1469 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1470 #endif // __CYGWIN__
1472 // finally convert the result to Unicode if needed
1473 #if wxUSE_UNICODE && !defined(HAVE_WGETCWD)
1474 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1475 #endif // wxUSE_UNICODE
1485 // we can't create wxStringBuffer object inline: Sun CC generates buggy
1486 // code in this case!
1488 wxStringBuffer
buf(str
, _MAXPATHLEN
);
1489 wxGetWorkingDirectory(buf
, _MAXPATHLEN
);
1495 bool wxSetWorkingDirectory(const wxString
& d
)
1497 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1498 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1499 #elif defined(__WXPM__)
1500 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1501 #elif defined(__WINDOWS__)
1504 return (bool)(SetCurrentDirectory(d
) != 0);
1506 // Must change drive, too.
1507 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1510 wxChar firstChar
= d
[0];
1514 firstChar
= firstChar
- 32;
1516 // To a drive number
1517 unsigned int driveNo
= firstChar
- 64;
1520 unsigned int noDrives
;
1521 _dos_setdrive(driveNo
, &noDrives
);
1524 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1532 // Get the OS directory if appropriate (such as the Windows directory).
1533 // On non-Windows platform, probably just return the empty string.
1534 wxString
wxGetOSDirectory()
1536 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1538 GetWindowsDirectory(buf
, 256);
1539 return wxString(buf
);
1541 return wxEmptyString
;
1545 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1547 size_t len
= wxStrlen(pszFileName
);
1549 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1552 // find a file in a list of directories, returns false if not found
1553 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1555 // we assume that it's not empty
1556 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1557 _T("empty file name in wxFindFileInPath"));
1559 // skip path separator in the beginning of the file name if present
1560 if ( wxIsPathSeparator(*pszFile
) )
1563 // copy the path (strtok will modify it)
1564 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1565 wxStrcpy(szPath
, pszPath
);
1568 wxChar
*pc
, *save_ptr
;
1569 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1571 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1573 // search for the file in this directory
1575 if ( !wxEndsWithPathSeparator(pc
) )
1576 strFile
+= wxFILE_SEP_PATH
;
1579 if ( FileExists(strFile
) ) {
1585 // suppress warning about unused variable save_ptr when wxStrtok() is a
1586 // macro which throws away its third argument
1591 return pc
!= NULL
; // if true => we breaked from the loop
1594 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1599 // it can be empty, but it shouldn't be NULL
1600 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1602 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1605 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1609 wxStat(filename
.fn_str(), &buf
);
1610 return buf
.st_mtime
;
1614 //------------------------------------------------------------------------
1615 // wild character routines
1616 //------------------------------------------------------------------------
1618 bool wxIsWild( const wxString
& pattern
)
1620 wxString tmp
= pattern
;
1621 wxChar
*pat
= WXSTRINGCAST(tmp
);
1624 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1634 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1636 #if defined(HAVE_FNMATCH_H)
1638 // this probably won't work well for multibyte chars in Unicode mode?
1640 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1642 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1646 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1649 * WARNING: this code is broken!
1652 wxString tmp1
= pat
;
1653 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1654 wxString tmp2
= text
;
1655 wxChar
*str
= WXSTRINGCAST(tmp2
);
1658 bool done
= FALSE
, ret_code
, ok
;
1659 // Below is for vi fans
1660 const wxChar OB
= wxT('{'), CB
= wxT('}');
1662 // dot_special means '.' only matches '.'
1663 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1666 while ((*pattern
!= wxT('\0')) && (!done
)
1667 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1671 if (*pattern
!= wxT('\0'))
1677 while ((*str
!=wxT('\0'))
1678 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1681 while (*str
!= wxT('\0'))
1683 while (*pattern
!= wxT('\0'))
1690 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1694 if (*pattern
== wxT('\\')) {
1696 if (*pattern
== wxT('\0')) {
1701 if (*(pattern
+ 1) == wxT('-')) {
1704 if (*pattern
== wxT(']')) {
1708 if (*pattern
== wxT('\\')) {
1710 if (*pattern
== wxT('\0')) {
1715 if ((*str
< c
) || (*str
> *pattern
)) {
1719 } else if (*pattern
!= *str
) {
1724 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1725 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1729 if (*pattern
!= wxT('\0')) {
1739 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1742 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1743 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1744 if (*pattern
== wxT('\\'))
1746 ok
= (*pattern
++ == *cp
++);
1748 if (*pattern
== wxT('\0')) {
1754 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1755 if (*++pattern
== wxT('\\')) {
1756 if (*++pattern
== CB
)
1761 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1762 if (*++pattern
== wxT('\\')) {
1763 if (*++pattern
== CB
|| *pattern
== wxT(','))
1768 if (*pattern
!= wxT('\0'))
1773 if (*str
== *pattern
) {
1780 while (*pattern
== wxT('*'))
1782 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1788 #pragma warning(default:4706) // assignment within conditional expression
1791 //------------------------------------------------------------------------
1792 // Missing functions in Unicode for Win9x
1793 //------------------------------------------------------------------------
1795 // NB: MSLU only covers Win32 API, it doesn't provide Unicode implementation of
1796 // libc functions. Unfortunately, some of MSVCRT wchar_t functions
1797 // (e.g. _wopen) don't work on Windows 9x, so we have to workaround it
1798 // by calling the char version. We still want to use wchar_t version on
1799 // NT/2000/XP, though, because they allow for Unicode file names.
1800 #if wxUSE_UNICODE_MSLU
1802 #if defined( __VISUALC__ ) \
1803 || ( defined(__MINGW32__) && wxCHECK_W32API_VERSION( 0, 5 ) ) \
1804 || ( defined(__MWERKS__) && defined(__WXMSW__) )
1805 WXDLLEXPORT
int wxOpen(const wxChar
*name
, int flags
, int mode
)
1807 if ( wxGetOsVersion() == wxWINDOWS_NT
)
1808 return _wopen(name
, flags
, mode
);
1810 return _open(wxConvFile
.cWX2MB(name
), flags
, mode
);
1814 #endif // wxUSE_UNICODE_MSLU