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/osx/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
99 // ----------------------------------------------------------------------------
101 // ----------------------------------------------------------------------------
103 // MT-FIXME: get rid of this horror and all code using it
104 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
106 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
108 // VisualAge C++ V4.0 cannot have any external linkage const decs
109 // in headers included by more than one primary source
111 const int wxInvalidOffset
= -1;
114 // ----------------------------------------------------------------------------
116 // ----------------------------------------------------------------------------
118 // translate the filenames before passing them to OS functions
119 #define OS_FILENAME(s) (s.fn_str())
121 // ============================================================================
123 // ============================================================================
125 // ----------------------------------------------------------------------------
126 // wrappers around standard POSIX functions
127 // ----------------------------------------------------------------------------
129 #if wxUSE_UNICODE && defined __BORLANDC__ \
130 && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
132 // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
133 // regardless of the mode parameter. This hack works around the problem by
134 // setting the mode with _wchmod.
136 int wxCRT_Open(const wchar_t *pathname
, int flags
, mode_t mode
)
140 // we only want to fix the mode when the file is actually created, so
141 // when creating first try doing it O_EXCL so we can tell if the file
142 // was already there.
143 if ((flags
& O_CREAT
) && !(flags
& O_EXCL
) && (mode
& wxS_IWUSR
) != 0)
146 int fd
= _wopen(pathname
, flags
| moreflags
, mode
);
148 // the file was actually created and needs fixing
149 if (fd
!= -1 && (flags
& O_CREAT
) != 0 && (mode
& wxS_IWUSR
) != 0)
152 _wchmod(pathname
, mode
);
153 fd
= _wopen(pathname
, flags
& ~(O_EXCL
| O_CREAT
));
155 // the open failed, but it may have been because the added O_EXCL stopped
156 // the opening of an existing file, so try again without.
157 else if (fd
== -1 && moreflags
!= 0)
159 fd
= _wopen(pathname
, flags
& ~O_CREAT
);
167 // ----------------------------------------------------------------------------
169 // ----------------------------------------------------------------------------
171 bool wxPathList::Add(const wxString
& path
)
173 // add a path separator to force wxFileName to interpret it always as a directory
174 // (i.e. if we are called with '/home/user' we want to consider it a folder and
175 // not, as wxFileName would consider, a filename).
176 wxFileName
fn(path
+ wxFileName::GetPathSeparator());
178 // add only normalized relative/absolute paths
179 // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
180 // normalize paths which starts with ".." (which can be normalized only if
181 // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
182 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
185 wxString toadd
= fn
.GetPath();
186 if (Index(toadd
) == wxNOT_FOUND
)
187 wxArrayString::Add(toadd
); // do not add duplicates
192 void wxPathList::Add(const wxArrayString
&arr
)
194 for (size_t j
=0; j
< arr
.GetCount(); j
++)
198 // Add paths e.g. from the PATH environment variable
199 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
201 // No environment variables on WinCE
204 // The space has been removed from the tokenizers, otherwise a
205 // path such as "C:\Program Files" would be split into 2 paths:
206 // "C:\Program" and "Files"; this is true for both Windows and Unix.
208 static const wxChar PATH_TOKS
[] =
209 #if defined(__WINDOWS__) || defined(__OS2__)
210 wxT(";"); // Don't separate with colon in DOS (used for drive)
216 if ( wxGetEnv(envVariable
, &val
) )
218 // split into an array of string the value of the env var
219 wxArrayString arr
= wxStringTokenize(val
, PATH_TOKS
);
220 WX_APPEND_ARRAY(*this, arr
);
222 #endif // !__WXWINCE__
225 // Given a full filename (with path), ensure that that file can
226 // be accessed again USING FILENAME ONLY by adding the path
227 // to the list if not already there.
228 bool wxPathList::EnsureFileAccessible (const wxString
& path
)
230 return Add(wxPathOnly(path
));
233 #if WXWIN_COMPATIBILITY_2_6
234 bool wxPathList::Member (const wxString
& path
) const
236 return Index(path
) != wxNOT_FOUND
;
240 wxString
wxPathList::FindValidPath (const wxString
& file
) const
242 // normalize the given string as it could be a path + a filename
243 // and not only a filename
247 // NB: normalize without making absolute otherwise calling this function with
248 // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
249 // below would only add to the paths of this list the 'c.txt' part when doing
250 // the existence checks...
251 // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
252 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
253 return wxEmptyString
;
255 wxASSERT_MSG(!fn
.IsDir(), wxT("Cannot search for directories; only for files"));
257 strend
= fn
.GetFullName(); // search for the file name and ignore the path part
259 strend
= fn
.GetFullPath();
261 for (size_t i
=0; i
<GetCount(); i
++)
263 wxString strstart
= Item(i
);
264 if (!strstart
.IsEmpty() && strstart
.Last() != wxFileName::GetPathSeparator())
265 strstart
+= wxFileName::GetPathSeparator();
267 if (wxFileExists(strstart
+ strend
))
268 return strstart
+ strend
; // Found!
271 return wxEmptyString
; // Not found
274 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
) const
276 wxString f
= FindValidPath(file
);
277 if ( f
.empty() || wxIsAbsolutePath(f
) )
280 wxString buf
= ::wxGetCwd();
282 if ( !wxEndsWithPathSeparator(buf
) )
284 buf
+= wxFILE_SEP_PATH
;
291 // ----------------------------------------------------------------------------
292 // miscellaneous global functions (TOFIX!)
293 // ----------------------------------------------------------------------------
295 static inline wxChar
* MYcopystring(const wxString
& s
)
297 wxChar
* copy
= new wxChar
[s
.length() + 1];
298 return wxStrcpy(copy
, s
.c_str());
301 template<typename CharType
>
302 static inline CharType
* MYcopystring(const CharType
* s
)
304 CharType
* copy
= new CharType
[wxStrlen(s
) + 1];
305 return wxStrcpy(copy
, s
);
310 wxFileExists (const wxString
& filename
)
312 #if defined(__WXPALMOS__)
314 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
315 // we must use GetFileAttributes() instead of the ANSI C functions because
316 // it can cope with network (UNC) paths unlike them
317 DWORD ret
= ::GetFileAttributes(filename
.fn_str());
319 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
322 #define S_ISREG(mode) ((mode) & S_IFREG)
325 #ifndef wxNEED_WX_UNISTD_H
326 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
328 || (errno
== EACCES
) // if access is denied something with that name
329 // exists and is opened in exclusive mode.
333 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
335 #endif // __WIN32__/!__WIN32__
339 wxIsAbsolutePath (const wxString
& filename
)
341 if (!filename
.empty())
343 // Unix like or Windows
344 if (filename
[0] == wxT('/'))
347 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
350 #if defined(__WINDOWS__) || defined(__OS2__)
352 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
360 * Strip off any extension (dot something) from end of file,
361 * IF one exists. Inserts zero into buffer.
366 static void wxDoStripExtension(T
*buffer
)
368 int len
= wxStrlen(buffer
);
372 if (buffer
[i
] == wxT('.'))
381 void wxStripExtension(char *buffer
) { wxDoStripExtension(buffer
); }
382 void wxStripExtension(wchar_t *buffer
) { wxDoStripExtension(buffer
); }
384 void wxStripExtension(wxString
& buffer
)
386 //RN: Be careful about the handling the case where
387 //buffer.length() == 0
388 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
390 if (buffer
.GetChar(i
) == wxT('.'))
392 buffer
= buffer
.Left(i
);
398 // Destructive removal of /./ and /../ stuff
399 template<typename CharType
>
400 static CharType
*wxDoRealPath (CharType
*path
)
402 static const CharType SEP
= wxFILE_SEP_PATH
;
404 wxUnix2DosFilename(path
);
406 if (path
[0] && path
[1]) {
407 /* MATTHEW: special case "/./x" */
409 if (path
[2] == SEP
&& path
[1] == wxT('.'))
417 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
420 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
425 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
426 && (q
- 1 <= path
|| q
[-1] != SEP
))
429 if (path
[0] == wxT('\0'))
434 #if defined(__WXMSW__) || defined(__OS2__)
435 /* Check that path[2] is NULL! */
436 else if (path
[1] == wxT(':') && !path
[2])
445 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
453 char *wxRealPath(char *path
)
455 return wxDoRealPath(path
);
458 wchar_t *wxRealPath(wchar_t *path
)
460 return wxDoRealPath(path
);
463 wxString
wxRealPath(const wxString
& path
)
465 wxChar
*buf1
=MYcopystring(path
);
466 wxChar
*buf2
=wxRealPath(buf1
);
474 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
476 if (filename
.empty())
477 return (wxChar
*) NULL
;
479 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
481 wxString buf
= ::wxGetCwd();
482 wxChar ch
= buf
.Last();
484 if (ch
!= wxT('\\') && ch
!= wxT('/'))
490 buf
<< wxFileFunctionsBuffer
;
491 buf
= wxRealPath( buf
);
492 return MYcopystring( buf
);
494 return MYcopystring( wxFileFunctionsBuffer
);
500 ~user/ => user's home dir
501 If the environment variable a = "foo" and b = "bar" then:
518 /* input name in name, pathname output to buf. */
520 template<typename CharType
>
521 static CharType
*wxDoExpandPath(CharType
*buf
, const wxString
& name
)
523 register CharType
*d
, *s
, *nm
;
524 CharType lnm
[_MAXPATHLEN
];
527 // Some compilers don't like this line.
528 // const CharType trimchars[] = wxT("\n \t");
530 CharType trimchars
[4];
531 trimchars
[0] = wxT('\n');
532 trimchars
[1] = wxT(' ');
533 trimchars
[2] = wxT('\t');
536 static const CharType SEP
= wxFILE_SEP_PATH
;
538 //wxUnix2DosFilename(path);
544 nm
= ::MYcopystring(static_cast<const CharType
*>(name
.c_str())); // Make a scratch copy
545 CharType
*nm_tmp
= nm
;
547 /* Skip leading whitespace and cr */
548 while (wxStrchr(trimchars
, *nm
) != NULL
)
550 /* And strip off trailing whitespace and cr */
551 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
552 while (q
-- && wxStrchr(trimchars
, *s
) != NULL
)
560 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
563 /* Expand inline environment variables */
581 while ((*d
++ = *s
) != 0) {
583 if (*s
== wxT('\\')) {
584 if ((*(d
- 1) = *++s
)!=0) {
592 // No env variables on WinCE
595 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
597 if (*s
++ == wxT('$'))
600 register CharType
*start
= d
;
601 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
602 register CharType
*value
;
603 while ((*d
++ = *s
) != 0)
604 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
609 value
= wxGetenv(braces
? start
+ 1 : start
);
611 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
625 /* Expand ~ and ~user */
628 if (nm
[0] == wxT('~') && !q
)
631 if (nm
[1] == SEP
|| nm
[1] == 0)
633 homepath
= wxGetUserHome(wxEmptyString
);
634 if (!homepath
.empty()) {
635 s
= (CharType
*)(const CharType
*)homepath
.c_str();
640 { /* ~user/filename */
641 register CharType
*nnm
;
642 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
646 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
647 was_sep
= (*s
== SEP
);
648 nnm
= *s
? s
+ 1 : s
;
650 homepath
= wxGetUserHome(wxString(nm
+ 1));
651 if (homepath
.empty())
653 if (was_sep
) /* replace only if it was there: */
660 s
= (CharType
*)(const CharType
*)homepath
.c_str();
666 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
668 while (wxT('\0') != (*d
++ = *s
++))
671 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
675 while ((*d
++ = *s
++) != 0)
679 delete[] nm_tmp
; // clean up alloc
680 /* Now clean up the buffer */
681 return wxRealPath(buf
);
684 char *wxExpandPath(char *buf
, const wxString
& name
)
686 return wxDoExpandPath(buf
, name
);
689 wchar_t *wxExpandPath(wchar_t *buf
, const wxString
& name
)
691 return wxDoExpandPath(buf
, name
);
695 /* Contract Paths to be build upon an environment variable
698 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
700 The call wxExpandPath can convert these back!
703 wxContractPath (const wxString
& filename
,
704 const wxString
& WXUNUSED_IN_WINCE(envname
),
705 const wxString
& user
)
707 static wxChar dest
[_MAXPATHLEN
];
709 if (filename
.empty())
710 return (wxChar
*) NULL
;
712 wxStrcpy (dest
, filename
);
714 wxUnix2DosFilename(dest
);
717 // Handle environment
721 if (!envname
.empty() && !(val
= wxGetenv (envname
)).empty() &&
722 (tcp
= wxStrstr (dest
, val
)) != NULL
)
724 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ val
.length());
727 wxStrcpy (tcp
, envname
);
728 wxStrcat (tcp
, wxT("}"));
729 wxStrcat (tcp
, wxFileFunctionsBuffer
);
733 // Handle User's home (ignore root homes!)
734 val
= wxGetUserHome (user
);
738 const size_t len
= val
.length();
742 if (wxStrncmp(dest
, val
, len
) == 0)
744 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
746 wxStrcat(wxFileFunctionsBuffer
, user
);
747 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
748 wxStrcpy (dest
, wxFileFunctionsBuffer
);
754 // Return just the filename, not the path (basename)
755 wxChar
*wxFileNameFromPath (wxChar
*path
)
758 wxString n
= wxFileNameFromPath(p
);
760 return path
+ p
.length() - n
.length();
763 wxString
wxFileNameFromPath (const wxString
& path
)
766 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
768 wxString fullname
= name
;
771 fullname
<< wxFILE_SEP_EXT
<< ext
;
777 // Return just the directory, or NULL if no directory
779 wxPathOnly (wxChar
*path
)
783 static wxChar buf
[_MAXPATHLEN
];
786 wxStrcpy (buf
, path
);
788 int l
= wxStrlen(path
);
791 // Search backward for a backward or forward slash
794 // Unix like or Windows
795 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
801 if (path
[i
] == wxT(']'))
810 #if defined(__WXMSW__) || defined(__OS2__)
811 // Try Drive specifier
812 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
814 // A:junk --> A:. (since A:.\junk Not A:\junk)
821 return (wxChar
*) NULL
;
824 // Return just the directory, or NULL if no directory
825 wxString
wxPathOnly (const wxString
& path
)
829 wxChar buf
[_MAXPATHLEN
];
834 int l
= path
.length();
837 // Search backward for a backward or forward slash
840 // Unix like or Windows
841 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
843 // Don't return an empty string
847 return wxString(buf
);
850 if (path
[i
] == wxT(']'))
853 return wxString(buf
);
859 #if defined(__WXMSW__) || defined(__OS2__)
860 // Try Drive specifier
861 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
863 // A:junk --> A:. (since A:.\junk Not A:\junk)
866 return wxString(buf
);
870 return wxEmptyString
;
873 // Utility for converting delimiters in DOS filenames to UNIX style
874 // and back again - or we get nasty problems with delimiters.
875 // Also, convert to lower case, since case is significant in UNIX.
877 #if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
879 #define kDefaultPathStyle kCFURLPOSIXPathStyle
881 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
884 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
885 if ( additionalPathComponent
)
887 CFURLRef parentURLRef
= fullURLRef
;
888 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
889 additionalPathComponent
,false);
890 CFRelease( parentURLRef
) ;
892 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
893 CFRelease( fullURLRef
) ;
894 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
895 CFRelease( cfString
);
896 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
897 return wxCFStringRef(cfMutableString
).AsString();
900 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
902 OSStatus err
= noErr
;
903 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxCFStringRef(path
));
904 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
905 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
906 CFRelease( cfMutableString
);
909 if ( CFURLGetFSRef(url
, fsRef
) == false )
920 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
922 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
925 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
927 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
928 return wxCFStringRef(cfMutableString
).AsString() ;
933 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
936 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
938 return wxMacFSRefToPath( &fsRef
) ;
940 return wxEmptyString
;
943 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
945 OSStatus err
= noErr
;
947 wxMacPathToFSRef( path
, &fsRef
);
948 err
= FSGetCatalogInfo(&fsRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
956 static void wxDoDos2UnixFilename(T
*s
)
965 *s
= wxTolower(*s
); // Case INDEPENDENT
971 void wxDos2UnixFilename(char *s
) { wxDoDos2UnixFilename(s
); }
972 void wxDos2UnixFilename(wchar_t *s
) { wxDoDos2UnixFilename(s
); }
976 #if defined(__WXMSW__) || defined(__OS2__)
977 wxDoUnix2DosFilename(T
*s
)
979 wxDoUnix2DosFilename(T
*WXUNUSED(s
) )
982 // Yes, I really mean this to happen under DOS only! JACS
983 #if defined(__WXMSW__) || defined(__OS2__)
994 void wxUnix2DosFilename(char *s
) { wxDoUnix2DosFilename(s
); }
995 void wxUnix2DosFilename(wchar_t *s
) { wxDoUnix2DosFilename(s
); }
997 // Concatenate two files to form third
999 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1003 wxFile
in1(file1
), in2(file2
);
1004 wxTempFile
out(file3
);
1006 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
1010 unsigned char buf
[1024];
1012 for( int i
=0; i
<2; i
++)
1014 wxFile
*in
= i
==0 ? &in1
: &in2
;
1016 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
1018 if ( !out
.Write(buf
,ofs
) )
1020 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1023 return out
.Commit();
1035 // helper of generic implementation of wxCopyFile()
1036 #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1040 wxDoCopyFile(wxFile
& fileIn
,
1041 const wxStructStat
& fbuf
,
1042 const wxString
& filenameDst
,
1045 // reset the umask as we want to create the file with exactly the same
1046 // permissions as the original one
1049 // create file2 with the same permissions than file1 and open it for
1053 if ( !fileOut
.Create(filenameDst
, overwrite
, fbuf
.st_mode
& 0777) )
1056 // copy contents of file1 to file2
1060 ssize_t count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1061 if ( count
== wxInvalidOffset
)
1068 if ( fileOut
.Write(buf
, count
) < (size_t)count
)
1072 // we can expect fileIn to be closed successfully, but we should ensure
1073 // that fileOut was closed as some write errors (disk full) might not be
1074 // detected before doing this
1075 return fileIn
.Close() && fileOut
.Close();
1078 #endif // generic implementation of wxCopyFile
1082 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1084 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1085 // CopyFile() copies file attributes and modification time too, so use it
1086 // instead of our code if available
1088 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1089 if ( !::CopyFile(file1
.fn_str(), file2
.fn_str(), !overwrite
) )
1091 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1092 file1
.c_str(), file2
.c_str());
1096 #elif defined(__OS2__)
1097 if ( ::DosCopy(file1
.c_str(), file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1099 #elif defined(__PALMOS__)
1100 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1102 #elif wxUSE_FILE // !Win32
1105 // get permissions of file1
1106 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1108 // the file probably doesn't exist or we haven't the rights to read
1110 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1115 // open file1 for reading
1116 wxFile
fileIn(file1
, wxFile::read
);
1117 if ( !fileIn
.IsOpened() )
1120 // remove file2, if it exists. This is needed for creating
1121 // file2 with the correct permissions in the next step
1122 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1124 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1129 wxDoCopyFile(fileIn
, fbuf
, file2
, overwrite
);
1131 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1132 // copy the resource fork of the file too if it's present
1133 wxString pathRsrcOut
;
1137 // suppress error messages from this block as resource forks don't have
1141 // it's not enough to check for file existence: it always does on HFS
1142 // but is empty for files without resources
1143 if ( fileRsrcIn
.Open(file1
+ wxT("/..namedfork/rsrc")) &&
1144 fileRsrcIn
.Length() > 0 )
1146 // we must be using HFS or another filesystem with resource fork
1147 // support, suppose that destination file system also is HFS[-like]
1148 pathRsrcOut
= file2
+ wxT("/..namedfork/rsrc");
1150 else // check if we have resource fork in separate file (non-HFS case)
1152 wxFileName
fnRsrc(file1
);
1153 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1156 if ( fileRsrcIn
.Open( fnRsrc
.GetFullPath() ) )
1159 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1161 pathRsrcOut
= fnRsrc
.GetFullPath();
1166 if ( !pathRsrcOut
.empty() )
1168 if ( !wxDoCopyFile(fileRsrcIn
, fbuf
, pathRsrcOut
, overwrite
) )
1171 #endif // wxMac || wxCocoa
1173 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1174 // no chmod in VA. Should be some permission API for HPFS386 partitions
1176 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1178 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1182 #endif // OS/2 || Mac
1184 #else // !Win32 && ! wxUSE_FILE
1186 // impossible to simulate with wxWidgets API
1189 wxUnusedVar(overwrite
);
1192 #endif // __WXMSW__ && __WIN32__
1198 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1200 if ( !overwrite
&& wxFileExists(file2
) )
1204 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1205 file1
.c_str(), file2
.c_str()
1211 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1212 // Normal system call
1213 if ( wxRename (file1
, file2
) == 0 )
1218 if (wxCopyFile(file1
, file2
, overwrite
)) {
1219 wxRemoveFile(file1
);
1226 bool wxRemoveFile(const wxString
& file
)
1228 #if defined(__VISUALC__) \
1229 || defined(__BORLANDC__) \
1230 || defined(__WATCOMC__) \
1231 || defined(__DMC__) \
1232 || defined(__GNUWIN32__) \
1233 || (defined(__MWERKS__) && defined(__MSL__))
1234 int res
= wxRemove(file
);
1235 #elif defined(__WXMAC__)
1236 int res
= unlink(file
.fn_str());
1237 #elif defined(__WXPALMOS__)
1239 // TODO with VFSFileDelete()
1241 int res
= unlink(OS_FILENAME(file
));
1247 bool wxMkdir(const wxString
& dir
, int perm
)
1249 #if defined(__WXPALMOS__)
1251 #elif defined(__WXMAC__) && !defined(__UNIX__)
1252 return (mkdir(dir
.fn_str() , 0 ) == 0);
1254 const wxChar
*dirname
= dir
.c_str();
1256 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1257 // for the GNU compiler
1258 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1261 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1263 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1265 #elif defined(__OS2__)
1267 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1268 #elif defined(__DOS__)
1269 #if defined(__WATCOMC__)
1271 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1272 #elif defined(__DJGPP__)
1273 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1275 #error "Unsupported DOS compiler!"
1277 #else // !MSW, !DOS and !OS/2 VAC++
1280 if ( !CreateDirectory(dirname
, NULL
) )
1282 if ( wxMkDir(dir
.fn_str()) != 0 )
1286 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1295 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1297 #if defined(__VMS__)
1298 return false; //to be changed since rmdir exists in VMS7.x
1299 #elif defined(__OS2__)
1300 return (::DosDeleteDir(dir
.c_str()) == 0);
1301 #elif defined(__WXWINCE__)
1302 return (RemoveDirectory(dir
) != 0);
1303 #elif defined(__WXPALMOS__)
1304 // TODO with VFSFileRename()
1307 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1311 // does the path exists? (may have or not '/' or '\\' at the end)
1312 bool wxDirExists(const wxString
& pathName
)
1314 wxString
strPath(pathName
);
1316 #if defined(__WINDOWS__) || defined(__OS2__)
1317 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1318 // so remove all trailing backslashes from the path - but don't do this for
1319 // the paths "d:\" (which are different from "d:") nor for just "\"
1320 while ( wxEndsWithPathSeparator(strPath
) )
1322 size_t len
= strPath
.length();
1323 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1326 strPath
.Truncate(len
- 1);
1328 #endif // __WINDOWS__
1331 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1332 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1336 #if defined(__WXPALMOS__)
1338 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1339 // stat() can't cope with network paths
1340 DWORD ret
= ::GetFileAttributes(strPath
.fn_str());
1342 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1343 #elif defined(__OS2__)
1344 FILESTATUS3 Info
= {{0}};
1345 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1346 (void*) &Info
, sizeof(FILESTATUS3
));
1348 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1349 (rc
== ERROR_SHARING_VIOLATION
);
1350 // If we got a sharing violation, there must be something with this name.
1354 #ifndef __VISAGECPP__
1355 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1357 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1358 return wxStat(strPath
.c_str(), &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1361 #endif // __WIN32__/!__WIN32__
1364 // Get a temporary filename, opening and closing the file.
1365 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1368 if ( !wxGetTempFileName(prefix
, filename
) )
1373 // work around the PalmOS pacc compiler bug
1374 wxStrcpy(buf
, filename
.data());
1376 wxStrcpy(buf
, filename
);
1379 buf
= MYcopystring(filename
);
1384 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1387 buf
= wxFileName::CreateTempFileName(prefix
);
1389 return !buf
.empty();
1390 #else // !wxUSE_FILE
1391 wxUnusedVar(prefix
);
1395 #endif // wxUSE_FILE/!wxUSE_FILE
1398 // Get first file name matching given wild card.
1400 static wxDir
*gs_dir
= NULL
;
1401 static wxString gs_dirPath
;
1403 wxString
wxFindFirstFile(const wxString
& spec
, int flags
)
1405 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1406 if ( gs_dirPath
.empty() )
1407 gs_dirPath
= wxT(".");
1408 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1409 gs_dirPath
<< wxFILE_SEP_PATH
;
1413 gs_dir
= new wxDir(gs_dirPath
);
1415 if ( !gs_dir
->IsOpened() )
1417 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1418 return wxEmptyString
;
1424 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1425 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1426 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1430 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1431 if ( result
.empty() )
1437 return gs_dirPath
+ result
;
1440 wxString
wxFindNextFile()
1442 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1445 gs_dir
->GetNext(&result
);
1447 if ( result
.empty() )
1453 return gs_dirPath
+ result
;
1457 // Get current working directory.
1458 // If buf is NULL, allocates space using new, else copies into buf.
1459 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1460 // wxDoGetCwd() is their common core to be moved
1461 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1462 // Do not expose wxDoGetCwd in headers!
1464 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1466 #if defined(__WXPALMOS__)
1468 if(buf
&& sz
>0) buf
[0] = _T('\0');
1470 #elif defined(__WXWINCE__)
1472 if(buf
&& sz
>0) buf
[0] = _T('\0');
1477 buf
= new wxChar
[sz
+ 1];
1480 bool ok
wxDUMMY_INITIALIZE(false);
1482 // for the compilers which have Unicode version of _getcwd(), call it
1483 // directly, for the others call the ANSI version and do the translation
1486 #else // wxUSE_UNICODE
1487 bool needsANSI
= true;
1489 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1490 char cbuf
[_MAXPATHLEN
];
1494 #if wxUSE_UNICODE_MSLU
1495 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1497 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1500 ok
= _wgetcwd(buf
, sz
) != NULL
;
1506 #endif // wxUSE_UNICODE
1508 #if defined(_MSC_VER) || defined(__MINGW32__)
1509 ok
= _getcwd(cbuf
, sz
) != NULL
;
1510 #elif defined(__OS2__)
1512 ULONG ulDriveNum
= 0;
1513 ULONG ulDriveMap
= 0;
1514 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1519 rc
= ::DosQueryCurrentDir( 0 // current drive
1523 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1528 #else // !Win32/VC++ !Mac !OS2
1529 ok
= getcwd(cbuf
, sz
) != NULL
;
1533 // finally convert the result to Unicode if needed
1534 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1535 #endif // wxUSE_UNICODE
1540 wxLogSysError(_("Failed to get the working directory"));
1542 // VZ: the old code used to return "." on error which didn't make any
1543 // sense at all to me - empty string is a better error indicator
1544 // (NULL might be even better but I'm afraid this could lead to
1545 // problems with the old code assuming the return is never NULL)
1548 else // ok, but we might need to massage the path into the right format
1551 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1552 // with / deliminers. We don't like that.
1553 for (wxChar
*ch
= buf
; *ch
; ch
++)
1555 if (*ch
== wxT('/'))
1560 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1561 // he needs Unix as opposed to Win32 pathnames
1562 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1563 // another example of DOS/Unix mix (Cygwin)
1564 wxString pathUnix
= buf
;
1566 char bufA
[_MAXPATHLEN
];
1567 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1568 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1570 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1571 #endif // wxUSE_UNICODE
1572 #endif // __CYGWIN__
1585 #if WXWIN_COMPATIBILITY_2_6
1586 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1588 return wxDoGetCwd(buf
,sz
);
1590 #endif // WXWIN_COMPATIBILITY_2_6
1595 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1599 bool wxSetWorkingDirectory(const wxString
& d
)
1601 #if defined(__OS2__)
1604 ::DosSetDefaultDisk(wxToupper(d
[0]) - _T('A') + 1);
1605 // do not call DosSetCurrentDir when just changing drive,
1606 // since it requires e.g. "d:." instead of "d:"!
1607 if (d
.length() == 2)
1610 return (::DosSetCurrentDir(d
.c_str()) == 0);
1611 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1612 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1613 #elif defined(__WINDOWS__)
1617 // No equivalent in WinCE
1621 return (bool)(SetCurrentDirectory(d
.fn_str()) != 0);
1624 // Must change drive, too.
1625 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1628 wxChar firstChar
= d
[0];
1632 firstChar
= firstChar
- 32;
1634 // To a drive number
1635 unsigned int driveNo
= firstChar
- 64;
1638 unsigned int noDrives
;
1639 _dos_setdrive(driveNo
, &noDrives
);
1642 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1650 // Get the OS directory if appropriate (such as the Windows directory).
1651 // On non-Windows platform, probably just return the empty string.
1652 wxString
wxGetOSDirectory()
1655 return wxString(wxT("\\Windows"));
1656 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1658 GetWindowsDirectory(buf
, 256);
1659 return wxString(buf
);
1660 #elif defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
1661 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1663 return wxEmptyString
;
1667 bool wxEndsWithPathSeparator(const wxString
& filename
)
1669 return !filename
.empty() && wxIsPathSeparator(filename
.Last());
1672 // find a file in a list of directories, returns false if not found
1673 bool wxFindFileInPath(wxString
*pStr
, const wxString
& szPath
, const wxString
& szFile
)
1675 // we assume that it's not empty
1676 wxCHECK_MSG( !szFile
.empty(), false,
1677 _T("empty file name in wxFindFileInPath"));
1679 // skip path separator in the beginning of the file name if present
1681 if ( wxIsPathSeparator(szFile
[0u]) )
1682 szFile2
= szFile
.Mid(1);
1686 wxStringTokenizer
tkn(szPath
, wxPATH_SEP
);
1688 while ( tkn
.HasMoreTokens() )
1690 wxString strFile
= tkn
.GetNextToken();
1691 if ( !wxEndsWithPathSeparator(strFile
) )
1692 strFile
+= wxFILE_SEP_PATH
;
1695 if ( wxFileExists(strFile
) )
1705 void WXDLLIMPEXP_BASE
wxSplitPath(const wxString
& fileName
,
1710 wxFileName::SplitPath(fileName
, pstrPath
, pstrName
, pstrExt
);
1715 time_t WXDLLIMPEXP_BASE
wxFileModificationTime(const wxString
& filename
)
1718 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1721 return mtime
.GetTicks();
1724 #endif // wxUSE_DATETIME
1727 // Parses the filterStr, returning the number of filters.
1728 // Returns 0 if none or if there's a problem.
1729 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1731 int WXDLLIMPEXP_BASE
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1732 wxArrayString
& descriptions
,
1733 wxArrayString
& filters
)
1735 descriptions
.Clear();
1738 wxString
str(filterStr
);
1740 wxString description
, filter
;
1742 while( pos
!= wxNOT_FOUND
)
1744 pos
= str
.Find(wxT('|'));
1745 if ( pos
== wxNOT_FOUND
)
1747 // if there are no '|'s at all in the string just take the entire
1748 // string as filter and make description empty for later autocompletion
1749 if ( filters
.IsEmpty() )
1751 descriptions
.Add(wxEmptyString
);
1752 filters
.Add(filterStr
);
1756 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1762 description
= str
.Left(pos
);
1763 str
= str
.Mid(pos
+ 1);
1764 pos
= str
.Find(wxT('|'));
1765 if ( pos
== wxNOT_FOUND
)
1771 filter
= str
.Left(pos
);
1772 str
= str
.Mid(pos
+ 1);
1775 descriptions
.Add(description
);
1776 filters
.Add(filter
);
1779 #if defined(__WXMOTIF__)
1780 // split it so there is one wildcard per entry
1781 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1783 pos
= filters
[i
].Find(wxT(';'));
1784 if (pos
!= wxNOT_FOUND
)
1786 // first split only filters
1787 descriptions
.Insert(descriptions
[i
],i
+1);
1788 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1789 filters
[i
]=filters
[i
].Left(pos
);
1791 // autoreplace new filter in description with pattern:
1792 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1793 // cause split into:
1794 // C/C++ Files(*.cpp)|*.cpp
1795 // C/C++ Files(*.c;*.h)|*.c;*.h
1796 // and next iteration cause another split into:
1797 // C/C++ Files(*.cpp)|*.cpp
1798 // C/C++ Files(*.c)|*.c
1799 // C/C++ Files(*.h)|*.h
1800 for ( size_t k
=i
;k
<i
+2;k
++ )
1802 pos
= descriptions
[k
].Find(filters
[k
]);
1803 if (pos
!= wxNOT_FOUND
)
1805 wxString before
= descriptions
[k
].Left(pos
);
1806 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1807 pos
= before
.Find(_T('('),true);
1808 if (pos
>before
.Find(_T(')'),true))
1810 before
= before
.Left(pos
+1);
1811 before
<< filters
[k
];
1812 pos
= after
.Find(_T(')'));
1813 int pos1
= after
.Find(_T('('));
1814 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1816 before
<< after
.Mid(pos
);
1817 descriptions
[k
] = before
;
1827 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1829 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1831 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1835 return filters
.GetCount();
1838 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1839 static bool wxCheckWin32Permission(const wxString
& path
, DWORD access
)
1841 // quoting the MSDN: "To obtain a handle to a directory, call the
1842 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1843 // doesn't work under Win9x/ME but then it's not needed there anyhow
1844 bool isdir
= wxDirExists(path
);
1845 if ( isdir
&& wxGetOsVersion() == wxOS_WINDOWS_9X
)
1847 // FAT directories always allow all access, even if they have the
1848 // readonly flag set
1852 HANDLE h
= ::CreateFile
1856 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1859 isdir
? FILE_FLAG_BACKUP_SEMANTICS
: 0,
1862 if ( h
!= INVALID_HANDLE_VALUE
)
1865 return h
!= INVALID_HANDLE_VALUE
;
1867 #endif // __WINDOWS__
1869 bool wxIsWritable(const wxString
&path
)
1871 #if defined( __UNIX__ ) || defined(__OS2__)
1872 // access() will take in count also symbolic links
1873 return wxAccess(path
.c_str(), W_OK
) == 0;
1874 #elif defined( __WINDOWS__ )
1875 return wxCheckWin32Permission(path
, GENERIC_WRITE
);
1883 bool wxIsReadable(const wxString
&path
)
1885 #if defined( __UNIX__ ) || defined(__OS2__)
1886 // access() will take in count also symbolic links
1887 return wxAccess(path
.c_str(), R_OK
) == 0;
1888 #elif defined( __WINDOWS__ )
1889 return wxCheckWin32Permission(path
, GENERIC_READ
);
1897 bool wxIsExecutable(const wxString
&path
)
1899 #if defined( __UNIX__ ) || defined(__OS2__)
1900 // access() will take in count also symbolic links
1901 return wxAccess(path
.c_str(), X_OK
) == 0;
1902 #elif defined( __WINDOWS__ )
1903 return wxCheckWin32Permission(path
, GENERIC_EXECUTE
);
1911 // Return the type of an open file
1913 // Some file types on some platforms seem seekable but in fact are not.
1914 // The main use of this function is to allow such cases to be detected
1915 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1917 // This is important for the archive streams, which benefit greatly from
1918 // being able to seek on a stream, but which will produce corrupt archives
1919 // if they unknowingly seek on a non-seekable stream.
1921 // wxFILE_KIND_DISK is a good catch all return value, since other values
1922 // disable features of the archive streams. Some other value must be returned
1923 // for a file type that appears seekable but isn't.
1926 // * Pipes on Windows
1927 // * Files on VMS with a record format other than StreamLF
1929 wxFileKind
wxGetFileKind(int fd
)
1931 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1932 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1934 case FILE_TYPE_CHAR
:
1935 return wxFILE_KIND_TERMINAL
;
1936 case FILE_TYPE_DISK
:
1937 return wxFILE_KIND_DISK
;
1938 case FILE_TYPE_PIPE
:
1939 return wxFILE_KIND_PIPE
;
1942 return wxFILE_KIND_UNKNOWN
;
1944 #elif defined(__UNIX__)
1946 return wxFILE_KIND_TERMINAL
;
1951 if (S_ISFIFO(st
.st_mode
))
1952 return wxFILE_KIND_PIPE
;
1953 if (!S_ISREG(st
.st_mode
))
1954 return wxFILE_KIND_UNKNOWN
;
1956 #if defined(__VMS__)
1957 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1958 return wxFILE_KIND_UNKNOWN
;
1961 return wxFILE_KIND_DISK
;
1964 #define wxFILEKIND_STUB
1966 return wxFILE_KIND_DISK
;
1970 wxFileKind
wxGetFileKind(FILE *fp
)
1972 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1973 // Should be fixed in version 1.4.
1974 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1976 return wxFILE_KIND_DISK
;
1977 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
1978 return fp
? wxGetFileKind(_fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1980 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1985 //------------------------------------------------------------------------
1986 // wild character routines
1987 //------------------------------------------------------------------------
1989 bool wxIsWild( const wxString
& pattern
)
1991 for ( wxString::const_iterator p
= pattern
.begin(); p
!= pattern
.end(); ++p
)
1993 switch ( (*p
).GetValue() )
2002 if ( ++p
== pattern
.end() )
2010 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
2012 * The match procedure is public domain code (from ircII's reg.c)
2013 * but modified to suit our tastes (RN: No "%" syntax I guess)
2016 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
2020 /* Match if both are empty. */
2024 const wxChar
*m
= pat
.c_str(),
2032 if (dot_special
&& (*n
== wxT('.')))
2034 /* Never match so that hidden Unix files
2035 * are never found. */
2048 else if (*m
== wxT('?'))
2056 if (*m
== wxT('\\'))
2059 /* Quoting "nothing" is a bad thing */
2066 * If we are out of both strings or we just
2067 * saw a wildcard, then we can say we have a
2078 * We could check for *n == NULL at this point, but
2079 * since it's more common to have a character there,
2080 * check to see if they match first (m and n) and
2081 * then if they don't match, THEN we can check for
2097 * If there are no more characters in the
2098 * string, but we still need to find another
2099 * character (*m != NULL), then it will be
2100 * impossible to match it
2119 #pragma warning(default:4706) // assignment within conditional expression