1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filefn.cpp
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 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #include "wx/filefn.h"
36 #include "wx/dynarray.h"
38 #include "wx/filename.h"
41 #include "wx/tokenzr.h"
43 // there are just too many of those...
45 #pragma warning(disable:4706) // assignment within conditional expression
52 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
53 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
58 #if defined(__WXMAC__)
59 #include "wx/mac/private.h" // includes mac headers
63 #include "wx/msw/private.h"
64 #include "wx/msw/mslu.h"
66 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
68 // note that it must be included after <windows.h>
71 #include <sys/cygwin.h>
73 #endif // __GNUWIN32__
75 // io.h is needed for _get_osfhandle()
76 // Already included by filefn.h for many Windows compilers
77 #if defined __MWERKS__ || defined __CYGWIN__
86 // TODO: Borland probably has _wgetcwd as well?
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
96 #define _MAXPATHLEN 1024
100 // # include "MoreFilesX.h"
103 // ----------------------------------------------------------------------------
105 // ----------------------------------------------------------------------------
107 // MT-FIXME: get rid of this horror and all code using it
108 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
110 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
112 // VisualAge C++ V4.0 cannot have any external linkage const decs
113 // in headers included by more than one primary source
115 const int wxInvalidOffset
= -1;
118 // ----------------------------------------------------------------------------
120 // ----------------------------------------------------------------------------
122 // translate the filenames before passing them to OS functions
123 #define OS_FILENAME(s) (s.fn_str())
125 // ============================================================================
127 // ============================================================================
129 // ----------------------------------------------------------------------------
130 // wrappers around standard POSIX functions
131 // ----------------------------------------------------------------------------
133 #if wxUSE_UNICODE && defined __BORLANDC__ \
134 && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
136 // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
137 // regardless of the mode parameter. This hack works around the problem by
138 // setting the mode with _wchmod.
140 int wxCRT_Open(const wchar_t *pathname
, int flags
, mode_t mode
)
144 // we only want to fix the mode when the file is actually created, so
145 // when creating first try doing it O_EXCL so we can tell if the file
146 // was already there.
147 if ((flags
& O_CREAT
) && !(flags
& O_EXCL
) && (mode
& wxS_IWUSR
) != 0)
150 int fd
= _wopen(pathname
, flags
| moreflags
, mode
);
152 // the file was actually created and needs fixing
153 if (fd
!= -1 && (flags
& O_CREAT
) != 0 && (mode
& wxS_IWUSR
) != 0)
156 _wchmod(pathname
, mode
);
157 fd
= _wopen(pathname
, flags
& ~(O_EXCL
| O_CREAT
));
159 // the open failed, but it may have been because the added O_EXCL stopped
160 // the opening of an existing file, so try again without.
161 else if (fd
== -1 && moreflags
!= 0)
163 fd
= _wopen(pathname
, flags
& ~O_CREAT
);
171 // ----------------------------------------------------------------------------
173 // ----------------------------------------------------------------------------
175 bool wxPathList::Add(const wxString
& path
)
177 // add a path separator to force wxFileName to interpret it always as a directory
178 // (i.e. if we are called with '/home/user' we want to consider it a folder and
179 // not, as wxFileName would consider, a filename).
180 wxFileName
fn(path
+ wxFileName::GetPathSeparator());
182 // add only normalized relative/absolute paths
183 // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
184 // normalize paths which starts with ".." (which can be normalized only if
185 // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
186 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
189 wxString toadd
= fn
.GetPath();
190 if (Index(toadd
) == wxNOT_FOUND
)
191 wxArrayString::Add(toadd
); // do not add duplicates
196 void wxPathList::Add(const wxArrayString
&arr
)
198 for (size_t j
=0; j
< arr
.GetCount(); j
++)
202 // Add paths e.g. from the PATH environment variable
203 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
205 // No environment variables on WinCE
208 // The space has been removed from the tokenizers, otherwise a
209 // path such as "C:\Program Files" would be split into 2 paths:
210 // "C:\Program" and "Files"; this is true for both Windows and Unix.
212 static const wxChar PATH_TOKS
[] =
213 #if defined(__WINDOWS__) || defined(__OS2__)
214 wxT(";"); // Don't separate with colon in DOS (used for drive)
220 if ( wxGetEnv(envVariable
, &val
) )
222 // split into an array of string the value of the env var
223 wxArrayString arr
= wxStringTokenize(val
, PATH_TOKS
);
224 WX_APPEND_ARRAY(*this, arr
);
226 #endif // !__WXWINCE__
229 // Given a full filename (with path), ensure that that file can
230 // be accessed again USING FILENAME ONLY by adding the path
231 // to the list if not already there.
232 bool wxPathList::EnsureFileAccessible (const wxString
& path
)
234 return Add(wxPathOnly(path
));
237 #if WXWIN_COMPATIBILITY_2_6
238 bool wxPathList::Member (const wxString
& path
) const
240 return Index(path
) != wxNOT_FOUND
;
244 wxString
wxPathList::FindValidPath (const wxString
& file
) const
246 // normalize the given string as it could be a path + a filename
247 // and not only a filename
251 // NB: normalize without making absolute otherwise calling this function with
252 // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
253 // below would only add to the paths of this list the 'c.txt' part when doing
254 // the existence checks...
255 // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
256 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
257 return wxEmptyString
;
259 wxASSERT_MSG(!fn
.IsDir(), wxT("Cannot search for directories; only for files"));
261 strend
= fn
.GetFullName(); // search for the file name and ignore the path part
263 strend
= fn
.GetFullPath();
265 for (size_t i
=0; i
<GetCount(); i
++)
267 wxString strstart
= Item(i
);
268 if (!strstart
.IsEmpty() && strstart
.Last() != wxFileName::GetPathSeparator())
269 strstart
+= wxFileName::GetPathSeparator();
271 if (wxFileExists(strstart
+ strend
))
272 return strstart
+ strend
; // Found!
275 return wxEmptyString
; // Not found
278 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
) const
280 wxString f
= FindValidPath(file
);
281 if ( f
.empty() || wxIsAbsolutePath(f
) )
284 wxString buf
= ::wxGetCwd();
286 if ( !wxEndsWithPathSeparator(buf
) )
288 buf
+= wxFILE_SEP_PATH
;
295 // ----------------------------------------------------------------------------
296 // miscellaneous global functions (TOFIX!)
297 // ----------------------------------------------------------------------------
299 static inline wxChar
* MYcopystring(const wxString
& s
)
301 wxChar
* copy
= new wxChar
[s
.length() + 1];
302 return wxStrcpy(copy
, s
.c_str());
305 template<typename CharType
>
306 static inline CharType
* MYcopystring(const CharType
* s
)
308 CharType
* copy
= new CharType
[wxStrlen(s
) + 1];
309 return wxStrcpy(copy
, s
);
314 wxFileExists (const wxString
& filename
)
316 #if defined(__WXPALMOS__)
318 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
319 // we must use GetFileAttributes() instead of the ANSI C functions because
320 // it can cope with network (UNC) paths unlike them
321 DWORD ret
= ::GetFileAttributes(filename
.fn_str());
323 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
326 #define S_ISREG(mode) ((mode) & S_IFREG)
329 #ifndef wxNEED_WX_UNISTD_H
330 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
332 || (errno
== EACCES
) // if access is denied something with that name
333 // exists and is opened in exclusive mode.
337 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
339 #endif // __WIN32__/!__WIN32__
343 wxIsAbsolutePath (const wxString
& filename
)
345 if (!filename
.empty())
347 // Unix like or Windows
348 if (filename
[0] == wxT('/'))
351 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
354 #if defined(__WINDOWS__) || defined(__OS2__)
356 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
364 * Strip off any extension (dot something) from end of file,
365 * IF one exists. Inserts zero into buffer.
370 static void wxDoStripExtension(T
*buffer
)
372 int len
= wxStrlen(buffer
);
376 if (buffer
[i
] == wxT('.'))
385 void wxStripExtension(char *buffer
) { wxDoStripExtension(buffer
); }
386 void wxStripExtension(wchar_t *buffer
) { wxDoStripExtension(buffer
); }
388 void wxStripExtension(wxString
& buffer
)
390 //RN: Be careful about the handling the case where
391 //buffer.length() == 0
392 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
394 if (buffer
.GetChar(i
) == wxT('.'))
396 buffer
= buffer
.Left(i
);
402 // Destructive removal of /./ and /../ stuff
403 template<typename CharType
>
404 static CharType
*wxDoRealPath (CharType
*path
)
407 static const CharType SEP
= wxT('\\');
408 wxUnix2DosFilename(path
);
410 static const CharType SEP
= wxT('/');
412 if (path
[0] && path
[1]) {
413 /* MATTHEW: special case "/./x" */
415 if (path
[2] == SEP
&& path
[1] == wxT('.'))
423 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
426 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
431 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
432 && (q
- 1 <= path
|| q
[-1] != SEP
))
435 if (path
[0] == wxT('\0'))
440 #if defined(__WXMSW__) || defined(__OS2__)
441 /* Check that path[2] is NULL! */
442 else if (path
[1] == wxT(':') && !path
[2])
451 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
459 char *wxRealPath(char *path
)
461 return wxDoRealPath(path
);
464 wchar_t *wxRealPath(wchar_t *path
)
466 return wxDoRealPath(path
);
469 wxString
wxRealPath(const wxString
& path
)
471 wxChar
*buf1
=MYcopystring(path
);
472 wxChar
*buf2
=wxRealPath(buf1
);
480 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
482 if (filename
.empty())
483 return (wxChar
*) NULL
;
485 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
487 wxString buf
= ::wxGetCwd();
488 wxChar ch
= buf
.Last();
490 if (ch
!= wxT('\\') && ch
!= wxT('/'))
496 buf
<< wxFileFunctionsBuffer
;
497 buf
= wxRealPath( buf
);
498 return MYcopystring( buf
);
500 return MYcopystring( wxFileFunctionsBuffer
);
506 ~user/ => user's home dir
507 If the environment variable a = "foo" and b = "bar" then:
524 /* input name in name, pathname output to buf. */
526 template<typename CharType
>
527 static CharType
*wxDoExpandPath(CharType
*buf
, const wxString
& name
)
529 register CharType
*d
, *s
, *nm
;
530 CharType lnm
[_MAXPATHLEN
];
533 // Some compilers don't like this line.
534 // const CharType trimchars[] = wxT("\n \t");
536 CharType trimchars
[4];
537 trimchars
[0] = wxT('\n');
538 trimchars
[1] = wxT(' ');
539 trimchars
[2] = wxT('\t');
543 const CharType SEP
= wxT('\\');
545 const CharType SEP
= wxT('/');
550 nm
= ::MYcopystring(static_cast<const CharType
*>(name
.c_str())); // Make a scratch copy
551 CharType
*nm_tmp
= nm
;
553 /* Skip leading whitespace and cr */
554 while (wxStrchr(trimchars
, *nm
) != NULL
)
556 /* And strip off trailing whitespace and cr */
557 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
558 while (q
-- && wxStrchr(trimchars
, *s
) != NULL
)
566 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
569 /* Expand inline environment variables */
587 while ((*d
++ = *s
) != 0) {
589 if (*s
== wxT('\\')) {
590 if ((*(d
- 1) = *++s
)!=0) {
598 // No env variables on WinCE
601 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
603 if (*s
++ == wxT('$'))
606 register CharType
*start
= d
;
607 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
608 register CharType
*value
;
609 while ((*d
++ = *s
) != 0)
610 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
615 value
= wxGetenv(braces
? start
+ 1 : start
);
617 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
631 /* Expand ~ and ~user */
634 if (nm
[0] == wxT('~') && !q
)
637 if (nm
[1] == SEP
|| nm
[1] == 0)
639 homepath
= wxGetUserHome(wxEmptyString
);
640 if (!homepath
.empty()) {
641 s
= (CharType
*)(const CharType
*)homepath
.c_str();
646 { /* ~user/filename */
647 register CharType
*nnm
;
648 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
652 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
653 was_sep
= (*s
== SEP
);
654 nnm
= *s
? s
+ 1 : s
;
656 homepath
= wxGetUserHome(wxString(nm
+ 1));
657 if (homepath
.empty())
659 if (was_sep
) /* replace only if it was there: */
666 s
= (CharType
*)(const CharType
*)homepath
.c_str();
672 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
674 while (wxT('\0') != (*d
++ = *s
++))
677 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
681 while ((*d
++ = *s
++) != 0)
685 delete[] nm_tmp
; // clean up alloc
686 /* Now clean up the buffer */
687 return wxRealPath(buf
);
690 char *wxExpandPath(char *buf
, const wxString
& name
)
692 return wxDoExpandPath(buf
, name
);
695 wchar_t *wxExpandPath(wchar_t *buf
, const wxString
& name
)
697 return wxDoExpandPath(buf
, name
);
701 /* Contract Paths to be build upon an environment variable
704 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
706 The call wxExpandPath can convert these back!
709 wxContractPath (const wxString
& filename
,
710 const wxString
& WXUNUSED_IN_WINCE(envname
),
711 const wxString
& user
)
713 static wxChar dest
[_MAXPATHLEN
];
715 if (filename
.empty())
716 return (wxChar
*) NULL
;
718 wxStrcpy (dest
, filename
);
720 wxUnix2DosFilename(dest
);
723 // Handle environment
727 if (!envname
.empty() && !(val
= wxGetenv (envname
)).empty() &&
728 (tcp
= wxStrstr (dest
, val
)) != NULL
)
730 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ val
.length());
733 wxStrcpy (tcp
, envname
);
734 wxStrcat (tcp
, wxT("}"));
735 wxStrcat (tcp
, wxFileFunctionsBuffer
);
739 // Handle User's home (ignore root homes!)
740 val
= wxGetUserHome (user
);
744 const size_t len
= val
.length();
748 if (wxStrncmp(dest
, val
, len
) == 0)
750 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
752 wxStrcat(wxFileFunctionsBuffer
, user
);
753 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
754 wxStrcpy (dest
, wxFileFunctionsBuffer
);
760 // Return just the filename, not the path (basename)
761 wxChar
*wxFileNameFromPath (wxChar
*path
)
764 wxString n
= wxFileNameFromPath(p
);
766 return path
+ p
.length() - n
.length();
769 wxString
wxFileNameFromPath (const wxString
& path
)
772 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
774 wxString fullname
= name
;
777 fullname
<< wxFILE_SEP_EXT
<< ext
;
783 // Return just the directory, or NULL if no directory
785 wxPathOnly (wxChar
*path
)
789 static wxChar buf
[_MAXPATHLEN
];
792 wxStrcpy (buf
, path
);
794 int l
= wxStrlen(path
);
797 // Search backward for a backward or forward slash
800 // Unix like or Windows
801 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
807 if (path
[i
] == wxT(']'))
816 #if defined(__WXMSW__) || defined(__OS2__)
817 // Try Drive specifier
818 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
820 // A:junk --> A:. (since A:.\junk Not A:\junk)
827 return (wxChar
*) NULL
;
830 // Return just the directory, or NULL if no directory
831 wxString
wxPathOnly (const wxString
& path
)
835 wxChar buf
[_MAXPATHLEN
];
840 int l
= path
.length();
843 // Search backward for a backward or forward slash
846 // Unix like or Windows
847 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
849 // Don't return an empty string
853 return wxString(buf
);
856 if (path
[i
] == wxT(']'))
859 return wxString(buf
);
865 #if defined(__WXMSW__) || defined(__OS2__)
866 // Try Drive specifier
867 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
869 // A:junk --> A:. (since A:.\junk Not A:\junk)
872 return wxString(buf
);
876 return wxEmptyString
;
879 // Utility for converting delimiters in DOS filenames to UNIX style
880 // and back again - or we get nasty problems with delimiters.
881 // Also, convert to lower case, since case is significant in UNIX.
883 #if defined(__WXMAC__)
885 #define kDefaultPathStyle kCFURLPOSIXPathStyle
887 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
890 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
891 if ( additionalPathComponent
)
893 CFURLRef parentURLRef
= fullURLRef
;
894 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
895 additionalPathComponent
,false);
896 CFRelease( parentURLRef
) ;
898 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
899 CFRelease( fullURLRef
) ;
900 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
901 CFRelease( cfString
);
902 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
903 return wxMacCFStringHolder(cfMutableString
).AsString();
906 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
908 OSStatus err
= noErr
;
909 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxMacCFStringHolder(path
));
910 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
911 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
912 CFRelease( cfMutableString
);
915 if ( CFURLGetFSRef(url
, fsRef
) == false )
926 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
928 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
931 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
933 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
934 return wxMacCFStringHolder(cfMutableString
).AsString() ;
939 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
942 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
944 return wxMacFSRefToPath( &fsRef
) ;
946 return wxEmptyString
;
949 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
951 OSStatus err
= noErr
;
953 wxMacPathToFSRef( path
, &fsRef
);
954 err
= FSGetCatalogInfo(&fsRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
962 static void wxDoDos2UnixFilename(T
*s
)
971 *s
= wxTolower(*s
); // Case INDEPENDENT
977 void wxDos2UnixFilename(char *s
) { wxDoDos2UnixFilename(s
); }
978 void wxDos2UnixFilename(wchar_t *s
) { wxDoDos2UnixFilename(s
); }
982 #if defined(__WXMSW__) || defined(__OS2__)
983 wxDoUnix2DosFilename(T
*s
)
985 wxDoUnix2DosFilename(T
*WXUNUSED(s
) )
988 // Yes, I really mean this to happen under DOS only! JACS
989 #if defined(__WXMSW__) || defined(__OS2__)
1000 void wxUnix2DosFilename(char *s
) { wxDoUnix2DosFilename(s
); }
1001 void wxUnix2DosFilename(wchar_t *s
) { wxDoUnix2DosFilename(s
); }
1003 // Concatenate two files to form third
1005 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1009 wxFile
in1(file1
), in2(file2
);
1010 wxTempFile
out(file3
);
1012 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
1016 unsigned char buf
[1024];
1018 for( int i
=0; i
<2; i
++)
1020 wxFile
*in
= i
==0 ? &in1
: &in2
;
1022 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
1024 if ( !out
.Write(buf
,ofs
) )
1026 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1029 return out
.Commit();
1041 // helper of generic implementation of wxCopyFile()
1042 #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1046 wxDoCopyFile(wxFile
& fileIn
,
1047 const wxStructStat
& fbuf
,
1048 const wxString
& filenameDst
,
1051 // reset the umask as we want to create the file with exactly the same
1052 // permissions as the original one
1055 // create file2 with the same permissions than file1 and open it for
1059 if ( !fileOut
.Create(filenameDst
, overwrite
, fbuf
.st_mode
& 0777) )
1062 // copy contents of file1 to file2
1066 ssize_t count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1067 if ( count
== wxInvalidOffset
)
1074 if ( fileOut
.Write(buf
, count
) < (size_t)count
)
1078 // we can expect fileIn to be closed successfully, but we should ensure
1079 // that fileOut was closed as some write errors (disk full) might not be
1080 // detected before doing this
1081 return fileIn
.Close() && fileOut
.Close();
1084 #endif // generic implementation of wxCopyFile
1088 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1090 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1091 // CopyFile() copies file attributes and modification time too, so use it
1092 // instead of our code if available
1094 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1095 if ( !::CopyFile(file1
.fn_str(), file2
.fn_str(), !overwrite
) )
1097 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1098 file1
.c_str(), file2
.c_str());
1102 #elif defined(__OS2__)
1103 if ( ::DosCopy(file1
.c_str(), file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1105 #elif defined(__PALMOS__)
1106 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1108 #elif wxUSE_FILE // !Win32
1111 // get permissions of file1
1112 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1114 // the file probably doesn't exist or we haven't the rights to read
1116 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1121 // open file1 for reading
1122 wxFile
fileIn(file1
, wxFile::read
);
1123 if ( !fileIn
.IsOpened() )
1126 // remove file2, if it exists. This is needed for creating
1127 // file2 with the correct permissions in the next step
1128 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1130 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1135 wxDoCopyFile(fileIn
, fbuf
, file2
, overwrite
);
1137 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1138 // copy the resource fork of the file too if it's present
1139 wxString pathRsrcOut
;
1143 // suppress error messages from this block as resource forks don't have
1147 // it's not enough to check for file existence: it always does on HFS
1148 // but is empty for files without resources
1149 if ( fileRsrcIn
.Open(file1
+ wxT("/..namedfork/rsrc")) &&
1150 fileRsrcIn
.Length() > 0 )
1152 // we must be using HFS or another filesystem with resource fork
1153 // support, suppose that destination file system also is HFS[-like]
1154 pathRsrcOut
= file2
+ wxT("/..namedfork/rsrc");
1156 else // check if we have resource fork in separate file (non-HFS case)
1158 wxFileName
fnRsrc(file1
);
1159 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1162 if ( fileRsrcIn
.Open( fnRsrc
.GetFullPath() ) )
1165 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1167 pathRsrcOut
= fnRsrc
.GetFullPath();
1172 if ( !pathRsrcOut
.empty() )
1174 if ( !wxDoCopyFile(fileRsrcIn
, fbuf
, pathRsrcOut
, overwrite
) )
1177 #endif // wxMac || wxCocoa
1179 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1180 // no chmod in VA. Should be some permission API for HPFS386 partitions
1182 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1184 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1188 #endif // OS/2 || Mac
1190 #else // !Win32 && ! wxUSE_FILE
1192 // impossible to simulate with wxWidgets API
1195 wxUnusedVar(overwrite
);
1198 #endif // __WXMSW__ && __WIN32__
1204 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1206 if ( !overwrite
&& wxFileExists(file2
) )
1210 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1211 file1
.c_str(), file2
.c_str()
1217 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1218 // Normal system call
1219 if ( wxRename (file1
, file2
) == 0 )
1224 if (wxCopyFile(file1
, file2
, overwrite
)) {
1225 wxRemoveFile(file1
);
1232 bool wxRemoveFile(const wxString
& file
)
1234 #if defined(__VISUALC__) \
1235 || defined(__BORLANDC__) \
1236 || defined(__WATCOMC__) \
1237 || defined(__DMC__) \
1238 || defined(__GNUWIN32__) \
1239 || (defined(__MWERKS__) && defined(__MSL__))
1240 int res
= wxRemove(file
);
1241 #elif defined(__WXMAC__)
1242 int res
= unlink(file
.fn_str());
1243 #elif defined(__WXPALMOS__)
1245 // TODO with VFSFileDelete()
1247 int res
= unlink(OS_FILENAME(file
));
1253 bool wxMkdir(const wxString
& dir
, int perm
)
1255 #if defined(__WXPALMOS__)
1257 #elif defined(__WXMAC__) && !defined(__UNIX__)
1258 return (mkdir(dir
.fn_str() , 0 ) == 0);
1260 const wxChar
*dirname
= dir
.c_str();
1262 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1263 // for the GNU compiler
1264 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1267 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1269 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1271 #elif defined(__OS2__)
1273 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1274 #elif defined(__DOS__)
1275 #if defined(__WATCOMC__)
1277 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1278 #elif defined(__DJGPP__)
1279 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1281 #error "Unsupported DOS compiler!"
1283 #else // !MSW, !DOS and !OS/2 VAC++
1286 if ( !CreateDirectory(dirname
, NULL
) )
1288 if ( wxMkDir(dir
.fn_str()) != 0 )
1292 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1301 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1303 #if defined(__VMS__)
1304 return false; //to be changed since rmdir exists in VMS7.x
1305 #elif defined(__OS2__)
1306 return (::DosDeleteDir(dir
.c_str()) == 0);
1307 #elif defined(__WXWINCE__)
1308 return (RemoveDirectory(dir
) != 0);
1309 #elif defined(__WXPALMOS__)
1310 // TODO with VFSFileRename()
1313 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1317 // does the path exists? (may have or not '/' or '\\' at the end)
1318 bool wxDirExists(const wxString
& pathName
)
1320 wxString
strPath(pathName
);
1322 #if defined(__WINDOWS__) || defined(__OS2__)
1323 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1324 // so remove all trailing backslashes from the path - but don't do this for
1325 // the paths "d:\" (which are different from "d:") nor for just "\"
1326 while ( wxEndsWithPathSeparator(strPath
) )
1328 size_t len
= strPath
.length();
1329 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1332 strPath
.Truncate(len
- 1);
1334 #endif // __WINDOWS__
1337 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1338 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1342 #if defined(__WXPALMOS__)
1344 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1345 // stat() can't cope with network paths
1346 DWORD ret
= ::GetFileAttributes(strPath
.fn_str());
1348 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1349 #elif defined(__OS2__)
1350 FILESTATUS3 Info
= {{0}};
1351 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1352 (void*) &Info
, sizeof(FILESTATUS3
));
1354 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1355 (rc
== ERROR_SHARING_VIOLATION
);
1356 // If we got a sharing violation, there must be something with this name.
1360 #ifndef __VISAGECPP__
1361 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1363 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1364 return wxStat(strPath
.c_str(), &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1367 #endif // __WIN32__/!__WIN32__
1370 // Get a temporary filename, opening and closing the file.
1371 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1374 if ( !wxGetTempFileName(prefix
, filename
) )
1378 wxStrcpy(buf
, filename
);
1380 buf
= MYcopystring(filename
);
1385 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1388 buf
= wxFileName::CreateTempFileName(prefix
);
1390 return !buf
.empty();
1391 #else // !wxUSE_FILE
1392 wxUnusedVar(prefix
);
1396 #endif // wxUSE_FILE/!wxUSE_FILE
1399 // Get first file name matching given wild card.
1401 static wxDir
*gs_dir
= NULL
;
1402 static wxString gs_dirPath
;
1404 wxString
wxFindFirstFile(const wxString
& spec
, int flags
)
1406 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1407 if ( gs_dirPath
.empty() )
1408 gs_dirPath
= wxT(".");
1409 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1410 gs_dirPath
<< wxFILE_SEP_PATH
;
1414 gs_dir
= new wxDir(gs_dirPath
);
1416 if ( !gs_dir
->IsOpened() )
1418 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1419 return wxEmptyString
;
1425 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1426 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1427 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1431 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1432 if ( result
.empty() )
1438 return gs_dirPath
+ result
;
1441 wxString
wxFindNextFile()
1443 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1446 gs_dir
->GetNext(&result
);
1448 if ( result
.empty() )
1454 return gs_dirPath
+ result
;
1458 // Get current working directory.
1459 // If buf is NULL, allocates space using new, else copies into buf.
1460 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1461 // wxDoGetCwd() is their common core to be moved
1462 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1463 // Do not expose wxDoGetCwd in headers!
1465 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1467 #if defined(__WXPALMOS__)
1469 if(buf
&& sz
>0) buf
[0] = _T('\0');
1471 #elif defined(__WXWINCE__)
1473 if(buf
&& sz
>0) buf
[0] = _T('\0');
1478 buf
= new wxChar
[sz
+ 1];
1481 bool ok
wxDUMMY_INITIALIZE(false);
1483 // for the compilers which have Unicode version of _getcwd(), call it
1484 // directly, for the others call the ANSI version and do the translation
1487 #else // wxUSE_UNICODE
1488 bool needsANSI
= true;
1490 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1491 char cbuf
[_MAXPATHLEN
];
1495 #if wxUSE_UNICODE_MSLU
1496 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1498 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1501 ok
= _wgetcwd(buf
, sz
) != NULL
;
1507 #endif // wxUSE_UNICODE
1509 #if defined(_MSC_VER) || defined(__MINGW32__)
1510 ok
= _getcwd(cbuf
, sz
) != NULL
;
1511 #elif defined(__OS2__)
1513 ULONG ulDriveNum
= 0;
1514 ULONG ulDriveMap
= 0;
1515 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1520 rc
= ::DosQueryCurrentDir( 0 // current drive
1524 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1529 #else // !Win32/VC++ !Mac !OS2
1530 ok
= getcwd(cbuf
, sz
) != NULL
;
1534 // finally convert the result to Unicode if needed
1535 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1536 #endif // wxUSE_UNICODE
1541 wxLogSysError(_("Failed to get the working directory"));
1543 // VZ: the old code used to return "." on error which didn't make any
1544 // sense at all to me - empty string is a better error indicator
1545 // (NULL might be even better but I'm afraid this could lead to
1546 // problems with the old code assuming the return is never NULL)
1549 else // ok, but we might need to massage the path into the right format
1552 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1553 // with / deliminers. We don't like that.
1554 for (wxChar
*ch
= buf
; *ch
; ch
++)
1556 if (*ch
== wxT('/'))
1561 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1562 // he needs Unix as opposed to Win32 pathnames
1563 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1564 // another example of DOS/Unix mix (Cygwin)
1565 wxString pathUnix
= buf
;
1567 char bufA
[_MAXPATHLEN
];
1568 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1569 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1571 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1572 #endif // wxUSE_UNICODE
1573 #endif // __CYGWIN__
1586 #if WXWIN_COMPATIBILITY_2_6
1587 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1589 return wxDoGetCwd(buf
,sz
);
1591 #endif // WXWIN_COMPATIBILITY_2_6
1596 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1600 bool wxSetWorkingDirectory(const wxString
& d
)
1602 #if defined(__OS2__)
1605 ::DosSetDefaultDisk(wxToupper(d
[0]) - _T('A') + 1);
1606 // do not call DosSetCurrentDir when just changing drive,
1607 // since it requires e.g. "d:." instead of "d:"!
1608 if (d
.length() == 2)
1611 return (::DosSetCurrentDir(d
.c_str()) == 0);
1612 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1613 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1614 #elif defined(__WINDOWS__)
1618 // No equivalent in WinCE
1622 return (bool)(SetCurrentDirectory(d
.fn_str()) != 0);
1625 // Must change drive, too.
1626 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1629 wxChar firstChar
= d
[0];
1633 firstChar
= firstChar
- 32;
1635 // To a drive number
1636 unsigned int driveNo
= firstChar
- 64;
1639 unsigned int noDrives
;
1640 _dos_setdrive(driveNo
, &noDrives
);
1643 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1651 // Get the OS directory if appropriate (such as the Windows directory).
1652 // On non-Windows platform, probably just return the empty string.
1653 wxString
wxGetOSDirectory()
1656 return wxString(wxT("\\Windows"));
1657 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1659 GetWindowsDirectory(buf
, 256);
1660 return wxString(buf
);
1661 #elif defined(__WXMAC__)
1662 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1664 return wxEmptyString
;
1668 bool wxEndsWithPathSeparator(const wxString
& filename
)
1670 return !filename
.empty() && wxIsPathSeparator(filename
.Last());
1673 // find a file in a list of directories, returns false if not found
1674 bool wxFindFileInPath(wxString
*pStr
, const wxString
& szPath
, const wxString
& szFile
)
1676 // we assume that it's not empty
1677 wxCHECK_MSG( !szFile
.empty(), false,
1678 _T("empty file name in wxFindFileInPath"));
1680 // skip path separator in the beginning of the file name if present
1682 if ( wxIsPathSeparator(szFile
[0u]) )
1683 szFile2
= szFile
.Mid(1);
1687 wxStringTokenizer
tkn(szPath
, wxPATH_SEP
);
1689 while ( tkn
.HasMoreTokens() )
1691 wxString strFile
= tkn
.GetNextToken();
1692 if ( !wxEndsWithPathSeparator(strFile
) )
1693 strFile
+= wxFILE_SEP_PATH
;
1696 if ( wxFileExists(strFile
) )
1706 void WXDLLEXPORT
wxSplitPath(const wxString
& fileName
,
1711 wxFileName::SplitPath(fileName
, pstrPath
, pstrName
, pstrExt
);
1716 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1719 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1722 return mtime
.GetTicks();
1725 #endif // wxUSE_DATETIME
1728 // Parses the filterStr, returning the number of filters.
1729 // Returns 0 if none or if there's a problem.
1730 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1732 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1733 wxArrayString
& descriptions
,
1734 wxArrayString
& filters
)
1736 descriptions
.Clear();
1739 wxString
str(filterStr
);
1741 wxString description
, filter
;
1743 while( pos
!= wxNOT_FOUND
)
1745 pos
= str
.Find(wxT('|'));
1746 if ( pos
== wxNOT_FOUND
)
1748 // if there are no '|'s at all in the string just take the entire
1749 // string as filter and make description empty for later autocompletion
1750 if ( filters
.IsEmpty() )
1752 descriptions
.Add(wxEmptyString
);
1753 filters
.Add(filterStr
);
1757 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1763 description
= str
.Left(pos
);
1764 str
= str
.Mid(pos
+ 1);
1765 pos
= str
.Find(wxT('|'));
1766 if ( pos
== wxNOT_FOUND
)
1772 filter
= str
.Left(pos
);
1773 str
= str
.Mid(pos
+ 1);
1776 descriptions
.Add(description
);
1777 filters
.Add(filter
);
1780 #if defined(__WXMOTIF__)
1781 // split it so there is one wildcard per entry
1782 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1784 pos
= filters
[i
].Find(wxT(';'));
1785 if (pos
!= wxNOT_FOUND
)
1787 // first split only filters
1788 descriptions
.Insert(descriptions
[i
],i
+1);
1789 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1790 filters
[i
]=filters
[i
].Left(pos
);
1792 // autoreplace new filter in description with pattern:
1793 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1794 // cause split into:
1795 // C/C++ Files(*.cpp)|*.cpp
1796 // C/C++ Files(*.c;*.h)|*.c;*.h
1797 // and next iteration cause another split into:
1798 // C/C++ Files(*.cpp)|*.cpp
1799 // C/C++ Files(*.c)|*.c
1800 // C/C++ Files(*.h)|*.h
1801 for ( size_t k
=i
;k
<i
+2;k
++ )
1803 pos
= descriptions
[k
].Find(filters
[k
]);
1804 if (pos
!= wxNOT_FOUND
)
1806 wxString before
= descriptions
[k
].Left(pos
);
1807 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1808 pos
= before
.Find(_T('('),true);
1809 if (pos
>before
.Find(_T(')'),true))
1811 before
= before
.Left(pos
+1);
1812 before
<< filters
[k
];
1813 pos
= after
.Find(_T(')'));
1814 int pos1
= after
.Find(_T('('));
1815 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1817 before
<< after
.Mid(pos
);
1818 descriptions
[k
] = before
;
1828 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1830 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1832 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1836 return filters
.GetCount();
1839 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1840 static bool wxCheckWin32Permission(const wxString
& path
, DWORD access
)
1842 // quoting the MSDN: "To obtain a handle to a directory, call the
1843 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1844 // doesn't work under Win9x/ME but then it's not needed there anyhow
1845 bool isdir
= wxDirExists(path
);
1846 if ( isdir
&& wxGetOsVersion() == wxOS_WINDOWS_9X
)
1848 // FAT directories always allow all access, even if they have the
1849 // readonly flag set
1853 HANDLE h
= ::CreateFile
1857 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1860 isdir
? FILE_FLAG_BACKUP_SEMANTICS
: 0,
1863 if ( h
!= INVALID_HANDLE_VALUE
)
1866 return h
!= INVALID_HANDLE_VALUE
;
1868 #endif // __WINDOWS__
1870 bool wxIsWritable(const wxString
&path
)
1872 #if defined( __UNIX__ ) || defined(__OS2__)
1873 // access() will take in count also symbolic links
1874 return wxAccess(path
.c_str(), W_OK
) == 0;
1875 #elif defined( __WINDOWS__ )
1876 return wxCheckWin32Permission(path
, GENERIC_WRITE
);
1884 bool wxIsReadable(const wxString
&path
)
1886 #if defined( __UNIX__ ) || defined(__OS2__)
1887 // access() will take in count also symbolic links
1888 return wxAccess(path
.c_str(), R_OK
) == 0;
1889 #elif defined( __WINDOWS__ )
1890 return wxCheckWin32Permission(path
, GENERIC_READ
);
1898 bool wxIsExecutable(const wxString
&path
)
1900 #if defined( __UNIX__ ) || defined(__OS2__)
1901 // access() will take in count also symbolic links
1902 return wxAccess(path
.c_str(), X_OK
) == 0;
1903 #elif defined( __WINDOWS__ )
1904 return wxCheckWin32Permission(path
, GENERIC_EXECUTE
);
1912 // Return the type of an open file
1914 // Some file types on some platforms seem seekable but in fact are not.
1915 // The main use of this function is to allow such cases to be detected
1916 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1918 // This is important for the archive streams, which benefit greatly from
1919 // being able to seek on a stream, but which will produce corrupt archives
1920 // if they unknowingly seek on a non-seekable stream.
1922 // wxFILE_KIND_DISK is a good catch all return value, since other values
1923 // disable features of the archive streams. Some other value must be returned
1924 // for a file type that appears seekable but isn't.
1927 // * Pipes on Windows
1928 // * Files on VMS with a record format other than StreamLF
1930 wxFileKind
wxGetFileKind(int fd
)
1932 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1933 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1935 case FILE_TYPE_CHAR
:
1936 return wxFILE_KIND_TERMINAL
;
1937 case FILE_TYPE_DISK
:
1938 return wxFILE_KIND_DISK
;
1939 case FILE_TYPE_PIPE
:
1940 return wxFILE_KIND_PIPE
;
1943 return wxFILE_KIND_UNKNOWN
;
1945 #elif defined(__UNIX__)
1947 return wxFILE_KIND_TERMINAL
;
1952 if (S_ISFIFO(st
.st_mode
))
1953 return wxFILE_KIND_PIPE
;
1954 if (!S_ISREG(st
.st_mode
))
1955 return wxFILE_KIND_UNKNOWN
;
1957 #if defined(__VMS__)
1958 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1959 return wxFILE_KIND_UNKNOWN
;
1962 return wxFILE_KIND_DISK
;
1965 #define wxFILEKIND_STUB
1967 return wxFILE_KIND_DISK
;
1971 wxFileKind
wxGetFileKind(FILE *fp
)
1973 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1974 // Should be fixed in version 1.4.
1975 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1977 return wxFILE_KIND_DISK
;
1978 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
1979 return fp
? wxGetFileKind(_fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1981 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1986 //------------------------------------------------------------------------
1987 // wild character routines
1988 //------------------------------------------------------------------------
1990 bool wxIsWild( const wxString
& pattern
)
1992 for ( wxString::const_iterator p
= pattern
.begin(); p
!= pattern
.end(); ++p
)
1994 switch ( (*p
).GetValue() )
2003 if ( ++p
== pattern
.end() )
2011 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
2013 * The match procedure is public domain code (from ircII's reg.c)
2014 * but modified to suit our tastes (RN: No "%" syntax I guess)
2017 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
2021 /* Match if both are empty. */
2025 const wxChar
*m
= pat
.c_str(),
2033 if (dot_special
&& (*n
== wxT('.')))
2035 /* Never match so that hidden Unix files
2036 * are never found. */
2049 else if (*m
== wxT('?'))
2057 if (*m
== wxT('\\'))
2060 /* Quoting "nothing" is a bad thing */
2067 * If we are out of both strings or we just
2068 * saw a wildcard, then we can say we have a
2079 * We could check for *n == NULL at this point, but
2080 * since it's more common to have a character there,
2081 * check to see if they match first (m and n) and
2082 * then if they don't match, THEN we can check for
2098 * If there are no more characters in the
2099 * string, but we still need to find another
2100 * character (*m != NULL), then it will be
2101 * impossible to match it
2120 #pragma warning(default:4706) // assignment within conditional expression