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"
34 #include "wx/file.h" // This does include filefn.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
59 // No, Cygwin doesn't appear to have fnmatch.h after all.
60 #if defined(HAVE_FNMATCH_H)
65 #include "wx/msw/wrapwin.h"
66 #include "wx/msw/mslu.h"
68 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
70 // note that it must be included after <windows.h>
73 #include <sys/cygwin.h>
75 #endif // __GNUWIN32__
78 // TODO: Borland probably has _wgetcwd as well?
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
88 #define _MAXPATHLEN 1024
92 # include "MoreFilesX.h"
95 // ----------------------------------------------------------------------------
97 // ----------------------------------------------------------------------------
99 // MT-FIXME: get rid of this horror and all code using it
100 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
102 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
104 // VisualAge C++ V4.0 cannot have any external linkage const decs
105 // in headers included by more than one primary source
107 const int wxInvalidOffset
= -1;
110 // ----------------------------------------------------------------------------
112 // ----------------------------------------------------------------------------
114 // we need to translate Mac filenames before passing them to OS functions
115 #define OS_FILENAME(s) (s.fn_str())
117 // ============================================================================
119 // ============================================================================
121 #ifdef wxNEED_WX_UNISTD_H
123 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
125 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
128 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
130 return access( wxConvFile
.cWX2MB( pathname
), mode
);
133 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
135 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
139 // wxNEED_WX_UNISTD_H
141 // ----------------------------------------------------------------------------
143 // ----------------------------------------------------------------------------
145 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
147 static inline wxChar
* MYcopystring(const wxString
& s
)
149 wxChar
* copy
= new wxChar
[s
.length() + 1];
150 return wxStrcpy(copy
, s
.c_str());
153 static inline wxChar
* MYcopystring(const wxChar
* s
)
155 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
156 return wxStrcpy(copy
, s
);
159 void wxPathList::Add (const wxString
& path
)
161 wxStringList::Add (WXSTRINGCAST path
);
164 // Add paths e.g. from the PATH environment variable
165 void wxPathList::AddEnvList (const wxString
& envVariable
)
167 // No environment variables on WinCE
169 static const wxChar PATH_TOKS
[] =
170 #if defined(__WINDOWS__) || defined(__OS2__)
172 The space has been removed from the tokenizers, otherwise a
173 path such as "C:\Program Files" would be split into 2 paths:
174 "C:\Program" and "Files"
176 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
177 wxT(";"); // Don't seperate with colon in DOS (used for drive)
182 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
185 wxChar
*s
= MYcopystring (val
);
186 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
193 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
201 // suppress warning about unused variable save_ptr when wxStrtok() is a
202 // macro which throws away its third argument
210 // Given a full filename (with path), ensure that that file can
211 // be accessed again USING FILENAME ONLY by adding the path
212 // to the list if not already there.
213 void wxPathList::EnsureFileAccessible (const wxString
& path
)
215 wxString
path_only(wxPathOnly(path
));
216 if ( !path_only
.IsEmpty() )
218 if ( !Member(path_only
) )
223 bool wxPathList::Member (const wxString
& path
)
225 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
227 wxString
path2( node
->GetData() );
229 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined (__WXMAC__)
231 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
233 // Case sensitive File System
234 path
.CompareTo (path2
) == 0
242 wxString
wxPathList::FindValidPath (const wxString
& file
)
244 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
245 return wxString(wxFileFunctionsBuffer
);
247 wxChar buf
[_MAXPATHLEN
];
248 wxStrcpy(buf
, wxFileFunctionsBuffer
);
250 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
252 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
254 const wxChar
*path
= node
->GetData();
255 wxStrcpy (wxFileFunctionsBuffer
, path
);
256 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
257 if (ch
!= wxT('\\') && ch
!= wxT('/'))
258 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
259 wxStrcat (wxFileFunctionsBuffer
, filename
);
261 wxUnix2DosFilename (wxFileFunctionsBuffer
);
263 if (wxFileExists (wxFileFunctionsBuffer
))
265 return wxString(wxFileFunctionsBuffer
); // Found!
269 return wxEmptyString
; // Not found
272 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
274 wxString f
= FindValidPath(file
);
275 if ( f
.empty() || wxIsAbsolutePath(f
) )
279 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
281 if ( !wxEndsWithPathSeparator(buf
) )
283 buf
+= wxFILE_SEP_PATH
;
291 wxFileExists (const wxString
& filename
)
293 // we must use GetFileAttributes() instead of the ANSI C functions because
294 // it can cope with network (UNC) paths unlike them
295 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
296 DWORD ret
= ::GetFileAttributes(filename
);
298 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
301 #ifndef wxNEED_WX_UNISTD_H
302 return wxStat( filename
.fn_str() , &st
) == 0 && (st
.st_mode
& S_IFREG
);
304 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
306 #endif // __WIN32__/!__WIN32__
310 wxIsAbsolutePath (const wxString
& filename
)
312 if (filename
!= wxT(""))
314 #if defined(__WXMAC__) && !defined(__DARWIN__)
315 // Classic or Carbon CodeWarrior like
316 // Carbon with Apple DevTools is Unix like
318 // This seems wrong to me, but there is no fix. since
319 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
320 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
321 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
324 // Unix like or Windows
325 if (filename
[0] == wxT('/'))
329 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
332 #if defined(__WINDOWS__) || defined(__OS2__)
334 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
342 * Strip off any extension (dot something) from end of file,
343 * IF one exists. Inserts zero into buffer.
347 void wxStripExtension(wxChar
*buffer
)
349 int len
= wxStrlen(buffer
);
353 if (buffer
[i
] == wxT('.'))
362 void wxStripExtension(wxString
& buffer
)
364 size_t len
= buffer
.Length();
368 if (buffer
.GetChar(i
) == wxT('.'))
370 buffer
= buffer
.Left(i
);
377 // Destructive removal of /./ and /../ stuff
378 wxChar
*wxRealPath (wxChar
*path
)
381 static const wxChar SEP
= wxT('\\');
382 wxUnix2DosFilename(path
);
384 static const wxChar SEP
= wxT('/');
386 if (path
[0] && path
[1]) {
387 /* MATTHEW: special case "/./x" */
389 if (path
[2] == SEP
&& path
[1] == wxT('.'))
397 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
400 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
405 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
406 && (q
- 1 <= path
|| q
[-1] != SEP
))
409 if (path
[0] == wxT('\0'))
414 #if defined(__WXMSW__) || defined(__OS2__)
415 /* Check that path[2] is NULL! */
416 else if (path
[1] == wxT(':') && !path
[2])
425 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
434 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
436 if (filename
== wxT(""))
437 return (wxChar
*) NULL
;
439 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
440 wxChar buf
[_MAXPATHLEN
];
442 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
443 wxChar ch
= buf
[wxStrlen(buf
) - 1];
445 if (ch
!= wxT('\\') && ch
!= wxT('/'))
446 wxStrcat(buf
, wxT("\\"));
449 wxStrcat(buf
, wxT("/"));
451 wxStrcat(buf
, wxFileFunctionsBuffer
);
452 return MYcopystring( wxRealPath(buf
) );
454 return MYcopystring( wxFileFunctionsBuffer
);
460 ~user/ => user's home dir
461 If the environment variable a = "foo" and b = "bar" then:
478 /* input name in name, pathname output to buf. */
480 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
482 register wxChar
*d
, *s
, *nm
;
483 wxChar lnm
[_MAXPATHLEN
];
486 // Some compilers don't like this line.
487 // const wxChar trimchars[] = wxT("\n \t");
490 trimchars
[0] = wxT('\n');
491 trimchars
[1] = wxT(' ');
492 trimchars
[2] = wxT('\t');
496 const wxChar SEP
= wxT('\\');
498 const wxChar SEP
= wxT('/');
501 if (name
== NULL
|| *name
== wxT('\0'))
503 nm
= MYcopystring(name
); // Make a scratch copy
506 /* Skip leading whitespace and cr */
507 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
509 /* And strip off trailing whitespace and cr */
510 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
511 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
519 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
522 /* Expand inline environment variables */
540 while ((*d
++ = *s
) != 0) {
542 if (*s
== wxT('\\')) {
543 if ((*(d
- 1) = *++s
)) {
551 // No env variables on WinCE
554 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
556 if (*s
++ == wxT('$'))
559 register wxChar
*start
= d
;
560 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
561 register wxChar
*value
;
562 while ((*d
++ = *s
) != 0)
563 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
568 value
= wxGetenv(braces
? start
+ 1 : start
);
570 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
584 /* Expand ~ and ~user */
586 if (nm
[0] == wxT('~') && !q
)
589 if (nm
[1] == SEP
|| nm
[1] == 0)
591 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
592 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
597 { /* ~user/filename */
598 register wxChar
*nnm
;
599 register wxChar
*home
;
600 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
604 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
605 was_sep
= (*s
== SEP
);
606 nnm
= *s
? s
+ 1 : s
;
608 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
609 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
610 if (was_sep
) /* replace only if it was there: */
621 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
623 while (wxT('\0') != (*d
++ = *s
++))
626 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
630 while ((*d
++ = *s
++) != 0)
634 delete[] nm_tmp
; // clean up alloc
635 /* Now clean up the buffer */
636 return wxRealPath(buf
);
639 /* Contract Paths to be build upon an environment variable
642 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
644 The call wxExpandPath can convert these back!
647 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
649 static wxChar dest
[_MAXPATHLEN
];
651 if (filename
== wxT(""))
652 return (wxChar
*) NULL
;
654 wxStrcpy (dest
, WXSTRINGCAST filename
);
656 wxUnix2DosFilename(dest
);
659 // Handle environment
663 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
664 (tcp
= wxStrstr (dest
, val
)) != NULL
)
666 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
669 wxStrcpy (tcp
, WXSTRINGCAST envname
);
670 wxStrcat (tcp
, wxT("}"));
671 wxStrcat (tcp
, wxFileFunctionsBuffer
);
675 // Handle User's home (ignore root homes!)
676 val
= wxGetUserHome (user
);
680 const size_t len
= wxStrlen(val
);
684 if (wxStrncmp(dest
, val
, len
) == 0)
686 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
688 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
689 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
690 wxStrcpy (dest
, wxFileFunctionsBuffer
);
696 // Return just the filename, not the path (basename)
697 wxChar
*wxFileNameFromPath (wxChar
*path
)
700 wxString n
= wxFileNameFromPath(p
);
702 return path
+ p
.length() - n
.length();
705 wxString
wxFileNameFromPath (const wxString
& path
)
708 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
710 wxString fullname
= name
;
713 fullname
<< wxFILE_SEP_EXT
<< ext
;
719 // Return just the directory, or NULL if no directory
721 wxPathOnly (wxChar
*path
)
725 static wxChar buf
[_MAXPATHLEN
];
728 wxStrcpy (buf
, path
);
730 int l
= wxStrlen(path
);
733 // Search backward for a backward or forward slash
736 #if defined(__WXMAC__) && !defined(__DARWIN__)
737 // Classic or Carbon CodeWarrior like
738 // Carbon with Apple DevTools is Unix like
739 if (path
[i
] == wxT(':') )
745 // Unix like or Windows
746 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
753 if (path
[i
] == wxT(']'))
762 #if defined(__WXMSW__) || defined(__OS2__)
763 // Try Drive specifier
764 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
766 // A:junk --> A:. (since A:.\junk Not A:\junk)
773 return (wxChar
*) NULL
;
776 // Return just the directory, or NULL if no directory
777 wxString
wxPathOnly (const wxString
& path
)
781 wxChar buf
[_MAXPATHLEN
];
784 wxStrcpy (buf
, WXSTRINGCAST path
);
786 int l
= path
.Length();
789 // Search backward for a backward or forward slash
792 #if defined(__WXMAC__) && !defined(__DARWIN__)
793 // Classic or Carbon CodeWarrior like
794 // Carbon with Apple DevTools is Unix like
795 if (path
[i
] == wxT(':') )
798 return wxString(buf
);
801 // Unix like or Windows
802 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
804 // Don't return an empty string
808 return wxString(buf
);
812 if (path
[i
] == wxT(']'))
815 return wxString(buf
);
821 #if defined(__WXMSW__) || defined(__OS2__)
822 // Try Drive specifier
823 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
825 // A:junk --> A:. (since A:.\junk Not A:\junk)
828 return wxString(buf
);
832 return wxString(wxT(""));
835 // Utility for converting delimiters in DOS filenames to UNIX style
836 // and back again - or we get nasty problems with delimiters.
837 // Also, convert to lower case, since case is significant in UNIX.
839 #if defined(__WXMAC__)
841 #if TARGET_API_MAC_OSX
842 #define kDefaultPathStyle kCFURLPOSIXPathStyle
844 #define kDefaultPathStyle kCFURLHFSPathStyle
847 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
850 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
851 if ( additionalPathComponent
)
853 CFURLRef parentURLRef
= fullURLRef
;
854 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
855 additionalPathComponent
,false);
856 CFRelease( parentURLRef
) ;
858 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
859 CFRelease( fullURLRef
) ;
860 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
863 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
865 OSStatus err
= noErr
;
866 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
869 if ( CFURLGetFSRef(url
, fsRef
) == false )
880 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
882 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
885 return wxMacCFStringHolder(cfname
).AsString() ;
888 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
891 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
893 return wxMacFSRefToPath( &fsRef
) ;
895 return wxEmptyString
;
898 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
900 OSStatus err
= noErr
;
902 wxMacPathToFSRef( path
, &fsRef
) ;
903 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
909 wxDos2UnixFilename (wxChar
*s
)
918 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
925 #if defined(__WXMSW__) || defined(__OS2__)
926 wxUnix2DosFilename (wxChar
*s
)
928 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
931 // Yes, I really mean this to happen under DOS only! JACS
932 #if defined(__WXMSW__) || defined(__OS2__)
943 // Concatenate two files to form third
945 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
948 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
951 FILE *fp1
wxDUMMY_INITIALIZE(NULL
);
954 // Open the inputs and outputs
955 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
956 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
957 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
969 while ((ch
= getc (fp1
)) != EOF
)
970 (void) putc (ch
, fp3
);
973 while ((ch
= getc (fp2
)) != EOF
)
974 (void) putc (ch
, fp3
);
978 bool result
= wxRenameFile(outfile
, file3
);
984 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
986 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
987 // CopyFile() copies file attributes and modification time too, so use it
988 // instead of our code if available
990 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
991 if ( !::CopyFile(file1
, file2
, !overwrite
) )
993 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
994 file1
.c_str(), file2
.c_str());
998 #elif defined(__OS2__)
999 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1004 // get permissions of file1
1005 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1007 // the file probably doesn't exist or we haven't the rights to read
1009 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1014 // open file1 for reading
1015 wxFile
fileIn(file1
, wxFile::read
);
1016 if ( !fileIn
.IsOpened() )
1019 // remove file2, if it exists. This is needed for creating
1020 // file2 with the correct permissions in the next step
1021 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1023 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1028 // reset the umask as we want to create the file with exactly the same
1029 // permissions as the original one
1032 // create file2 with the same permissions than file1 and open it for
1036 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1039 // copy contents of file1 to file2
1044 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1045 if ( fileIn
.Error() )
1052 if ( fileOut
.Write(buf
, count
) < count
)
1056 // we can expect fileIn to be closed successfully, but we should ensure
1057 // that fileOut was closed as some write errors (disk full) might not be
1058 // detected before doing this
1059 if ( !fileIn
.Close() || !fileOut
.Close() )
1062 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1063 // no chmod in VA. Should be some permission API for HPFS386 partitions
1065 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1067 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1071 #endif // OS/2 || Mac
1072 #endif // __WXMSW__ && __WIN32__
1078 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1081 // Normal system call
1082 if ( wxRename (file1
, file2
) == 0 )
1087 if (wxCopyFile(file1
, file2
)) {
1088 wxRemoveFile(file1
);
1095 bool wxRemoveFile(const wxString
& file
)
1097 #if defined(__VISUALC__) \
1098 || defined(__BORLANDC__) \
1099 || defined(__WATCOMC__) \
1100 || defined(__DMC__) \
1101 || defined(__GNUWIN32__) \
1102 || (defined(__MWERKS__) && defined(__MSL__))
1103 int res
= wxRemove(file
);
1104 #elif defined(__WXMAC__)
1105 int res
= unlink(wxFNCONV(file
));
1107 int res
= unlink(OS_FILENAME(file
));
1113 bool wxMkdir(const wxString
& dir
, int perm
)
1115 #if defined(__WXMAC__) && !defined(__UNIX__)
1116 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1118 const wxChar
*dirname
= dir
.c_str();
1120 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1121 // for the GNU compiler
1122 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1125 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1127 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1129 #elif defined(__OS2__)
1130 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1131 #elif defined(__DOS__)
1132 #if defined(__WATCOMC__)
1134 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1135 #elif defined(__DJGPP__)
1136 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1138 #error "Unsupported DOS compiler!"
1140 #else // !MSW, !DOS and !OS/2 VAC++
1143 if ( !CreateDirectory(dirname
, NULL
) )
1145 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1149 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1158 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1161 return false; //to be changed since rmdir exists in VMS7.x
1162 #elif defined(__OS2__)
1163 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1167 return (CreateDirectory(dir
, NULL
) != 0);
1169 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1175 // does the path exists? (may have or not '/' or '\\' at the end)
1176 bool wxPathExists(const wxChar
*pszPathName
)
1178 wxString
strPath(pszPathName
);
1180 #if defined(__WINDOWS__) || defined(__OS2__)
1181 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1182 // so remove all trailing backslashes from the path - but don't do this for
1183 // the pathes "d:\" (which are different from "d:") nor for just "\"
1184 while ( wxEndsWithPathSeparator(strPath
) )
1186 size_t len
= strPath
.length();
1187 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1190 strPath
.Truncate(len
- 1);
1192 #endif // __WINDOWS__
1195 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1196 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1200 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1201 // stat() can't cope with network paths
1202 DWORD ret
= ::GetFileAttributes(strPath
);
1204 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1208 #ifndef __VISAGECPP__
1209 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1211 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1212 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1215 #endif // __WIN32__/!__WIN32__
1218 // Get a temporary filename, opening and closing the file.
1219 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1221 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1222 if ( filename
.empty() )
1226 wxStrcpy(buf
, filename
);
1228 buf
= MYcopystring(filename
);
1233 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1235 buf
= wxFileName::CreateTempFileName(prefix
);
1237 return !buf
.empty();
1240 // Get first file name matching given wild card.
1242 static wxDir
*gs_dir
= NULL
;
1243 static wxString gs_dirPath
;
1245 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1247 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1248 if ( gs_dirPath
.IsEmpty() )
1249 gs_dirPath
= wxT(".");
1250 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1251 gs_dirPath
<< wxFILE_SEP_PATH
;
1255 gs_dir
= new wxDir(gs_dirPath
);
1257 if ( !gs_dir
->IsOpened() )
1259 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1260 return wxEmptyString
;
1266 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1267 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1268 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1272 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1273 if ( result
.IsEmpty() )
1279 return gs_dirPath
+ result
;
1282 wxString
wxFindNextFile()
1284 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1287 gs_dir
->GetNext(&result
);
1289 if ( result
.IsEmpty() )
1295 return gs_dirPath
+ result
;
1299 // Get current working directory.
1300 // If buf is NULL, allocates space using new, else
1302 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1309 buf
= new wxChar
[sz
+ 1];
1312 bool ok
wxDUMMY_INITIALIZE(false);
1314 // for the compilers which have Unicode version of _getcwd(), call it
1315 // directly, for the others call the ANSI version and do the translation
1318 #else // wxUSE_UNICODE
1319 bool needsANSI
= true;
1321 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1322 // This is not legal code as the compiler
1323 // is allowed destroy the wxCharBuffer.
1324 // wxCharBuffer c_buffer(sz);
1325 // char *cbuf = (char*)(const char*)c_buffer;
1326 char cbuf
[_MAXPATHLEN
];
1330 #if wxUSE_UNICODE_MSLU
1331 if ( wxGetOsVersion() != wxWIN95
)
1333 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1336 ok
= _wgetcwd(buf
, sz
) != NULL
;
1342 #endif // wxUSE_UNICODE
1344 #if defined(_MSC_VER) || defined(__MINGW32__)
1345 ok
= _getcwd(cbuf
, sz
) != NULL
;
1346 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1348 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1350 wxString
res( lbuf
, *wxConvCurrent
) ;
1351 wxStrcpy( buf
, res
) ;
1356 #elif defined(__OS2__)
1358 ULONG ulDriveNum
= 0;
1359 ULONG ulDriveMap
= 0;
1360 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1365 rc
= ::DosQueryCurrentDir( 0 // current drive
1369 cbuf
[0] = 'A' + (ulDriveNum
- 1);
1374 #else // !Win32/VC++ !Mac !OS2
1375 ok
= getcwd(cbuf
, sz
) != NULL
;
1378 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1379 // finally convert the result to Unicode if needed
1380 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1381 #endif // wxUSE_UNICODE
1386 wxLogSysError(_("Failed to get the working directory"));
1388 // VZ: the old code used to return "." on error which didn't make any
1389 // sense at all to me - empty string is a better error indicator
1390 // (NULL might be even better but I'm afraid this could lead to
1391 // problems with the old code assuming the return is never NULL)
1394 else // ok, but we might need to massage the path into the right format
1397 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1398 // with / deliminers. We don't like that.
1399 for (wxChar
*ch
= buf
; *ch
; ch
++)
1401 if (*ch
== wxT('/'))
1406 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1407 // he needs Unix as opposed to Win32 pathnames
1408 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1409 // another example of DOS/Unix mix (Cygwin)
1410 wxString pathUnix
= buf
;
1411 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1412 #endif // __CYGWIN__
1427 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1428 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1429 wxString
str( buffer
);
1435 bool wxSetWorkingDirectory(const wxString
& d
)
1437 #if defined(__OS2__)
1438 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1439 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1440 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1441 #elif defined(__WINDOWS__)
1445 // No equivalent in WinCE
1448 return (bool)(SetCurrentDirectory(d
) != 0);
1451 // Must change drive, too.
1452 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1455 wxChar firstChar
= d
[0];
1459 firstChar
= firstChar
- 32;
1461 // To a drive number
1462 unsigned int driveNo
= firstChar
- 64;
1465 unsigned int noDrives
;
1466 _dos_setdrive(driveNo
, &noDrives
);
1469 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1477 // Get the OS directory if appropriate (such as the Windows directory).
1478 // On non-Windows platform, probably just return the empty string.
1479 wxString
wxGetOSDirectory()
1482 return wxString(wxT("\\Windows"));
1483 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1485 GetWindowsDirectory(buf
, 256);
1486 return wxString(buf
);
1487 #elif defined(__WXMAC__)
1488 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1490 return wxEmptyString
;
1494 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1496 size_t len
= wxStrlen(pszFileName
);
1498 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1501 // find a file in a list of directories, returns false if not found
1502 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1504 // we assume that it's not empty
1505 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1506 _T("empty file name in wxFindFileInPath"));
1508 // skip path separator in the beginning of the file name if present
1509 if ( wxIsPathSeparator(*pszFile
) )
1512 // copy the path (strtok will modify it)
1513 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1514 wxStrcpy(szPath
, pszPath
);
1517 wxChar
*pc
, *save_ptr
;
1518 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1520 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1522 // search for the file in this directory
1524 if ( !wxEndsWithPathSeparator(pc
) )
1525 strFile
+= wxFILE_SEP_PATH
;
1528 if ( wxFileExists(strFile
) ) {
1534 // suppress warning about unused variable save_ptr when wxStrtok() is a
1535 // macro which throws away its third argument
1540 return pc
!= NULL
; // if true => we breaked from the loop
1543 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1548 // it can be empty, but it shouldn't be NULL
1549 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1551 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1554 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1557 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1558 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1559 0, FILE_ATTRIBUTE_NORMAL
, 0);
1560 if (fileHandle
== INVALID_HANDLE_VALUE
)
1564 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1566 CloseHandle(fileHandle
);
1568 wxDateTime dateTime
;
1570 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1572 wxLogLastError(_T("FileTimeToLocalFileTime"));
1576 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1578 wxLogLastError(_T("FileTimeToSystemTime"));
1581 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1582 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1583 return dateTime
.GetTicks();
1590 wxStat( filename
, &buf
);
1592 return buf
.st_mtime
;
1597 // Parses the filterStr, returning the number of filters.
1598 // Returns 0 if none or if there's a problem.
1599 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1601 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
, wxArrayString
& descriptions
, wxArrayString
& filters
)
1603 descriptions
.Clear();
1606 wxString
str(filterStr
);
1608 wxString description
, filter
;
1610 while( pos
!= wxNOT_FOUND
)
1612 pos
= str
.Find(wxT('|'));
1613 if ( pos
== wxNOT_FOUND
)
1615 // if there are no '|'s at all in the string just take the entire
1616 // string as filter and make description empty for later autocompletion
1617 if ( filters
.IsEmpty() )
1619 descriptions
.Add(wxEmptyString
);
1620 filters
.Add(filterStr
);
1624 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1630 description
= str
.Left(pos
);
1631 str
= str
.Mid(pos
+ 1);
1632 pos
= str
.Find(wxT('|'));
1633 if ( pos
== wxNOT_FOUND
)
1639 filter
= str
.Left(pos
);
1640 str
= str
.Mid(pos
+ 1);
1643 descriptions
.Add(description
);
1644 filters
.Add(filter
);
1647 #if defined(__WXMOTIF__)
1648 // split it so there is one wildcard per entry
1649 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1651 pos
= filters
[i
].Find(wxT(';'));
1652 if (pos
!= wxNOT_FOUND
)
1654 // first split only filters
1655 descriptions
.Insert(descriptions
[i
],i
+1);
1656 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1657 filters
[i
]=filters
[i
].Left(pos
);
1659 // autoreplace new filter in description with pattern:
1660 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1661 // cause split into:
1662 // C/C++ Files(*.cpp)|*.cpp
1663 // C/C++ Files(*.c;*.h)|*.c;*.h
1664 // and next iteration cause another split into:
1665 // C/C++ Files(*.cpp)|*.cpp
1666 // C/C++ Files(*.c)|*.c
1667 // C/C++ Files(*.h)|*.h
1668 for ( size_t k
=i
;k
<i
+2;k
++ )
1670 pos
= descriptions
[k
].Find(filters
[k
]);
1671 if (pos
!= wxNOT_FOUND
)
1673 wxString before
= descriptions
[k
].Left(pos
);
1674 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1675 pos
= before
.Find(_T('('),true);
1676 if (pos
>before
.Find(_T(')'),true))
1678 before
= before
.Left(pos
+1);
1679 before
<< filters
[k
];
1680 pos
= after
.Find(_T(')'));
1681 int pos1
= after
.Find(_T('('));
1682 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1684 before
<< after
.Mid(pos
);
1685 descriptions
[k
] = before
;
1695 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1697 if ( descriptions
[j
] == wxEmptyString
&& filters
[j
] != wxEmptyString
)
1699 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1703 return filters
.GetCount();
1707 //------------------------------------------------------------------------
1708 // wild character routines
1709 //------------------------------------------------------------------------
1711 bool wxIsWild( const wxString
& pattern
)
1713 wxString tmp
= pattern
;
1714 wxChar
*pat
= WXSTRINGCAST(tmp
);
1719 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1730 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1732 * The match procedure is public domain code (from ircII's reg.c)
1735 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1739 /* Match if both are empty. */
1743 const wxChar
*m
= pat
.c_str(),
1754 if (dot_special
&& (*n
== wxT('.')))
1756 /* Never match so that hidden Unix files
1757 * are never found. */
1771 else if (*m
== wxT('?'))
1779 if (*m
== wxT('\\'))
1782 /* Quoting "nothing" is a bad thing */
1789 * If we are out of both strings or we just
1790 * saw a wildcard, then we can say we have a
1801 * We could check for *n == NULL at this point, but
1802 * since it's more common to have a character there,
1803 * check to see if they match first (m and n) and
1804 * then if they don't match, THEN we can check for
1822 * If there are no more characters in the
1823 * string, but we still need to find another
1824 * character (*m != NULL), then it will be
1825 * impossible to match it
1832 if (*np
== wxT(' '))
1858 #pragma warning(default:4706) // assignment within conditional expression