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 #ifndef INVALID_FILE_ATTRIBUTES
100 #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
103 // ----------------------------------------------------------------------------
105 // ----------------------------------------------------------------------------
107 #if WXWIN_COMPATIBILITY_2_8
108 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
111 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
113 // VisualAge C++ V4.0 cannot have any external linkage const decs
114 // in headers included by more than one primary source
116 const int wxInvalidOffset
= -1;
119 // ============================================================================
121 // ============================================================================
123 // ----------------------------------------------------------------------------
124 // wrappers around standard POSIX functions
125 // ----------------------------------------------------------------------------
127 #if wxUSE_UNICODE && defined __BORLANDC__ \
128 && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
130 // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
131 // regardless of the mode parameter. This hack works around the problem by
132 // setting the mode with _wchmod.
134 int wxCRT_Open(const wchar_t *pathname
, int flags
, mode_t mode
)
138 // we only want to fix the mode when the file is actually created, so
139 // when creating first try doing it O_EXCL so we can tell if the file
140 // was already there.
141 if ((flags
& O_CREAT
) && !(flags
& O_EXCL
) && (mode
& wxS_IWUSR
) != 0)
144 int fd
= _wopen(pathname
, flags
| moreflags
, mode
);
146 // the file was actually created and needs fixing
147 if (fd
!= -1 && (flags
& O_CREAT
) != 0 && (mode
& wxS_IWUSR
) != 0)
150 _wchmod(pathname
, mode
);
151 fd
= _wopen(pathname
, flags
& ~(O_EXCL
| O_CREAT
));
153 // the open failed, but it may have been because the added O_EXCL stopped
154 // the opening of an existing file, so try again without.
155 else if (fd
== -1 && moreflags
!= 0)
157 fd
= _wopen(pathname
, flags
& ~O_CREAT
);
165 // ----------------------------------------------------------------------------
167 // ----------------------------------------------------------------------------
169 bool wxPathList::Add(const wxString
& path
)
171 // add a path separator to force wxFileName to interpret it always as a directory
172 // (i.e. if we are called with '/home/user' we want to consider it a folder and
173 // not, as wxFileName would consider, a filename).
174 wxFileName
fn(path
+ wxFileName::GetPathSeparator());
176 // add only normalized relative/absolute paths
177 // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
178 // normalize paths which starts with ".." (which can be normalized only if
179 // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
180 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
183 wxString toadd
= fn
.GetPath();
184 if (Index(toadd
) == wxNOT_FOUND
)
185 wxArrayString::Add(toadd
); // do not add duplicates
190 void wxPathList::Add(const wxArrayString
&arr
)
192 for (size_t j
=0; j
< arr
.GetCount(); j
++)
196 // Add paths e.g. from the PATH environment variable
197 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
199 // No environment variables on WinCE
202 // The space has been removed from the tokenizers, otherwise a
203 // path such as "C:\Program Files" would be split into 2 paths:
204 // "C:\Program" and "Files"; this is true for both Windows and Unix.
206 static const wxChar PATH_TOKS
[] =
207 #if defined(__WINDOWS__) || defined(__OS2__)
208 wxT(";"); // Don't separate with colon in DOS (used for drive)
214 if ( wxGetEnv(envVariable
, &val
) )
216 // split into an array of string the value of the env var
217 wxArrayString arr
= wxStringTokenize(val
, PATH_TOKS
);
218 WX_APPEND_ARRAY(*this, arr
);
220 #endif // !__WXWINCE__
223 // Given a full filename (with path), ensure that that file can
224 // be accessed again USING FILENAME ONLY by adding the path
225 // to the list if not already there.
226 bool wxPathList::EnsureFileAccessible (const wxString
& path
)
228 return Add(wxPathOnly(path
));
231 #if WXWIN_COMPATIBILITY_2_6
232 bool wxPathList::Member (const wxString
& path
) const
234 return Index(path
) != wxNOT_FOUND
;
238 wxString
wxPathList::FindValidPath (const wxString
& file
) const
240 // normalize the given string as it could be a path + a filename
241 // and not only a filename
245 // NB: normalize without making absolute otherwise calling this function with
246 // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
247 // below would only add to the paths of this list the 'c.txt' part when doing
248 // the existence checks...
249 // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
250 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
251 return wxEmptyString
;
253 wxASSERT_MSG(!fn
.IsDir(), wxT("Cannot search for directories; only for files"));
255 strend
= fn
.GetFullName(); // search for the file name and ignore the path part
257 strend
= fn
.GetFullPath();
259 for (size_t i
=0; i
<GetCount(); i
++)
261 wxString strstart
= Item(i
);
262 if (!strstart
.IsEmpty() && strstart
.Last() != wxFileName::GetPathSeparator())
263 strstart
+= wxFileName::GetPathSeparator();
265 if (wxFileExists(strstart
+ strend
))
266 return strstart
+ strend
; // Found!
269 return wxEmptyString
; // Not found
272 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
) const
274 wxString f
= FindValidPath(file
);
275 if ( f
.empty() || wxIsAbsolutePath(f
) )
278 wxString buf
= ::wxGetCwd();
280 if ( !wxEndsWithPathSeparator(buf
) )
282 buf
+= wxFILE_SEP_PATH
;
289 // ----------------------------------------------------------------------------
290 // miscellaneous global functions
291 // ----------------------------------------------------------------------------
293 #if WXWIN_COMPATIBILITY_2_8
294 static inline wxChar
* MYcopystring(const wxString
& s
)
296 wxChar
* copy
= new wxChar
[s
.length() + 1];
297 return wxStrcpy(copy
, s
.c_str());
300 template<typename CharType
>
301 static inline CharType
* MYcopystring(const CharType
* s
)
303 CharType
* copy
= new CharType
[wxStrlen(s
) + 1];
304 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
!= INVALID_FILE_ATTRIBUTES
) && !(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(':')))
359 #if WXWIN_COMPATIBILITY_2_8
361 * Strip off any extension (dot something) from end of file,
362 * IF one exists. Inserts zero into buffer.
367 static void wxDoStripExtension(T
*buffer
)
369 int len
= wxStrlen(buffer
);
373 if (buffer
[i
] == wxT('.'))
382 void wxStripExtension(char *buffer
) { wxDoStripExtension(buffer
); }
383 void wxStripExtension(wchar_t *buffer
) { wxDoStripExtension(buffer
); }
385 void wxStripExtension(wxString
& buffer
)
387 //RN: Be careful about the handling the case where
388 //buffer.length() == 0
389 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
391 if (buffer
.GetChar(i
) == wxT('.'))
393 buffer
= buffer
.Left(i
);
399 // Destructive removal of /./ and /../ stuff
400 template<typename CharType
>
401 static CharType
*wxDoRealPath (CharType
*path
)
403 static const CharType SEP
= wxFILE_SEP_PATH
;
405 wxUnix2DosFilename(path
);
407 if (path
[0] && path
[1]) {
408 /* MATTHEW: special case "/./x" */
410 if (path
[2] == SEP
&& path
[1] == wxT('.'))
418 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
421 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
426 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
427 && (q
- 1 <= path
|| q
[-1] != SEP
))
430 if (path
[0] == wxT('\0'))
435 #if defined(__WXMSW__) || defined(__OS2__)
436 /* Check that path[2] is NULL! */
437 else if (path
[1] == wxT(':') && !path
[2])
446 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
454 char *wxRealPath(char *path
)
456 return wxDoRealPath(path
);
459 wchar_t *wxRealPath(wchar_t *path
)
461 return wxDoRealPath(path
);
464 wxString
wxRealPath(const wxString
& path
)
466 wxChar
*buf1
=MYcopystring(path
);
467 wxChar
*buf2
=wxRealPath(buf1
);
475 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
477 if (filename
.empty())
480 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
482 wxString buf
= ::wxGetCwd();
483 wxChar ch
= buf
.Last();
485 if (ch
!= wxT('\\') && ch
!= wxT('/'))
491 buf
<< wxFileFunctionsBuffer
;
492 buf
= wxRealPath( buf
);
493 return MYcopystring( buf
);
495 return MYcopystring( wxFileFunctionsBuffer
);
501 ~user/ => user's home dir
502 If the environment variable a = "foo" and b = "bar" then:
519 /* input name in name, pathname output to buf. */
521 template<typename CharType
>
522 static CharType
*wxDoExpandPath(CharType
*buf
, const wxString
& name
)
524 register CharType
*d
, *s
, *nm
;
525 CharType lnm
[_MAXPATHLEN
];
528 // Some compilers don't like this line.
529 // const CharType trimchars[] = wxT("\n \t");
531 CharType trimchars
[4];
532 trimchars
[0] = wxT('\n');
533 trimchars
[1] = wxT(' ');
534 trimchars
[2] = wxT('\t');
537 static const CharType SEP
= wxFILE_SEP_PATH
;
539 //wxUnix2DosFilename(path);
545 nm
= ::MYcopystring(static_cast<const CharType
*>(name
.c_str())); // Make a scratch copy
546 CharType
*nm_tmp
= nm
;
548 /* Skip leading whitespace and cr */
549 while (wxStrchr(trimchars
, *nm
) != NULL
)
551 /* And strip off trailing whitespace and cr */
552 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
553 while (q
-- && wxStrchr(trimchars
, *s
) != NULL
)
561 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
564 /* Expand inline environment variables */
582 while ((*d
++ = *s
) != 0) {
584 if (*s
== wxT('\\')) {
585 if ((*(d
- 1) = *++s
)!=0) {
593 // No env variables on WinCE
596 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
598 if (*s
++ == wxT('$'))
601 register CharType
*start
= d
;
602 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
603 register CharType
*value
;
604 while ((*d
++ = *s
) != 0)
605 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
610 value
= wxGetenv(braces
? start
+ 1 : start
);
612 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
626 /* Expand ~ and ~user */
629 if (nm
[0] == wxT('~') && !q
)
632 if (nm
[1] == SEP
|| nm
[1] == 0)
634 homepath
= wxGetUserHome(wxEmptyString
);
635 if (!homepath
.empty()) {
636 s
= (CharType
*)(const CharType
*)homepath
.c_str();
641 { /* ~user/filename */
642 register CharType
*nnm
;
643 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
647 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
648 was_sep
= (*s
== SEP
);
649 nnm
= *s
? s
+ 1 : s
;
651 homepath
= wxGetUserHome(wxString(nm
+ 1));
652 if (homepath
.empty())
654 if (was_sep
) /* replace only if it was there: */
661 s
= (CharType
*)(const CharType
*)homepath
.c_str();
667 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
669 while (wxT('\0') != (*d
++ = *s
++))
672 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
676 while ((*d
++ = *s
++) != 0)
680 delete[] nm_tmp
; // clean up alloc
681 /* Now clean up the buffer */
682 return wxRealPath(buf
);
685 char *wxExpandPath(char *buf
, const wxString
& name
)
687 return wxDoExpandPath(buf
, name
);
690 wchar_t *wxExpandPath(wchar_t *buf
, const wxString
& name
)
692 return wxDoExpandPath(buf
, name
);
696 /* Contract Paths to be build upon an environment variable
699 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
701 The call wxExpandPath can convert these back!
704 wxContractPath (const wxString
& filename
,
705 const wxString
& WXUNUSED_IN_WINCE(envname
),
706 const wxString
& user
)
708 static wxChar dest
[_MAXPATHLEN
];
710 if (filename
.empty())
713 wxStrcpy (dest
, filename
);
715 wxUnix2DosFilename(dest
);
718 // Handle environment
722 if (!envname
.empty() && !(val
= wxGetenv (envname
)).empty() &&
723 (tcp
= wxStrstr (dest
, val
)) != NULL
)
725 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ val
.length());
728 wxStrcpy (tcp
, envname
);
729 wxStrcat (tcp
, wxT("}"));
730 wxStrcat (tcp
, wxFileFunctionsBuffer
);
734 // Handle User's home (ignore root homes!)
735 val
= wxGetUserHome (user
);
739 const size_t len
= val
.length();
743 if (wxStrncmp(dest
, val
, len
) == 0)
745 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
747 wxStrcat(wxFileFunctionsBuffer
, user
);
748 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
749 wxStrcpy (dest
, wxFileFunctionsBuffer
);
755 #endif // #if WXWIN_COMPATIBILITY_2_8
757 // Return just the filename, not the path (basename)
758 wxChar
*wxFileNameFromPath (wxChar
*path
)
761 wxString n
= wxFileNameFromPath(p
);
763 return path
+ p
.length() - n
.length();
766 wxString
wxFileNameFromPath (const wxString
& path
)
769 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
771 wxString fullname
= name
;
774 fullname
<< wxFILE_SEP_EXT
<< ext
;
780 // Return just the directory, or NULL if no directory
782 wxPathOnly (wxChar
*path
)
786 static wxChar buf
[_MAXPATHLEN
];
789 wxStrcpy (buf
, path
);
791 int l
= wxStrlen(path
);
794 // Search backward for a backward or forward slash
797 // Unix like or Windows
798 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
804 if (path
[i
] == wxT(']'))
813 #if defined(__WXMSW__) || defined(__OS2__)
814 // Try Drive specifier
815 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
817 // A:junk --> A:. (since A:.\junk Not A:\junk)
827 // Return just the directory, or NULL if no directory
828 wxString
wxPathOnly (const wxString
& path
)
832 wxChar buf
[_MAXPATHLEN
];
837 int l
= path
.length();
840 // Search backward for a backward or forward slash
843 // Unix like or Windows
844 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
846 // Don't return an empty string
850 return wxString(buf
);
853 if (path
[i
] == wxT(']'))
856 return wxString(buf
);
862 #if defined(__WXMSW__) || defined(__OS2__)
863 // Try Drive specifier
864 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
866 // A:junk --> A:. (since A:.\junk Not A:\junk)
869 return wxString(buf
);
873 return wxEmptyString
;
876 // Utility for converting delimiters in DOS filenames to UNIX style
877 // and back again - or we get nasty problems with delimiters.
878 // Also, convert to lower case, since case is significant in UNIX.
880 #if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
882 #define kDefaultPathStyle kCFURLPOSIXPathStyle
884 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
887 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
888 if ( additionalPathComponent
)
890 CFURLRef parentURLRef
= fullURLRef
;
891 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
892 additionalPathComponent
,false);
893 CFRelease( parentURLRef
) ;
895 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
896 CFRelease( fullURLRef
) ;
897 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
898 CFRelease( cfString
);
899 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
900 return wxCFStringRef(cfMutableString
).AsString();
903 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
905 OSStatus err
= noErr
;
906 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxCFStringRef(path
));
907 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
908 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
909 CFRelease( cfMutableString
);
912 if ( CFURLGetFSRef(url
, fsRef
) == false )
923 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
925 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
928 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
930 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
931 return wxCFStringRef(cfMutableString
).AsString() ;
936 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
939 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
941 return wxMacFSRefToPath( &fsRef
) ;
943 return wxEmptyString
;
946 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
948 OSStatus err
= noErr
;
950 wxMacPathToFSRef( path
, &fsRef
);
951 err
= FSGetCatalogInfo(&fsRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
959 #if WXWIN_COMPATIBILITY_2_8
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 #endif // #if WXWIN_COMPATIBILITY_2_8
1005 // Concatenate two files to form third
1007 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1011 wxFile
in1(file1
), in2(file2
);
1012 wxTempFile
out(file3
);
1014 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
1018 unsigned char buf
[1024];
1020 for( int i
=0; i
<2; i
++)
1022 wxFile
*in
= i
==0 ? &in1
: &in2
;
1024 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
1026 if ( !out
.Write(buf
,ofs
) )
1028 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1031 return out
.Commit();
1043 // helper of generic implementation of wxCopyFile()
1044 #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1048 wxDoCopyFile(wxFile
& fileIn
,
1049 const wxStructStat
& fbuf
,
1050 const wxString
& filenameDst
,
1053 // reset the umask as we want to create the file with exactly the same
1054 // permissions as the original one
1057 // create file2 with the same permissions than file1 and open it for
1061 if ( !fileOut
.Create(filenameDst
, overwrite
, fbuf
.st_mode
& 0777) )
1064 // copy contents of file1 to file2
1068 ssize_t count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1069 if ( count
== wxInvalidOffset
)
1076 if ( fileOut
.Write(buf
, count
) < (size_t)count
)
1080 // we can expect fileIn to be closed successfully, but we should ensure
1081 // that fileOut was closed as some write errors (disk full) might not be
1082 // detected before doing this
1083 return fileIn
.Close() && fileOut
.Close();
1086 #endif // generic implementation of wxCopyFile
1090 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1092 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1093 // CopyFile() copies file attributes and modification time too, so use it
1094 // instead of our code if available
1096 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1097 if ( !::CopyFile(file1
.fn_str(), file2
.fn_str(), !overwrite
) )
1099 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1100 file1
.c_str(), file2
.c_str());
1104 #elif defined(__OS2__)
1105 if ( ::DosCopy(file1
.c_str(), file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1107 #elif defined(__PALMOS__)
1108 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1110 #elif wxUSE_FILE // !Win32
1113 // get permissions of file1
1114 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1116 // the file probably doesn't exist or we haven't the rights to read
1118 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1123 // open file1 for reading
1124 wxFile
fileIn(file1
, wxFile::read
);
1125 if ( !fileIn
.IsOpened() )
1128 // remove file2, if it exists. This is needed for creating
1129 // file2 with the correct permissions in the next step
1130 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1132 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1137 wxDoCopyFile(fileIn
, fbuf
, file2
, overwrite
);
1139 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1140 // copy the resource fork of the file too if it's present
1141 wxString pathRsrcOut
;
1145 // suppress error messages from this block as resource forks don't have
1149 // it's not enough to check for file existence: it always does on HFS
1150 // but is empty for files without resources
1151 if ( fileRsrcIn
.Open(file1
+ wxT("/..namedfork/rsrc")) &&
1152 fileRsrcIn
.Length() > 0 )
1154 // we must be using HFS or another filesystem with resource fork
1155 // support, suppose that destination file system also is HFS[-like]
1156 pathRsrcOut
= file2
+ wxT("/..namedfork/rsrc");
1158 else // check if we have resource fork in separate file (non-HFS case)
1160 wxFileName
fnRsrc(file1
);
1161 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1164 if ( fileRsrcIn
.Open( fnRsrc
.GetFullPath() ) )
1167 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1169 pathRsrcOut
= fnRsrc
.GetFullPath();
1174 if ( !pathRsrcOut
.empty() )
1176 if ( !wxDoCopyFile(fileRsrcIn
, fbuf
, pathRsrcOut
, overwrite
) )
1179 #endif // wxMac || wxCocoa
1181 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1182 // no chmod in VA. Should be some permission API for HPFS386 partitions
1184 if ( chmod(file2
.fn_str(), fbuf
.st_mode
) != 0 )
1186 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1190 #endif // OS/2 || Mac
1192 #else // !Win32 && ! wxUSE_FILE
1194 // impossible to simulate with wxWidgets API
1197 wxUnusedVar(overwrite
);
1200 #endif // __WXMSW__ && __WIN32__
1206 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1208 if ( !overwrite
&& wxFileExists(file2
) )
1212 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1213 file1
.c_str(), file2
.c_str()
1219 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1220 // Normal system call
1221 if ( wxRename (file1
, file2
) == 0 )
1226 if (wxCopyFile(file1
, file2
, overwrite
)) {
1227 wxRemoveFile(file1
);
1234 bool wxRemoveFile(const wxString
& file
)
1236 #if defined(__VISUALC__) \
1237 || defined(__BORLANDC__) \
1238 || defined(__WATCOMC__) \
1239 || defined(__DMC__) \
1240 || defined(__GNUWIN32__) \
1241 || (defined(__MWERKS__) && defined(__MSL__))
1242 int res
= wxRemove(file
);
1243 #elif defined(__WXMAC__)
1244 int res
= unlink(file
.fn_str());
1245 #elif defined(__WXPALMOS__)
1247 // TODO with VFSFileDelete()
1249 int res
= unlink(file
.fn_str());
1255 bool wxMkdir(const wxString
& dir
, int perm
)
1257 #if defined(__WXPALMOS__)
1260 #if defined(__WXMAC__) && !defined(__UNIX__)
1261 if ( mkdir(dir
.fn_str(), 0) != 0 )
1263 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1264 // for the GNU compiler
1265 #elif (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || \
1266 (defined(__GNUWIN32__) && !defined(__MINGW32__)) || \
1267 defined(__WINE__) || defined(__WXMICROWIN__)
1268 const wxChar
*dirname
= dir
.c_str();
1271 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1273 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1275 #elif defined(__OS2__)
1277 if (::DosCreateDir(dir
.c_str(), NULL
) != 0) // enhance for EAB's??
1278 #elif defined(__DOS__)
1279 const wxChar
*dirname
= dir
.c_str();
1280 #if defined(__WATCOMC__)
1282 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1283 #elif defined(__DJGPP__)
1284 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1286 #error "Unsupported DOS compiler!"
1288 #else // !MSW, !DOS and !OS/2 VAC++
1291 if ( CreateDirectory(dir
, NULL
) == 0 )
1293 if ( wxMkDir(dir
.fn_str()) != 0 )
1297 wxLogSysError(_("Directory '%s' couldn't be created"), dir
);
1302 #endif // PALMOS/!PALMOS
1305 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1307 #if defined(__VMS__)
1308 return false; //to be changed since rmdir exists in VMS7.x
1309 #elif defined(__WXPALMOS__)
1310 // TODO with VFSFileRename()
1313 #if defined(__OS2__)
1314 if ( ::DosDeleteDir(dir
.c_str()) != 0 )
1315 #elif defined(__WXWINCE__)
1316 if ( RemoveDirectory(dir
) == 0 )
1318 if ( wxRmDir(dir
.fn_str()) != 0 )
1321 wxLogSysError(_("Directory '%s' couldn't be deleted"), dir
);
1326 #endif // PALMOS/!PALMOS
1329 // does the path exists? (may have or not '/' or '\\' at the end)
1330 bool wxDirExists(const wxString
& pathName
)
1332 wxString
strPath(pathName
);
1334 #if defined(__WINDOWS__) || defined(__OS2__)
1335 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1336 // so remove all trailing backslashes from the path - but don't do this for
1337 // the paths "d:\" (which are different from "d:") nor for just "\"
1338 while ( wxEndsWithPathSeparator(strPath
) )
1340 size_t len
= strPath
.length();
1341 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1344 strPath
.Truncate(len
- 1);
1346 #endif // __WINDOWS__
1349 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1350 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1354 #if defined(__WXPALMOS__)
1356 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1357 // stat() can't cope with network paths
1358 DWORD ret
= ::GetFileAttributes(strPath
.fn_str());
1360 return (ret
!= INVALID_FILE_ATTRIBUTES
) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1361 #elif defined(__OS2__)
1362 FILESTATUS3 Info
= {{0}};
1363 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1364 (void*) &Info
, sizeof(FILESTATUS3
));
1366 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1367 (rc
== ERROR_SHARING_VIOLATION
);
1368 // If we got a sharing violation, there must be something with this name.
1372 #ifndef __VISAGECPP__
1373 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1375 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1376 return wxStat(strPath
.c_str(), &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1379 #endif // __WIN32__/!__WIN32__
1382 #if WXWIN_COMPATIBILITY_2_8
1384 // Get a temporary filename, opening and closing the file.
1385 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1388 if ( !wxGetTempFileName(prefix
, filename
) )
1393 // work around the PalmOS pacc compiler bug
1394 wxStrcpy(buf
, filename
.data());
1396 wxStrcpy(buf
, filename
);
1399 buf
= MYcopystring(filename
);
1404 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1407 buf
= wxFileName::CreateTempFileName(prefix
);
1409 return !buf
.empty();
1410 #else // !wxUSE_FILE
1411 wxUnusedVar(prefix
);
1415 #endif // wxUSE_FILE/!wxUSE_FILE
1418 #endif // #if WXWIN_COMPATIBILITY_2_8
1420 // Get first file name matching given wild card.
1422 static wxDir
*gs_dir
= NULL
;
1423 static wxString gs_dirPath
;
1425 wxString
wxFindFirstFile(const wxString
& spec
, int flags
)
1427 wxFileName::SplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1428 if ( gs_dirPath
.empty() )
1429 gs_dirPath
= wxT(".");
1430 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1431 gs_dirPath
<< wxFILE_SEP_PATH
;
1433 delete gs_dir
; // can be NULL, this is ok
1434 gs_dir
= new wxDir(gs_dirPath
);
1436 if ( !gs_dir
->IsOpened() )
1438 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1439 return wxEmptyString
;
1445 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1446 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1447 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1451 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1452 if ( result
.empty() )
1458 return gs_dirPath
+ result
;
1461 wxString
wxFindNextFile()
1463 wxCHECK_MSG( gs_dir
, "", "You must call wxFindFirstFile before!" );
1466 gs_dir
->GetNext(&result
);
1468 if ( result
.empty() )
1474 return gs_dirPath
+ result
;
1478 // Get current working directory.
1479 // If buf is NULL, allocates space using new, else copies into buf.
1480 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1481 // wxDoGetCwd() is their common core to be moved
1482 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1483 // Do not expose wxDoGetCwd in headers!
1485 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1487 #if defined(__WXPALMOS__)
1489 if(buf
&& sz
>0) buf
[0] = _T('\0');
1491 #elif defined(__WXWINCE__)
1493 if(buf
&& sz
>0) buf
[0] = _T('\0');
1498 buf
= new wxChar
[sz
+ 1];
1501 bool ok
wxDUMMY_INITIALIZE(false);
1503 // for the compilers which have Unicode version of _getcwd(), call it
1504 // directly, for the others call the ANSI version and do the translation
1507 #else // wxUSE_UNICODE
1508 bool needsANSI
= true;
1510 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1511 char cbuf
[_MAXPATHLEN
];
1515 #if wxUSE_UNICODE_MSLU
1516 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1518 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1521 ok
= _wgetcwd(buf
, sz
) != NULL
;
1527 #endif // wxUSE_UNICODE
1529 #if defined(_MSC_VER) || defined(__MINGW32__)
1530 ok
= _getcwd(cbuf
, sz
) != NULL
;
1531 #elif defined(__OS2__)
1533 ULONG ulDriveNum
= 0;
1534 ULONG ulDriveMap
= 0;
1535 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1540 rc
= ::DosQueryCurrentDir( 0 // current drive
1544 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1549 #else // !Win32/VC++ !Mac !OS2
1550 ok
= getcwd(cbuf
, sz
) != NULL
;
1554 // finally convert the result to Unicode if needed
1555 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1556 #endif // wxUSE_UNICODE
1561 wxLogSysError(_("Failed to get the working directory"));
1563 // VZ: the old code used to return "." on error which didn't make any
1564 // sense at all to me - empty string is a better error indicator
1565 // (NULL might be even better but I'm afraid this could lead to
1566 // problems with the old code assuming the return is never NULL)
1569 else // ok, but we might need to massage the path into the right format
1572 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1573 // with / deliminers. We don't like that.
1574 for (wxChar
*ch
= buf
; *ch
; ch
++)
1576 if (*ch
== wxT('/'))
1581 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1582 // he needs Unix as opposed to Win32 pathnames
1583 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1584 // another example of DOS/Unix mix (Cygwin)
1585 wxString pathUnix
= buf
;
1587 char bufA
[_MAXPATHLEN
];
1588 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1589 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1591 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1592 #endif // wxUSE_UNICODE
1593 #endif // __CYGWIN__
1606 #if WXWIN_COMPATIBILITY_2_6
1607 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1609 return wxDoGetCwd(buf
,sz
);
1611 #endif // WXWIN_COMPATIBILITY_2_6
1616 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1620 bool wxSetWorkingDirectory(const wxString
& d
)
1622 #if defined(__OS2__)
1625 ::DosSetDefaultDisk(wxToupper(d
[0]) - _T('A') + 1);
1626 // do not call DosSetCurrentDir when just changing drive,
1627 // since it requires e.g. "d:." instead of "d:"!
1628 if (d
.length() == 2)
1631 return (::DosSetCurrentDir(d
.c_str()) == 0);
1632 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1633 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1634 #elif defined(__WINDOWS__)
1638 // No equivalent in WinCE
1642 return (bool)(SetCurrentDirectory(d
.fn_str()) != 0);
1645 // Must change drive, too.
1646 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1649 wxChar firstChar
= d
[0];
1653 firstChar
= firstChar
- 32;
1655 // To a drive number
1656 unsigned int driveNo
= firstChar
- 64;
1659 unsigned int noDrives
;
1660 _dos_setdrive(driveNo
, &noDrives
);
1663 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1671 // Get the OS directory if appropriate (such as the Windows directory).
1672 // On non-Windows platform, probably just return the empty string.
1673 wxString
wxGetOSDirectory()
1676 return wxString(wxT("\\Windows"));
1677 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1679 GetWindowsDirectory(buf
, 256);
1680 return wxString(buf
);
1681 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1682 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1684 return wxEmptyString
;
1688 bool wxEndsWithPathSeparator(const wxString
& filename
)
1690 return !filename
.empty() && wxIsPathSeparator(filename
.Last());
1693 // find a file in a list of directories, returns false if not found
1694 bool wxFindFileInPath(wxString
*pStr
, const wxString
& szPath
, const wxString
& szFile
)
1696 // we assume that it's not empty
1697 wxCHECK_MSG( !szFile
.empty(), false,
1698 _T("empty file name in wxFindFileInPath"));
1700 // skip path separator in the beginning of the file name if present
1702 if ( wxIsPathSeparator(szFile
[0u]) )
1703 szFile2
= szFile
.Mid(1);
1707 wxStringTokenizer
tkn(szPath
, wxPATH_SEP
);
1709 while ( tkn
.HasMoreTokens() )
1711 wxString strFile
= tkn
.GetNextToken();
1712 if ( !wxEndsWithPathSeparator(strFile
) )
1713 strFile
+= wxFILE_SEP_PATH
;
1716 if ( wxFileExists(strFile
) )
1726 #if WXWIN_COMPATIBILITY_2_8
1727 void WXDLLIMPEXP_BASE
wxSplitPath(const wxString
& fileName
,
1732 wxFileName::SplitPath(fileName
, pstrPath
, pstrName
, pstrExt
);
1734 #endif // #if WXWIN_COMPATIBILITY_2_8
1738 time_t WXDLLIMPEXP_BASE
wxFileModificationTime(const wxString
& filename
)
1741 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1744 return mtime
.GetTicks();
1747 #endif // wxUSE_DATETIME
1750 // Parses the filterStr, returning the number of filters.
1751 // Returns 0 if none or if there's a problem.
1752 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1754 int WXDLLIMPEXP_BASE
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1755 wxArrayString
& descriptions
,
1756 wxArrayString
& filters
)
1758 descriptions
.Clear();
1761 wxString
str(filterStr
);
1763 wxString description
, filter
;
1765 while( pos
!= wxNOT_FOUND
)
1767 pos
= str
.Find(wxT('|'));
1768 if ( pos
== wxNOT_FOUND
)
1770 // if there are no '|'s at all in the string just take the entire
1771 // string as filter and make description empty for later autocompletion
1772 if ( filters
.IsEmpty() )
1774 descriptions
.Add(wxEmptyString
);
1775 filters
.Add(filterStr
);
1779 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1785 description
= str
.Left(pos
);
1786 str
= str
.Mid(pos
+ 1);
1787 pos
= str
.Find(wxT('|'));
1788 if ( pos
== wxNOT_FOUND
)
1794 filter
= str
.Left(pos
);
1795 str
= str
.Mid(pos
+ 1);
1798 descriptions
.Add(description
);
1799 filters
.Add(filter
);
1802 #if defined(__WXMOTIF__)
1803 // split it so there is one wildcard per entry
1804 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1806 pos
= filters
[i
].Find(wxT(';'));
1807 if (pos
!= wxNOT_FOUND
)
1809 // first split only filters
1810 descriptions
.Insert(descriptions
[i
],i
+1);
1811 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1812 filters
[i
]=filters
[i
].Left(pos
);
1814 // autoreplace new filter in description with pattern:
1815 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1816 // cause split into:
1817 // C/C++ Files(*.cpp)|*.cpp
1818 // C/C++ Files(*.c;*.h)|*.c;*.h
1819 // and next iteration cause another split into:
1820 // C/C++ Files(*.cpp)|*.cpp
1821 // C/C++ Files(*.c)|*.c
1822 // C/C++ Files(*.h)|*.h
1823 for ( size_t k
=i
;k
<i
+2;k
++ )
1825 pos
= descriptions
[k
].Find(filters
[k
]);
1826 if (pos
!= wxNOT_FOUND
)
1828 wxString before
= descriptions
[k
].Left(pos
);
1829 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1830 pos
= before
.Find(_T('('),true);
1831 if (pos
>before
.Find(_T(')'),true))
1833 before
= before
.Left(pos
+1);
1834 before
<< filters
[k
];
1835 pos
= after
.Find(_T(')'));
1836 int pos1
= after
.Find(_T('('));
1837 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1839 before
<< after
.Mid(pos
);
1840 descriptions
[k
] = before
;
1850 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1852 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1854 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1858 return filters
.GetCount();
1861 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1862 static bool wxCheckWin32Permission(const wxString
& path
, DWORD access
)
1864 // quoting the MSDN: "To obtain a handle to a directory, call the
1865 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1866 // doesn't work under Win9x/ME but then it's not needed there anyhow
1867 const DWORD dwAttr
= ::GetFileAttributes(path
.fn_str());
1868 if ( dwAttr
== INVALID_FILE_ATTRIBUTES
)
1870 // file probably doesn't exist at all
1874 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
1876 // FAT directories always allow all access, even if they have the
1877 // readonly flag set, and FAT files can only be read-only
1878 return (dwAttr
& FILE_ATTRIBUTE_DIRECTORY
) ||
1879 (access
!= GENERIC_WRITE
||
1880 !(dwAttr
& FILE_ATTRIBUTE_READONLY
));
1883 HANDLE h
= ::CreateFile
1887 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1890 dwAttr
& FILE_ATTRIBUTE_DIRECTORY
1891 ? FILE_FLAG_BACKUP_SEMANTICS
1895 if ( h
!= INVALID_HANDLE_VALUE
)
1898 return h
!= INVALID_HANDLE_VALUE
;
1900 #endif // __WINDOWS__
1902 bool wxIsWritable(const wxString
&path
)
1904 #if defined( __UNIX__ ) || defined(__OS2__)
1905 // access() will take in count also symbolic links
1906 return wxAccess(path
.c_str(), W_OK
) == 0;
1907 #elif defined( __WINDOWS__ )
1908 return wxCheckWin32Permission(path
, GENERIC_WRITE
);
1916 bool wxIsReadable(const wxString
&path
)
1918 #if defined( __UNIX__ ) || defined(__OS2__)
1919 // access() will take in count also symbolic links
1920 return wxAccess(path
.c_str(), R_OK
) == 0;
1921 #elif defined( __WINDOWS__ )
1922 return wxCheckWin32Permission(path
, GENERIC_READ
);
1930 bool wxIsExecutable(const wxString
&path
)
1932 #if defined( __UNIX__ ) || defined(__OS2__)
1933 // access() will take in count also symbolic links
1934 return wxAccess(path
.c_str(), X_OK
) == 0;
1935 #elif defined( __WINDOWS__ )
1936 return wxCheckWin32Permission(path
, GENERIC_EXECUTE
);
1944 // Return the type of an open file
1946 // Some file types on some platforms seem seekable but in fact are not.
1947 // The main use of this function is to allow such cases to be detected
1948 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1950 // This is important for the archive streams, which benefit greatly from
1951 // being able to seek on a stream, but which will produce corrupt archives
1952 // if they unknowingly seek on a non-seekable stream.
1954 // wxFILE_KIND_DISK is a good catch all return value, since other values
1955 // disable features of the archive streams. Some other value must be returned
1956 // for a file type that appears seekable but isn't.
1959 // * Pipes on Windows
1960 // * Files on VMS with a record format other than StreamLF
1962 wxFileKind
wxGetFileKind(int fd
)
1964 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1965 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1967 case FILE_TYPE_CHAR
:
1968 return wxFILE_KIND_TERMINAL
;
1969 case FILE_TYPE_DISK
:
1970 return wxFILE_KIND_DISK
;
1971 case FILE_TYPE_PIPE
:
1972 return wxFILE_KIND_PIPE
;
1975 return wxFILE_KIND_UNKNOWN
;
1977 #elif defined(__UNIX__)
1979 return wxFILE_KIND_TERMINAL
;
1984 if (S_ISFIFO(st
.st_mode
))
1985 return wxFILE_KIND_PIPE
;
1986 if (!S_ISREG(st
.st_mode
))
1987 return wxFILE_KIND_UNKNOWN
;
1989 #if defined(__VMS__)
1990 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1991 return wxFILE_KIND_UNKNOWN
;
1994 return wxFILE_KIND_DISK
;
1997 #define wxFILEKIND_STUB
1999 return wxFILE_KIND_DISK
;
2003 wxFileKind
wxGetFileKind(FILE *fp
)
2005 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
2006 // Should be fixed in version 1.4.
2007 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
2009 return wxFILE_KIND_DISK
;
2010 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
2011 return fp
? wxGetFileKind(_fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2013 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2018 //------------------------------------------------------------------------
2019 // wild character routines
2020 //------------------------------------------------------------------------
2022 bool wxIsWild( const wxString
& pattern
)
2024 for ( wxString::const_iterator p
= pattern
.begin(); p
!= pattern
.end(); ++p
)
2026 switch ( (*p
).GetValue() )
2035 if ( ++p
== pattern
.end() )
2043 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
2045 * The match procedure is public domain code (from ircII's reg.c)
2046 * but modified to suit our tastes (RN: No "%" syntax I guess)
2049 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
2053 /* Match if both are empty. */
2057 const wxChar
*m
= pat
.c_str(),
2065 if (dot_special
&& (*n
== wxT('.')))
2067 /* Never match so that hidden Unix files
2068 * are never found. */
2081 else if (*m
== wxT('?'))
2089 if (*m
== wxT('\\'))
2092 /* Quoting "nothing" is a bad thing */
2099 * If we are out of both strings or we just
2100 * saw a wildcard, then we can say we have a
2111 * We could check for *n == NULL at this point, but
2112 * since it's more common to have a character there,
2113 * check to see if they match first (m and n) and
2114 * then if they don't match, THEN we can check for
2130 * If there are no more characters in the
2131 * string, but we still need to find another
2132 * character (*m != NULL), then it will be
2133 * impossible to match it
2152 #pragma warning(default:4706) // assignment within conditional expression