1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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
58 #include "wx/msw/wince/time.h"
59 #include "wx/msw/private.h"
66 #elif !defined(__MWERKS__)
67 #include <sys/types.h>
71 #include <sys/types.h>
84 // need to check for __OS2__ first since currently both
85 // __OS2__ and __UNIX__ are defined.
87 #include "wx/os2/private.h"
91 #elif defined(__UNIX__)
97 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
98 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__) && !defined(__WXWINCE__)
102 #endif // __WINDOWS__
103 #endif // native Win compiler
116 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
117 // this (3.1 I believe) and how to test for it.
118 // If this works for Borland 4.0 as well, then no worries.
129 // No, Cygwin doesn't appear to have fnmatch.h after all.
130 #if defined(HAVE_FNMATCH_H)
135 #include "wx/msw/wrapwin.h"
136 #include "wx/msw/mslu.h"
143 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
145 // note that it must be included after <windows.h>
148 #include <sys/cygwin.h>
150 #endif // __GNUWIN32__
151 #endif // __WINDOWS__
153 // TODO: Borland probably has _wgetcwd as well?
158 // ----------------------------------------------------------------------------
160 // ----------------------------------------------------------------------------
163 #define _MAXPATHLEN 1024
167 # include "MoreFilesX.h"
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 // MT-FIXME: get rid of this horror and all code using it
175 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
177 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
179 // VisualAge C++ V4.0 cannot have any external linkage const decs
180 // in headers included by more than one primary source
182 const off_t wxInvalidOffset
= (off_t
)-1;
185 // ----------------------------------------------------------------------------
187 // ----------------------------------------------------------------------------
189 // we need to translate Mac filenames before passing them to OS functions
190 #define OS_FILENAME(s) (s.fn_str())
192 // ============================================================================
194 // ============================================================================
196 #ifdef wxNEED_WX_UNISTD_H
198 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
200 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
203 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
205 return access( wxConvFile
.cWX2MB( pathname
), mode
);
208 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
210 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
214 // wxNEED_WX_UNISTD_H
216 // ----------------------------------------------------------------------------
218 // ----------------------------------------------------------------------------
220 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
222 static inline wxChar
* MYcopystring(const wxString
& s
)
224 wxChar
* copy
= new wxChar
[s
.length() + 1];
225 return wxStrcpy(copy
, s
.c_str());
228 static inline wxChar
* MYcopystring(const wxChar
* s
)
230 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
231 return wxStrcpy(copy
, s
);
234 void wxPathList::Add (const wxString
& path
)
236 wxStringList::Add (WXSTRINGCAST path
);
239 // Add paths e.g. from the PATH environment variable
240 void wxPathList::AddEnvList (const wxString
& envVariable
)
242 // No environment variables on WinCE
244 static const wxChar PATH_TOKS
[] =
245 #if defined(__WINDOWS__) || defined(__OS2__)
247 The space has been removed from the tokenizers, otherwise a
248 path such as "C:\Program Files" would be split into 2 paths:
249 "C:\Program" and "Files"
251 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
252 wxT(";"); // Don't seperate with colon in DOS (used for drive)
257 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
260 wxChar
*s
= MYcopystring (val
);
261 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
268 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
276 // suppress warning about unused variable save_ptr when wxStrtok() is a
277 // macro which throws away its third argument
285 // Given a full filename (with path), ensure that that file can
286 // be accessed again USING FILENAME ONLY by adding the path
287 // to the list if not already there.
288 void wxPathList::EnsureFileAccessible (const wxString
& path
)
290 wxString
path_only(wxPathOnly(path
));
291 if ( !path_only
.IsEmpty() )
293 if ( !Member(path_only
) )
298 bool wxPathList::Member (const wxString
& path
)
300 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
302 wxString
path2( node
->GetData() );
304 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined (__WXMAC__)
306 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
308 // Case sensitive File System
309 path
.CompareTo (path2
) == 0
317 wxString
wxPathList::FindValidPath (const wxString
& file
)
319 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
320 return wxString(wxFileFunctionsBuffer
);
322 wxChar buf
[_MAXPATHLEN
];
323 wxStrcpy(buf
, wxFileFunctionsBuffer
);
325 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
327 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
329 const wxChar
*path
= node
->GetData();
330 wxStrcpy (wxFileFunctionsBuffer
, path
);
331 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
332 if (ch
!= wxT('\\') && ch
!= wxT('/'))
333 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
334 wxStrcat (wxFileFunctionsBuffer
, filename
);
336 wxUnix2DosFilename (wxFileFunctionsBuffer
);
338 if (wxFileExists (wxFileFunctionsBuffer
))
340 return wxString(wxFileFunctionsBuffer
); // Found!
344 return wxEmptyString
; // Not found
347 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
349 wxString f
= FindValidPath(file
);
350 if ( f
.empty() || wxIsAbsolutePath(f
) )
354 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
356 if ( !wxEndsWithPathSeparator(buf
) )
358 buf
+= wxFILE_SEP_PATH
;
366 wxFileExists (const wxString
& filename
)
368 // we must use GetFileAttributes() instead of the ANSI C functions because
369 // it can cope with network (UNC) paths unlike them
370 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
371 DWORD ret
= ::GetFileAttributes(filename
);
373 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
376 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
377 #endif // __WIN32__/!__WIN32__
381 wxIsAbsolutePath (const wxString
& filename
)
383 if (filename
!= wxT(""))
385 #if defined(__WXMAC__) && !defined(__DARWIN__)
386 // Classic or Carbon CodeWarrior like
387 // Carbon with Apple DevTools is Unix like
389 // This seems wrong to me, but there is no fix. since
390 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
391 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
392 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
395 // Unix like or Windows
396 if (filename
[0] == wxT('/'))
400 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
403 #if defined(__WINDOWS__) || defined(__OS2__)
405 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
413 * Strip off any extension (dot something) from end of file,
414 * IF one exists. Inserts zero into buffer.
418 void wxStripExtension(wxChar
*buffer
)
420 int len
= wxStrlen(buffer
);
424 if (buffer
[i
] == wxT('.'))
433 void wxStripExtension(wxString
& buffer
)
435 size_t len
= buffer
.Length();
439 if (buffer
.GetChar(i
) == wxT('.'))
441 buffer
= buffer
.Left(i
);
448 // Destructive removal of /./ and /../ stuff
449 wxChar
*wxRealPath (wxChar
*path
)
452 static const wxChar SEP
= wxT('\\');
453 wxUnix2DosFilename(path
);
455 static const wxChar SEP
= wxT('/');
457 if (path
[0] && path
[1]) {
458 /* MATTHEW: special case "/./x" */
460 if (path
[2] == SEP
&& path
[1] == wxT('.'))
468 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
471 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
476 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
477 && (q
- 1 <= path
|| q
[-1] != SEP
))
480 if (path
[0] == wxT('\0'))
485 #if defined(__WXMSW__) || defined(__OS2__)
486 /* Check that path[2] is NULL! */
487 else if (path
[1] == wxT(':') && !path
[2])
496 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
505 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
507 if (filename
== wxT(""))
508 return (wxChar
*) NULL
;
510 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
511 wxChar buf
[_MAXPATHLEN
];
513 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
514 wxChar ch
= buf
[wxStrlen(buf
) - 1];
516 if (ch
!= wxT('\\') && ch
!= wxT('/'))
517 wxStrcat(buf
, wxT("\\"));
520 wxStrcat(buf
, wxT("/"));
522 wxStrcat(buf
, wxFileFunctionsBuffer
);
523 return MYcopystring( wxRealPath(buf
) );
525 return MYcopystring( wxFileFunctionsBuffer
);
531 ~user/ => user's home dir
532 If the environment variable a = "foo" and b = "bar" then:
549 /* input name in name, pathname output to buf. */
551 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
553 register wxChar
*d
, *s
, *nm
;
554 wxChar lnm
[_MAXPATHLEN
];
557 // Some compilers don't like this line.
558 // const wxChar trimchars[] = wxT("\n \t");
561 trimchars
[0] = wxT('\n');
562 trimchars
[1] = wxT(' ');
563 trimchars
[2] = wxT('\t');
567 const wxChar SEP
= wxT('\\');
569 const wxChar SEP
= wxT('/');
572 if (name
== NULL
|| *name
== wxT('\0'))
574 nm
= MYcopystring(name
); // Make a scratch copy
577 /* Skip leading whitespace and cr */
578 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
580 /* And strip off trailing whitespace and cr */
581 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
582 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
590 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
593 /* Expand inline environment variables */
611 while ((*d
++ = *s
) != 0) {
613 if (*s
== wxT('\\')) {
614 if ((*(d
- 1) = *++s
)) {
622 // No env variables on WinCE
625 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
627 if (*s
++ == wxT('$'))
630 register wxChar
*start
= d
;
631 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
632 register wxChar
*value
;
633 while ((*d
++ = *s
) != 0)
634 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
639 value
= wxGetenv(braces
? start
+ 1 : start
);
641 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
655 /* Expand ~ and ~user */
657 if (nm
[0] == wxT('~') && !q
)
660 if (nm
[1] == SEP
|| nm
[1] == 0)
662 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
663 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
668 { /* ~user/filename */
669 register wxChar
*nnm
;
670 register wxChar
*home
;
671 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
675 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
676 was_sep
= (*s
== SEP
);
677 nnm
= *s
? s
+ 1 : s
;
679 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
680 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
681 if (was_sep
) /* replace only if it was there: */
692 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
694 while (wxT('\0') != (*d
++ = *s
++))
697 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
701 while ((*d
++ = *s
++) != 0)
705 delete[] nm_tmp
; // clean up alloc
706 /* Now clean up the buffer */
707 return wxRealPath(buf
);
710 /* Contract Paths to be build upon an environment variable
713 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
715 The call wxExpandPath can convert these back!
718 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
720 static wxChar dest
[_MAXPATHLEN
];
722 if (filename
== wxT(""))
723 return (wxChar
*) NULL
;
725 wxStrcpy (dest
, WXSTRINGCAST filename
);
727 wxUnix2DosFilename(dest
);
730 // Handle environment
734 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
735 (tcp
= wxStrstr (dest
, val
)) != NULL
)
737 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
740 wxStrcpy (tcp
, WXSTRINGCAST envname
);
741 wxStrcat (tcp
, wxT("}"));
742 wxStrcat (tcp
, wxFileFunctionsBuffer
);
746 // Handle User's home (ignore root homes!)
747 val
= wxGetUserHome (user
);
751 const size_t len
= wxStrlen(val
);
755 if (wxStrncmp(dest
, val
, len
) == 0)
757 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
759 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
760 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
761 wxStrcpy (dest
, wxFileFunctionsBuffer
);
767 // Return just the filename, not the path (basename)
768 wxChar
*wxFileNameFromPath (wxChar
*path
)
771 wxString n
= wxFileNameFromPath(p
);
773 return path
+ p
.length() - n
.length();
776 wxString
wxFileNameFromPath (const wxString
& path
)
779 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
781 wxString fullname
= name
;
784 fullname
<< wxFILE_SEP_EXT
<< ext
;
790 // Return just the directory, or NULL if no directory
792 wxPathOnly (wxChar
*path
)
796 static wxChar buf
[_MAXPATHLEN
];
799 wxStrcpy (buf
, path
);
801 int l
= wxStrlen(path
);
804 // Search backward for a backward or forward slash
807 #if defined(__WXMAC__) && !defined(__DARWIN__)
808 // Classic or Carbon CodeWarrior like
809 // Carbon with Apple DevTools is Unix like
810 if (path
[i
] == wxT(':') )
816 // Unix like or Windows
817 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
824 if (path
[i
] == wxT(']'))
833 #if defined(__WXMSW__) || defined(__OS2__)
834 // Try Drive specifier
835 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
837 // A:junk --> A:. (since A:.\junk Not A:\junk)
844 return (wxChar
*) NULL
;
847 // Return just the directory, or NULL if no directory
848 wxString
wxPathOnly (const wxString
& path
)
852 wxChar buf
[_MAXPATHLEN
];
855 wxStrcpy (buf
, WXSTRINGCAST path
);
857 int l
= path
.Length();
860 // Search backward for a backward or forward slash
863 #if defined(__WXMAC__) && !defined(__DARWIN__)
864 // Classic or Carbon CodeWarrior like
865 // Carbon with Apple DevTools is Unix like
866 if (path
[i
] == wxT(':') )
869 return wxString(buf
);
872 // Unix like or Windows
873 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
875 // Don't return an empty string
879 return wxString(buf
);
883 if (path
[i
] == wxT(']'))
886 return wxString(buf
);
892 #if defined(__WXMSW__) || defined(__OS2__)
893 // Try Drive specifier
894 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
896 // A:junk --> A:. (since A:.\junk Not A:\junk)
899 return wxString(buf
);
903 return wxString(wxT(""));
906 // Utility for converting delimiters in DOS filenames to UNIX style
907 // and back again - or we get nasty problems with delimiters.
908 // Also, convert to lower case, since case is significant in UNIX.
910 #if defined(__WXMAC__)
912 #if TARGET_API_MAC_OSX
913 #define kDefaultPathStyle kCFURLPOSIXPathStyle
915 #define kDefaultPathStyle kCFURLHFSPathStyle
918 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
921 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
922 if ( additionalPathComponent
)
924 CFURLRef parentURLRef
= fullURLRef
;
925 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
926 additionalPathComponent
,false);
927 CFRelease( parentURLRef
) ;
929 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
930 CFRelease( fullURLRef
) ;
931 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
934 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
936 OSStatus err
= noErr
;
937 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
940 if ( CFURLGetFSRef(url
, fsRef
) == false )
951 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
953 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
956 return wxMacCFStringHolder(cfname
).AsString() ;
959 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
962 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
964 return wxMacFSRefToPath( &fsRef
) ;
966 return wxEmptyString
;
969 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
971 OSStatus err
= noErr
;
973 wxMacPathToFSRef( path
, &fsRef
) ;
974 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
980 wxDos2UnixFilename (wxChar
*s
)
989 *s
= wxTolower (*s
); // Case INDEPENDENT
996 #if defined(__WXMSW__) || defined(__OS2__)
997 wxUnix2DosFilename (wxChar
*s
)
999 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1002 // Yes, I really mean this to happen under DOS only! JACS
1003 #if defined(__WXMSW__) || defined(__OS2__)
1014 // Concatenate two files to form third
1016 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1019 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
1022 FILE *fp1
wxDUMMY_INITIALIZE(NULL
);
1025 // Open the inputs and outputs
1026 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1027 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1028 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1040 while ((ch
= getc (fp1
)) != EOF
)
1041 (void) putc (ch
, fp3
);
1044 while ((ch
= getc (fp2
)) != EOF
)
1045 (void) putc (ch
, fp3
);
1049 bool result
= wxRenameFile(outfile
, file3
);
1055 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1057 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1058 // CopyFile() copies file attributes and modification time too, so use it
1059 // instead of our code if available
1061 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1062 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1064 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1065 file1
.c_str(), file2
.c_str());
1069 #elif defined(__OS2__)
1070 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1075 // get permissions of file1
1076 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1078 // the file probably doesn't exist or we haven't the rights to read
1080 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1085 // open file1 for reading
1086 wxFile
fileIn(file1
, wxFile::read
);
1087 if ( !fileIn
.IsOpened() )
1090 // remove file2, if it exists. This is needed for creating
1091 // file2 with the correct permissions in the next step
1092 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1094 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1100 // reset the umask as we want to create the file with exactly the same
1101 // permissions as the original one
1102 mode_t oldUmask
= umask( 0 );
1105 // create file2 with the same permissions than file1 and open it for
1109 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1113 /// restore the old umask
1117 // copy contents of file1 to file2
1122 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1123 if ( fileIn
.Error() )
1130 if ( fileOut
.Write(buf
, count
) < count
)
1134 // we can expect fileIn to be closed successfully, but we should ensure
1135 // that fileOut was closed as some write errors (disk full) might not be
1136 // detected before doing this
1137 if ( !fileIn
.Close() || !fileOut
.Close() )
1140 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1141 // no chmod in VA. Should be some permission API for HPFS386 partitions
1143 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1145 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1149 #endif // OS/2 || Mac
1150 #endif // __WXMSW__ && __WIN32__
1156 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1159 // Normal system call
1160 if ( wxRename (file1
, file2
) == 0 )
1165 if (wxCopyFile(file1
, file2
)) {
1166 wxRemoveFile(file1
);
1173 bool wxRemoveFile(const wxString
& file
)
1175 #if defined(__VISUALC__) \
1176 || defined(__BORLANDC__) \
1177 || defined(__WATCOMC__) \
1178 || defined(__DMC__) \
1179 || defined(__GNUWIN32__) \
1180 || (defined(__MWERKS__) && defined(__MSL__))
1181 int res
= wxRemove(file
);
1182 #elif defined(__WXMAC__)
1183 int res
= unlink(wxFNCONV(file
));
1185 int res
= unlink(OS_FILENAME(file
));
1191 bool wxMkdir(const wxString
& dir
, int perm
)
1193 #if defined(__WXMAC__) && !defined(__UNIX__)
1194 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1196 const wxChar
*dirname
= dir
.c_str();
1198 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1199 // for the GNU compiler
1200 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1203 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1205 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1207 #elif defined(__OS2__)
1208 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1209 #elif defined(__DOS__)
1210 #if defined(__WATCOMC__)
1212 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1213 #elif defined(__DJGPP__)
1214 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1216 #error "Unsupported DOS compiler!"
1218 #else // !MSW, !DOS and !OS/2 VAC++
1221 if ( !CreateDirectory(dirname
, NULL
) )
1223 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1227 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1236 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1239 return false; //to be changed since rmdir exists in VMS7.x
1240 #elif defined(__OS2__)
1241 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1245 return (CreateDirectory(dir
, NULL
) != 0);
1247 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1253 // does the path exists? (may have or not '/' or '\\' at the end)
1254 bool wxPathExists(const wxChar
*pszPathName
)
1256 wxString
strPath(pszPathName
);
1258 #if defined(__WINDOWS__) || defined(__OS2__)
1259 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1260 // so remove all trailing backslashes from the path - but don't do this for
1261 // the pathes "d:\" (which are different from "d:") nor for just "\"
1262 while ( wxEndsWithPathSeparator(strPath
) )
1264 size_t len
= strPath
.length();
1265 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1268 strPath
.Truncate(len
- 1);
1270 #endif // __WINDOWS__
1273 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1274 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
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(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1289 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1290 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1293 #endif // __WIN32__/!__WIN32__
1296 // Get a temporary filename, opening and closing the file.
1297 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1299 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1300 if ( filename
.empty() )
1304 wxStrcpy(buf
, filename
);
1306 buf
= MYcopystring(filename
);
1311 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1313 buf
= wxFileName::CreateTempFileName(prefix
);
1315 return !buf
.empty();
1318 // Get first file name matching given wild card.
1320 static wxDir
*gs_dir
= NULL
;
1321 static wxString gs_dirPath
;
1323 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1325 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1326 if ( gs_dirPath
.IsEmpty() )
1327 gs_dirPath
= wxT(".");
1328 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1329 gs_dirPath
<< wxFILE_SEP_PATH
;
1333 gs_dir
= new wxDir(gs_dirPath
);
1335 if ( !gs_dir
->IsOpened() )
1337 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1338 return wxEmptyString
;
1344 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1345 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1346 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1350 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1351 if ( result
.IsEmpty() )
1357 return gs_dirPath
+ result
;
1360 wxString
wxFindNextFile()
1362 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1365 gs_dir
->GetNext(&result
);
1367 if ( result
.IsEmpty() )
1373 return gs_dirPath
+ result
;
1377 // Get current working directory.
1378 // If buf is NULL, allocates space using new, else
1380 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1387 buf
= new wxChar
[sz
+ 1];
1390 bool ok
wxDUMMY_INITIALIZE(false);
1392 // for the compilers which have Unicode version of _getcwd(), call it
1393 // directly, for the others call the ANSI version and do the translation
1396 #else // wxUSE_UNICODE
1397 bool needsANSI
= true;
1399 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1400 // This is not legal code as the compiler
1401 // is allowed destroy the wxCharBuffer.
1402 // wxCharBuffer c_buffer(sz);
1403 // char *cbuf = (char*)(const char*)c_buffer;
1404 char cbuf
[_MAXPATHLEN
];
1408 #if wxUSE_UNICODE_MSLU
1409 if ( wxGetOsVersion() != wxWIN95
)
1411 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1414 ok
= _wgetcwd(buf
, sz
) != NULL
;
1420 #endif // wxUSE_UNICODE
1422 #if defined(_MSC_VER) || defined(__MINGW32__)
1423 ok
= _getcwd(cbuf
, sz
) != NULL
;
1424 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1426 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1428 wxString
res( lbuf
, *wxConvCurrent
) ;
1429 wxStrcpy( buf
, res
) ;
1434 #elif defined(__OS2__)
1436 ULONG ulDriveNum
= 0;
1437 ULONG ulDriveMap
= 0;
1438 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1443 rc
= ::DosQueryCurrentDir( 0 // current drive
1447 cbuf
[0] = 'A' + (ulDriveNum
- 1);
1452 #else // !Win32/VC++ !Mac !OS2
1453 ok
= getcwd(cbuf
, sz
) != NULL
;
1456 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1457 // finally convert the result to Unicode if needed
1458 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1459 #endif // wxUSE_UNICODE
1464 wxLogSysError(_("Failed to get the working directory"));
1466 // VZ: the old code used to return "." on error which didn't make any
1467 // sense at all to me - empty string is a better error indicator
1468 // (NULL might be even better but I'm afraid this could lead to
1469 // problems with the old code assuming the return is never NULL)
1472 else // ok, but we might need to massage the path into the right format
1475 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1476 // with / deliminers. We don't like that.
1477 for (wxChar
*ch
= buf
; *ch
; ch
++)
1479 if (*ch
== wxT('/'))
1484 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1485 // he needs Unix as opposed to Win32 pathnames
1486 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1487 // another example of DOS/Unix mix (Cygwin)
1488 wxString pathUnix
= buf
;
1489 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1490 #endif // __CYGWIN__
1505 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1506 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1507 wxString
str( buffer
);
1513 bool wxSetWorkingDirectory(const wxString
& d
)
1515 #if defined(__OS2__)
1516 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1517 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1518 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1519 #elif defined(__WINDOWS__)
1523 // No equivalent in WinCE
1526 return (bool)(SetCurrentDirectory(d
) != 0);
1529 // Must change drive, too.
1530 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1533 wxChar firstChar
= d
[0];
1537 firstChar
= firstChar
- 32;
1539 // To a drive number
1540 unsigned int driveNo
= firstChar
- 64;
1543 unsigned int noDrives
;
1544 _dos_setdrive(driveNo
, &noDrives
);
1547 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1555 // Get the OS directory if appropriate (such as the Windows directory).
1556 // On non-Windows platform, probably just return the empty string.
1557 wxString
wxGetOSDirectory()
1560 return wxString(wxT("\\Windows"));
1561 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1563 GetWindowsDirectory(buf
, 256);
1564 return wxString(buf
);
1565 #elif defined(__WXMAC__)
1566 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1568 return wxEmptyString
;
1572 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1574 size_t len
= wxStrlen(pszFileName
);
1576 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1579 // find a file in a list of directories, returns false if not found
1580 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1582 // we assume that it's not empty
1583 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1584 _T("empty file name in wxFindFileInPath"));
1586 // skip path separator in the beginning of the file name if present
1587 if ( wxIsPathSeparator(*pszFile
) )
1590 // copy the path (strtok will modify it)
1591 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1592 wxStrcpy(szPath
, pszPath
);
1595 wxChar
*pc
, *save_ptr
;
1596 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1598 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1600 // search for the file in this directory
1602 if ( !wxEndsWithPathSeparator(pc
) )
1603 strFile
+= wxFILE_SEP_PATH
;
1606 if ( wxFileExists(strFile
) ) {
1612 // suppress warning about unused variable save_ptr when wxStrtok() is a
1613 // macro which throws away its third argument
1618 return pc
!= NULL
; // if true => we breaked from the loop
1621 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1626 // it can be empty, but it shouldn't be NULL
1627 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1629 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1632 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1635 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1636 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1637 0, FILE_ATTRIBUTE_NORMAL
, 0);
1638 if (fileHandle
== INVALID_HANDLE_VALUE
)
1642 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1644 CloseHandle(fileHandle
);
1646 wxDateTime dateTime
;
1648 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1650 wxLogLastError(_T("FileTimeToLocalFileTime"));
1654 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1656 wxLogLastError(_T("FileTimeToSystemTime"));
1659 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1660 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1661 return dateTime
.GetTicks();
1668 wxStat( filename
, &buf
);
1670 return buf
.st_mtime
;
1675 // Parses the filterStr, returning the number of filters.
1676 // Returns 0 if none or if there's a problem.
1677 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1679 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
, wxArrayString
& descriptions
, wxArrayString
& filters
)
1681 descriptions
.Clear();
1684 wxString
str(filterStr
);
1686 wxString description
, filter
;
1688 while( pos
!= wxNOT_FOUND
)
1690 pos
= str
.Find(wxT('|'));
1691 if ( pos
== wxNOT_FOUND
)
1693 // if there are no '|'s at all in the string just take the entire
1694 // string as filter and make description empty for later autocompletion
1695 if ( filters
.IsEmpty() )
1697 descriptions
.Add(wxEmptyString
);
1698 filters
.Add(filterStr
);
1702 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1708 description
= str
.Left(pos
);
1709 str
= str
.Mid(pos
+ 1);
1710 pos
= str
.Find(wxT('|'));
1711 if ( pos
== wxNOT_FOUND
)
1717 filter
= str
.Left(pos
);
1718 str
= str
.Mid(pos
+ 1);
1721 descriptions
.Add(description
);
1722 filters
.Add(filter
);
1725 #if defined(__WXMOTIF__)
1726 // split it so there is one wildcard per entry
1727 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1729 pos
= filters
[i
].Find(wxT(';'));
1730 if (pos
!= wxNOT_FOUND
)
1732 // first split only filters
1733 descriptions
.Insert(descriptions
[i
],i
+1);
1734 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1735 filters
[i
]=filters
[i
].Left(pos
);
1737 // autoreplace new filter in description with pattern:
1738 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1739 // cause split into:
1740 // C/C++ Files(*.cpp)|*.cpp
1741 // C/C++ Files(*.c;*.h)|*.c;*.h
1742 // and next iteration cause another split into:
1743 // C/C++ Files(*.cpp)|*.cpp
1744 // C/C++ Files(*.c)|*.c
1745 // C/C++ Files(*.h)|*.h
1746 for ( size_t k
=i
;k
<i
+2;k
++ )
1748 pos
= descriptions
[k
].Find(filters
[k
]);
1749 if (pos
!= wxNOT_FOUND
)
1751 wxString before
= descriptions
[k
].Left(pos
);
1752 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1753 pos
= before
.Find(_T('('),true);
1754 if (pos
>before
.Find(_T(')'),true))
1756 before
= before
.Left(pos
+1);
1757 before
<< filters
[k
];
1758 pos
= after
.Find(_T(')'));
1759 int pos1
= after
.Find(_T('('));
1760 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1762 before
<< after
.Mid(pos
);
1763 descriptions
[k
] = before
;
1773 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1775 if ( descriptions
[j
] == wxEmptyString
&& filters
[j
] != wxEmptyString
)
1777 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1781 return filters
.GetCount();
1785 //------------------------------------------------------------------------
1786 // wild character routines
1787 //------------------------------------------------------------------------
1789 bool wxIsWild( const wxString
& pattern
)
1791 wxString tmp
= pattern
;
1792 wxChar
*pat
= WXSTRINGCAST(tmp
);
1797 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1808 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1810 * The match procedure is public domain code (from ircII's reg.c)
1813 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1817 /* Match if both are empty. */
1821 const wxChar
*m
= pat
.c_str(),
1832 if (dot_special
&& (*n
== wxT('.')))
1834 /* Never match so that hidden Unix files
1835 * are never found. */
1849 else if (*m
== wxT('?'))
1857 if (*m
== wxT('\\'))
1860 /* Quoting "nothing" is a bad thing */
1867 * If we are out of both strings or we just
1868 * saw a wildcard, then we can say we have a
1879 * We could check for *n == NULL at this point, but
1880 * since it's more common to have a character there,
1881 * check to see if they match first (m and n) and
1882 * then if they don't match, THEN we can check for
1900 * If there are no more characters in the
1901 * string, but we still need to find another
1902 * character (*m != NULL), then it will be
1903 * impossible to match it
1910 if (*np
== wxT(' '))
1936 #pragma warning(default:4706) // assignment within conditional expression