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
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
);
306 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
309 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
317 wxIsAbsolutePath (const wxString
& filename
)
319 if (filename
!= wxT(""))
321 #if defined(__WXMAC__) && !defined(__DARWIN__)
322 // Classic or Carbon CodeWarrior like
323 // Carbon with Apple DevTools is Unix like
325 // This seems wrong to me, but there is no fix. since
326 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
327 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
328 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
331 // Unix like or Windows
332 if (filename
[0] == wxT('/'))
336 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
341 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
349 * Strip off any extension (dot something) from end of file,
350 * IF one exists. Inserts zero into buffer.
354 void wxStripExtension(wxChar
*buffer
)
356 int len
= wxStrlen(buffer
);
360 if (buffer
[i
] == wxT('.'))
369 void wxStripExtension(wxString
& buffer
)
371 size_t len
= buffer
.Length();
375 if (buffer
.GetChar(i
) == wxT('.'))
377 buffer
= buffer
.Left(i
);
384 // Destructive removal of /./ and /../ stuff
385 wxChar
*wxRealPath (wxChar
*path
)
388 static const wxChar SEP
= wxT('\\');
389 Unix2DosFilename(path
);
391 static const wxChar SEP
= wxT('/');
393 if (path
[0] && path
[1]) {
394 /* MATTHEW: special case "/./x" */
396 if (path
[2] == SEP
&& path
[1] == wxT('.'))
404 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
407 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
408 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
409 && (q
- 1 <= path
|| q
[-1] != SEP
))
412 if (path
[0] == wxT('\0'))
418 /* Check that path[2] is NULL! */
419 else if (path
[1] == wxT(':') && !path
[2])
428 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
437 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
439 if (filename
== wxT(""))
440 return (wxChar
*) NULL
;
442 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
443 wxChar buf
[_MAXPATHLEN
];
445 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
446 wxChar ch
= buf
[wxStrlen(buf
) - 1];
448 if (ch
!= wxT('\\') && ch
!= wxT('/'))
449 wxStrcat(buf
, wxT("\\"));
452 wxStrcat(buf
, wxT("/"));
454 wxStrcat(buf
, wxFileFunctionsBuffer
);
455 return copystring( wxRealPath(buf
) );
457 return copystring( wxFileFunctionsBuffer
);
463 ~user/ => user's home dir
464 If the environment variable a = "foo" and b = "bar" then:
481 /* input name in name, pathname output to buf. */
483 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
485 register wxChar
*d
, *s
, *nm
;
486 wxChar lnm
[_MAXPATHLEN
];
489 // Some compilers don't like this line.
490 // const wxChar trimchars[] = wxT("\n \t");
493 trimchars
[0] = wxT('\n');
494 trimchars
[1] = wxT(' ');
495 trimchars
[2] = wxT('\t');
499 const wxChar SEP
= wxT('\\');
501 const wxChar SEP
= wxT('/');
504 if (name
== NULL
|| *name
== wxT('\0'))
506 nm
= copystring(name
); // Make a scratch copy
509 /* Skip leading whitespace and cr */
510 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
512 /* And strip off trailing whitespace and cr */
513 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
514 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
522 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
525 /* Expand inline environment variables */
543 while ((*d
++ = *s
) != 0) {
545 if (*s
== wxT('\\')) {
546 if ((*(d
- 1) = *++s
)) {
555 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
557 if (*s
++ == wxT('$'))
560 register wxChar
*start
= d
;
561 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
562 register wxChar
*value
;
563 while ((*d
++ = *s
) != 0)
564 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
569 value
= wxGetenv(braces
? start
+ 1 : start
);
571 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
579 /* Expand ~ and ~user */
581 if (nm
[0] == wxT('~') && !q
)
584 if (nm
[1] == SEP
|| nm
[1] == 0)
586 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
587 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
592 { /* ~user/filename */
593 register wxChar
*nnm
;
594 register wxChar
*home
;
595 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
596 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
597 was_sep
= (*s
== SEP
);
598 nnm
= *s
? s
+ 1 : s
;
600 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
601 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
602 if (was_sep
) /* replace only if it was there: */
613 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
615 while (wxT('\0') != (*d
++ = *s
++))
618 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
622 while ((*d
++ = *s
++) != 0);
623 delete[] nm_tmp
; // clean up alloc
624 /* Now clean up the buffer */
625 return wxRealPath(buf
);
628 /* Contract Paths to be build upon an environment variable
631 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
633 The call wxExpandPath can convert these back!
636 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
638 static wxChar dest
[_MAXPATHLEN
];
640 if (filename
== wxT(""))
641 return (wxChar
*) NULL
;
643 wxStrcpy (dest
, WXSTRINGCAST filename
);
645 Unix2DosFilename(dest
);
648 // Handle environment
649 const wxChar
*val
= (const wxChar
*) NULL
;
650 wxChar
*tcp
= (wxChar
*) NULL
;
651 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
652 (tcp
= wxStrstr (dest
, val
)) != NULL
)
654 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
657 wxStrcpy (tcp
, WXSTRINGCAST envname
);
658 wxStrcat (tcp
, wxT("}"));
659 wxStrcat (tcp
, wxFileFunctionsBuffer
);
662 // Handle User's home (ignore root homes!)
664 if ((val
= wxGetUserHome (user
)) != NULL
&&
665 (len
= wxStrlen(val
)) > 2 &&
666 wxStrncmp(dest
, val
, len
) == 0)
668 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
670 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
672 // strcat(wxFileFunctionsBuffer, "\\");
674 // strcat(wxFileFunctionsBuffer, "/");
676 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
677 wxStrcpy (dest
, wxFileFunctionsBuffer
);
683 // Return just the filename, not the path
685 wxChar
*wxFileNameFromPath (wxChar
*path
)
689 register wxChar
*tcp
;
691 tcp
= path
+ wxStrlen (path
);
692 while (--tcp
>= path
)
694 #if defined(__WXMAC__) && !defined(__DARWIN__)
695 // Classic or Carbon CodeWarrior like
696 // Carbon with Apple DevTools is Unix like
697 if (*tcp
== wxT(':'))
700 // Unix like or Windows
701 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
705 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
709 #if defined(__WXMSW__) || defined(__WXPM__)
711 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
718 wxString
wxFileNameFromPath (const wxString
& path1
)
720 if (path1
!= wxT(""))
722 wxChar
*path
= WXSTRINGCAST path1
;
723 register wxChar
*tcp
;
725 tcp
= path
+ wxStrlen (path
);
726 while (--tcp
>= path
)
728 #if defined(__WXMAC__) && !defined(__DARWIN__)
729 // Classic or Carbon CodeWarrior like
730 // Carbon with Apple DevTools is Unix like
731 if (*tcp
== wxT(':') )
732 return wxString(tcp
+ 1);
734 // Unix like or Windows
735 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
736 return wxString(tcp
+ 1);
739 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
740 return wxString(tcp
+ 1);
743 #if defined(__WXMSW__) || defined(__WXPM__)
745 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
746 return wxString(path
+ 2);
749 // Yes, this should return the path, not an empty string, otherwise
750 // we get "thing.txt" -> "".
754 // Return just the directory, or NULL if no directory
756 wxPathOnly (wxChar
*path
)
760 static wxChar buf
[_MAXPATHLEN
];
763 wxStrcpy (buf
, path
);
765 int l
= wxStrlen(path
);
768 // Search backward for a backward or forward slash
771 #if defined(__WXMAC__) && !defined(__DARWIN__)
772 // Classic or Carbon CodeWarrior like
773 // Carbon with Apple DevTools is Unix like
774 if (path
[i
] == wxT(':') )
780 // Unix like or Windows
781 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
788 if (path
[i
] == wxT(']'))
797 #if defined(__WXMSW__) || defined(__WXPM__)
798 // Try Drive specifier
799 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
801 // A:junk --> A:. (since A:.\junk Not A:\junk)
808 return (wxChar
*) NULL
;
811 // Return just the directory, or NULL if no directory
812 wxString
wxPathOnly (const wxString
& path
)
816 wxChar buf
[_MAXPATHLEN
];
819 wxStrcpy (buf
, WXSTRINGCAST path
);
821 int l
= path
.Length();
824 // Search backward for a backward or forward slash
827 #if defined(__WXMAC__) && !defined(__DARWIN__)
828 // Classic or Carbon CodeWarrior like
829 // Carbon with Apple DevTools is Unix like
830 if (path
[i
] == wxT(':') )
833 return wxString(buf
);
836 // Unix like or Windows
837 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
840 return wxString(buf
);
844 if (path
[i
] == wxT(']'))
847 return wxString(buf
);
853 #if defined(__WXMSW__) || defined(__WXPM__)
854 // Try Drive specifier
855 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
857 // A:junk --> A:. (since A:.\junk Not A:\junk)
860 return wxString(buf
);
864 return wxString(wxT(""));
867 // Utility for converting delimiters in DOS filenames to UNIX style
868 // and back again - or we get nasty problems with delimiters.
869 // Also, convert to lower case, since case is significant in UNIX.
871 #if defined(__WXMAC__)
872 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
876 char thePath
[FILENAME_MAX
];
878 // convert the FSSpec to an FSRef
879 (void) FSpMakeFSRef( spec
, &theRef
);
880 // get the POSIX path associated with the FSRef
881 (void) FSRefMakePath( &theRef
, (UInt8
*)thePath
, sizeof(thePath
) );
883 // create path string for return value
884 wxString
result( thePath
) ;
889 // get length of path and allocate handle
890 FSpGetFullPath( spec
, &length
, &myPath
) ;
891 ::SetHandleSize( myPath
, length
+ 1 ) ;
893 (*myPath
)[length
] = 0 ;
894 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
895 (*myPath
)[length
-1] = 0 ;
897 // create path string for return value
898 wxString
result( (char*) *myPath
) ;
900 // free allocated handle
901 ::HUnlock( myPath
) ;
902 ::DisposeHandle( myPath
) ;
908 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
913 // get the FSRef associated with the POSIX path
914 (void) FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
915 // convert the FSRef to an FSSpec
916 (void) FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
918 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
923 // Mac file names are POSIX (Unix style) under Darwin
924 // therefore the conversion functions below are not needed
926 static char sMacFileNameConversion
[ 1000 ] ;
928 wxString
wxMac2UnixFilename (const char *str
)
930 char *s
= sMacFileNameConversion
;
934 memmove( s
+1 , s
,strlen( s
) + 1) ;
945 *s
= wxTolower(*s
); // Case INDEPENDENT
949 return wxString(sMacFileNameConversion
) ;
952 wxString
wxUnix2MacFilename (const char *str
)
954 char *s
= sMacFileNameConversion
;
960 // relative path , since it goes on with slash which is translated to a :
961 memmove( s
, s
+1 ,strlen( s
) ) ;
963 else if ( *s
== '/' )
965 // absolute path -> on mac just start with the drive name
966 memmove( s
, s
+1 ,strlen( s
) ) ;
970 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
974 if (*s
== '/' || *s
== '\\')
976 // convert any back-directory situations
977 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
980 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
988 return wxString (sMacFileNameConversion
) ;
991 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
993 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
996 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
998 wxString var
= wxUnix2MacFilename( path
) ;
999 wxMacFilename2FSSpec( var
, spec
) ;
1001 #endif // ! __DARWIN__
1006 wxDos2UnixFilename (char *s
)
1015 *s
= wxTolower (*s
); // Case INDEPENDENT
1022 #if defined(__WXMSW__) || defined(__WXPM__)
1023 wxUnix2DosFilename (wxChar
*s
)
1025 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1028 // Yes, I really mean this to happen under DOS only! JACS
1029 #if defined(__WXMSW__) || defined(__WXPM__)
1040 // Concatenate two files to form third
1042 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1045 if ( !wxGetTempFileName("cat", outfile
) )
1048 FILE *fp1
= (FILE *) NULL
;
1049 FILE *fp2
= (FILE *) NULL
;
1050 FILE *fp3
= (FILE *) NULL
;
1051 // Open the inputs and outputs
1052 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
1053 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
1054 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
1066 while ((ch
= getc (fp1
)) != EOF
)
1067 (void) putc (ch
, fp3
);
1070 while ((ch
= getc (fp2
)) != EOF
)
1071 (void) putc (ch
, fp3
);
1075 bool result
= wxRenameFile(outfile
, file3
);
1081 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1083 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1084 // CopyFile() copies file attributes and modification time too, so use it
1085 // instead of our code if available
1087 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1088 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1089 #elif defined(__WXPM__)
1090 if (::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) == 0)
1097 // get permissions of file1
1098 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1100 // the file probably doesn't exist or we haven't the rights to read
1102 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1107 // open file1 for reading
1108 wxFile
fileIn(file1
, wxFile::read
);
1109 if ( !fileIn
.IsOpened() )
1112 // remove file2, if it exists. This is needed for creating
1113 // file2 with the correct permissions in the next step
1114 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1116 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1122 // reset the umask as we want to create the file with exactly the same
1123 // permissions as the original one
1124 mode_t oldUmask
= umask( 0 );
1127 // create file2 with the same permissions than file1 and open it for
1130 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1134 /// restore the old umask
1138 // copy contents of file1 to file2
1143 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1144 if ( fileIn
.Error() )
1151 if ( fileOut
.Write(buf
, count
) < count
)
1155 // we can expect fileIn to be closed successfully, but we should ensure
1156 // that fileOut was closed as some write errors (disk full) might not be
1157 // detected before doing this
1158 if ( !fileIn
.Close() || !fileOut
.Close() )
1161 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1162 // no chmod in VA. Should be some permission API for HPFS386 partitions
1164 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1166 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1170 #endif // OS/2 || Mac
1173 #endif // __WXMSW__ && __WIN32__
1177 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1179 // Normal system call
1180 if ( wxRename (file1
, file2
) == 0 )
1184 if (wxCopyFile(file1
, file2
)) {
1185 wxRemoveFile(file1
);
1192 bool wxRemoveFile(const wxString
& file
)
1194 #if defined(__VISUALC__) \
1195 || defined(__BORLANDC__) \
1196 || defined(__WATCOMC__) \
1197 || defined(__GNUWIN32__)
1198 int res
= wxRemove(file
);
1200 int res
= unlink(OS_FILENAME(file
));
1206 bool wxMkdir(const wxString
& dir
, int perm
)
1208 #if defined(__WXMAC__) && !defined(__UNIX__)
1209 return (mkdir( dir
, 0 ) == 0);
1211 const wxChar
*dirname
= dir
.c_str();
1213 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1214 // for the GNU compiler
1215 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1216 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1217 #elif defined(__WXPM__)
1218 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1219 #elif defined(__DOS__)
1220 #if defined(__WATCOMC__)
1222 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1223 #elif defined(__DJGPP__)
1224 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1226 #error "Unsupported DOS compiler!"
1228 #else // !MSW, !DOS and !OS/2 VAC++
1230 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1233 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1242 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1245 return FALSE
; //to be changed since rmdir exists in VMS7.x
1246 #elif defined(__WXPM__)
1247 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1251 return FALSE
; // What to do?
1253 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1259 // does the path exists? (may have or not '/' or '\\' at the end)
1260 bool wxPathExists(const wxChar
*pszPathName
)
1262 wxString
strPath(pszPathName
);
1265 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1266 // so remove all trailing backslashes from the path - but don't do this for
1267 // the pathes "d:\" (which are different from "d:") nor for just "\"
1268 while ( wxEndsWithPathSeparator(strPath
) )
1270 size_t len
= strPath
.length();
1271 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1274 strPath
.Truncate(len
- 1);
1276 #endif // __WINDOWS__
1278 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1279 // stat() can't cope with network paths
1280 DWORD ret
= ::GetFileAttributes(strPath
);
1282 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1286 #ifndef __VISAGECPP__
1287 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1288 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1290 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1291 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1292 (st
.st_mode
== S_IFDIR
);
1295 #endif // __WIN32__/!__WIN32__
1298 // Get a temporary filename, opening and closing the file.
1299 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1301 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1302 if ( filename
.empty() )
1306 wxStrcpy(buf
, filename
);
1308 buf
= copystring(filename
);
1313 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1315 buf
= wxFileName::CreateTempFileName(prefix
);
1317 return !buf
.empty();
1320 // Get first file name matching given wild card.
1322 static wxDir
*gs_dir
= NULL
;
1323 static wxString gs_dirPath
;
1325 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1327 gs_dirPath
= wxPathOnly(spec
);
1328 if ( gs_dirPath
.IsEmpty() )
1329 gs_dirPath
= wxT(".");
1330 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1331 gs_dirPath
<< wxFILE_SEP_PATH
;
1335 gs_dir
= new wxDir(gs_dirPath
);
1337 if ( !gs_dir
->IsOpened() )
1339 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1340 return wxEmptyString
;
1346 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1347 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1348 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1352 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1353 if ( result
.IsEmpty() )
1359 return gs_dirPath
+ result
;
1362 wxString
wxFindNextFile()
1364 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1367 gs_dir
->GetNext(&result
);
1369 if ( result
.IsEmpty() )
1375 return gs_dirPath
+ result
;
1379 // Get current working directory.
1380 // If buf is NULL, allocates space using new, else
1382 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1386 buf
= new wxChar
[sz
+ 1];
1391 // for the compilers which have Unicode version of _getcwd(), call it
1392 // directly, for the others call the ANSI version and do the translation
1395 ok
= _wgetcwd(buf
, sz
) != NULL
;
1396 #else // !HAVE_WGETCWD
1397 wxCharBuffer
cbuf(sz
);
1401 #if !wxUSE_UNICODE || !defined(HAVE_WGETCWD)
1403 ok
= _getcwd(buf
, sz
) != NULL
;
1404 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1409 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1411 pb
.ioRefNum
= LMGetCurApRefNum();
1413 error
= PBGetFCBInfoSync(&pb
);
1414 if ( error
== noErr
)
1416 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1417 cwdSpec
.parID
= pb
.ioFCBParID
;
1418 cwdSpec
.name
[0] = 0 ;
1419 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1421 strcpy( buf
, res
) ;
1422 buf
[res
.length()]=0 ;
1430 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1432 rc
= ::DosQueryCurrentDir( 0 // current drive
1437 #else // !Win32/VC++ !Mac !OS2
1438 ok
= getcwd(buf
, sz
) != NULL
;
1440 #endif // !wxUSE_UNICODE || !HAVE_WGETCWD
1444 wxLogSysError(_("Failed to get the working directory"));
1446 // VZ: the old code used to return "." on error which didn't make any
1447 // sense at all to me - empty string is a better error indicator
1448 // (NULL might be even better but I'm afraid this could lead to
1449 // problems with the old code assuming the return is never NULL)
1452 else // ok, but we might need to massage the path into the right format
1455 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1456 // with / deliminers. We don't like that.
1457 for (wxChar
*ch
= buf
; *ch
; ch
++)
1459 if (*ch
== wxT('/'))
1465 // another example of DOS/Unix mix (Cygwin)
1466 wxString pathUnix
= buf
;
1467 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1468 #endif // __CYGWIN__
1470 // finally convert the result to Unicode if needed
1471 #if wxUSE_UNICODE && !defined(HAVE_WGETCWD)
1472 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1473 #endif // wxUSE_UNICODE
1483 // we can't create wxStringBuffer object inline: Sun CC generates buggy
1484 // code in this case!
1486 wxStringBuffer
buf(str
, _MAXPATHLEN
);
1487 wxGetWorkingDirectory(buf
, _MAXPATHLEN
);
1493 bool wxSetWorkingDirectory(const wxString
& d
)
1495 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1496 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1497 #elif defined(__WXPM__)
1498 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1499 #elif defined(__WINDOWS__)
1502 return (bool)(SetCurrentDirectory(d
) != 0);
1504 // Must change drive, too.
1505 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1508 wxChar firstChar
= d
[0];
1512 firstChar
= firstChar
- 32;
1514 // To a drive number
1515 unsigned int driveNo
= firstChar
- 64;
1518 unsigned int noDrives
;
1519 _dos_setdrive(driveNo
, &noDrives
);
1522 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1530 // Get the OS directory if appropriate (such as the Windows directory).
1531 // On non-Windows platform, probably just return the empty string.
1532 wxString
wxGetOSDirectory()
1534 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1536 GetWindowsDirectory(buf
, 256);
1537 return wxString(buf
);
1539 return wxEmptyString
;
1543 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1545 size_t len
= wxStrlen(pszFileName
);
1547 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1550 // find a file in a list of directories, returns false if not found
1551 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1553 // we assume that it's not empty
1554 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1555 _T("empty file name in wxFindFileInPath"));
1557 // skip path separator in the beginning of the file name if present
1558 if ( wxIsPathSeparator(*pszFile
) )
1561 // copy the path (strtok will modify it)
1562 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1563 wxStrcpy(szPath
, pszPath
);
1566 wxChar
*pc
, *save_ptr
;
1567 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1569 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1571 // search for the file in this directory
1573 if ( !wxEndsWithPathSeparator(pc
) )
1574 strFile
+= wxFILE_SEP_PATH
;
1577 if ( FileExists(strFile
) ) {
1583 // suppress warning about unused variable save_ptr when wxStrtok() is a
1584 // macro which throws away its third argument
1589 return pc
!= NULL
; // if true => we breaked from the loop
1592 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1597 // it can be empty, but it shouldn't be NULL
1598 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1600 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1603 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1607 wxStat(filename
.fn_str(), &buf
);
1608 return buf
.st_mtime
;
1612 //------------------------------------------------------------------------
1613 // wild character routines
1614 //------------------------------------------------------------------------
1616 bool wxIsWild( const wxString
& pattern
)
1618 wxString tmp
= pattern
;
1619 wxChar
*pat
= WXSTRINGCAST(tmp
);
1622 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1632 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1634 #if defined(HAVE_FNMATCH_H)
1636 // this probably won't work well for multibyte chars in Unicode mode?
1638 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1640 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1644 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1647 * WARNING: this code is broken!
1650 wxString tmp1
= pat
;
1651 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1652 wxString tmp2
= text
;
1653 wxChar
*str
= WXSTRINGCAST(tmp2
);
1656 bool done
= FALSE
, ret_code
, ok
;
1657 // Below is for vi fans
1658 const wxChar OB
= wxT('{'), CB
= wxT('}');
1660 // dot_special means '.' only matches '.'
1661 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1664 while ((*pattern
!= wxT('\0')) && (!done
)
1665 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1669 if (*pattern
!= wxT('\0'))
1675 while ((*str
!=wxT('\0'))
1676 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1679 while (*str
!= wxT('\0'))
1681 while (*pattern
!= wxT('\0'))
1688 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1692 if (*pattern
== wxT('\\')) {
1694 if (*pattern
== wxT('\0')) {
1699 if (*(pattern
+ 1) == wxT('-')) {
1702 if (*pattern
== wxT(']')) {
1706 if (*pattern
== wxT('\\')) {
1708 if (*pattern
== wxT('\0')) {
1713 if ((*str
< c
) || (*str
> *pattern
)) {
1717 } else if (*pattern
!= *str
) {
1722 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1723 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1727 if (*pattern
!= wxT('\0')) {
1737 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1740 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1741 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1742 if (*pattern
== wxT('\\'))
1744 ok
= (*pattern
++ == *cp
++);
1746 if (*pattern
== wxT('\0')) {
1752 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1753 if (*++pattern
== wxT('\\')) {
1754 if (*++pattern
== CB
)
1759 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1760 if (*++pattern
== wxT('\\')) {
1761 if (*++pattern
== CB
|| *pattern
== wxT(','))
1766 if (*pattern
!= wxT('\0'))
1771 if (*str
== *pattern
) {
1778 while (*pattern
== wxT('*'))
1780 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1786 #pragma warning(default:4706) // assignment within conditional expression
1789 //------------------------------------------------------------------------
1790 // Missing functions in Unicode for Win9x
1791 //------------------------------------------------------------------------
1793 // NB: MSLU only covers Win32 API, it doesn't provide Unicode implementation of
1794 // libc functions. Unfortunately, some of MSVCRT wchar_t functions
1795 // (e.g. _wopen) don't work on Windows 9x, so we have to workaround it
1796 // by calling the char version. We still want to use wchar_t version on
1797 // NT/2000/XP, though, because they allow for Unicode file names.
1798 #if wxUSE_UNICODE_MSLU
1800 #if defined( __VISUALC__ ) \
1801 || ( defined(__MINGW32__) && wxCHECK_W32API_VERSION( 0, 5 ) ) \
1802 || ( defined(__MWERKS__) && defined(__WXMSW__) )
1803 WXDLLEXPORT
int wxOpen(const wxChar
*name
, int flags
, int mode
)
1805 if ( wxGetOsVersion() == wxWINDOWS_NT
)
1806 return _wopen(name
, flags
, mode
);
1808 return _open(wxConvFile
.cWX2MB(name
), flags
, mode
);
1812 #endif // wxUSE_UNICODE_MSLU