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 // translate the filenames before passing them to OS functions
124 #define OS_FILENAME(s) (s.fn_str())
126 // ============================================================================
128 // ============================================================================
130 // ----------------------------------------------------------------------------
131 // wrappers around standard POSIX functions
132 // ----------------------------------------------------------------------------
134 #if wxUSE_UNICODE && defined __BORLANDC__ \
135 && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
137 // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
138 // regardless of the mode parameter. This hack works around the problem by
139 // setting the mode with _wchmod.
141 int wxCRT_Open(const wchar_t *pathname
, int flags
, mode_t mode
)
145 // we only want to fix the mode when the file is actually created, so
146 // when creating first try doing it O_EXCL so we can tell if the file
147 // was already there.
148 if ((flags
& O_CREAT
) && !(flags
& O_EXCL
) && (mode
& wxS_IWUSR
) != 0)
151 int fd
= _wopen(pathname
, flags
| moreflags
, mode
);
153 // the file was actually created and needs fixing
154 if (fd
!= -1 && (flags
& O_CREAT
) != 0 && (mode
& wxS_IWUSR
) != 0)
157 _wchmod(pathname
, mode
);
158 fd
= _wopen(pathname
, flags
& ~(O_EXCL
| O_CREAT
));
160 // the open failed, but it may have been because the added O_EXCL stopped
161 // the opening of an existing file, so try again without.
162 else if (fd
== -1 && moreflags
!= 0)
164 fd
= _wopen(pathname
, flags
& ~O_CREAT
);
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
176 bool wxPathList::Add(const wxString
& path
)
178 // add a path separator to force wxFileName to interpret it always as a directory
179 // (i.e. if we are called with '/home/user' we want to consider it a folder and
180 // not, as wxFileName would consider, a filename).
181 wxFileName
fn(path
+ wxFileName::GetPathSeparator());
183 // add only normalized relative/absolute paths
184 // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
185 // normalize paths which starts with ".." (which can be normalized only if
186 // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
187 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
190 wxString toadd
= fn
.GetPath();
191 if (Index(toadd
) == wxNOT_FOUND
)
192 wxArrayString::Add(toadd
); // do not add duplicates
197 void wxPathList::Add(const wxArrayString
&arr
)
199 for (size_t j
=0; j
< arr
.GetCount(); j
++)
203 // Add paths e.g. from the PATH environment variable
204 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
206 // No environment variables on WinCE
209 // The space has been removed from the tokenizers, otherwise a
210 // path such as "C:\Program Files" would be split into 2 paths:
211 // "C:\Program" and "Files"; this is true for both Windows and Unix.
213 static const wxChar PATH_TOKS
[] =
214 #if defined(__WINDOWS__) || defined(__OS2__)
215 wxT(";"); // Don't separate with colon in DOS (used for drive)
221 if ( wxGetEnv(envVariable
, &val
) )
223 // split into an array of string the value of the env var
224 wxArrayString arr
= wxStringTokenize(val
, PATH_TOKS
);
225 WX_APPEND_ARRAY(*this, arr
);
227 #endif // !__WXWINCE__
230 // Given a full filename (with path), ensure that that file can
231 // be accessed again USING FILENAME ONLY by adding the path
232 // to the list if not already there.
233 bool wxPathList::EnsureFileAccessible (const wxString
& path
)
235 return Add(wxPathOnly(path
));
238 #if WXWIN_COMPATIBILITY_2_6
239 bool wxPathList::Member (const wxString
& path
) const
241 return Index(path
) != wxNOT_FOUND
;
245 wxString
wxPathList::FindValidPath (const wxString
& file
) const
247 // normalize the given string as it could be a path + a filename
248 // and not only a filename
252 // NB: normalize without making absolute otherwise calling this function with
253 // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
254 // below would only add to the paths of this list the 'c.txt' part when doing
255 // the existence checks...
256 // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
257 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
258 return wxEmptyString
;
260 wxASSERT_MSG(!fn
.IsDir(), wxT("Cannot search for directories; only for files"));
262 strend
= fn
.GetFullName(); // search for the file name and ignore the path part
264 strend
= fn
.GetFullPath();
266 for (size_t i
=0; i
<GetCount(); i
++)
268 wxString strstart
= Item(i
);
269 if (!strstart
.IsEmpty() && strstart
.Last() != wxFileName::GetPathSeparator())
270 strstart
+= wxFileName::GetPathSeparator();
272 if (wxFileExists(strstart
+ strend
))
273 return strstart
+ strend
; // Found!
276 return wxEmptyString
; // Not found
279 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
) const
281 wxString f
= FindValidPath(file
);
282 if ( f
.empty() || wxIsAbsolutePath(f
) )
285 wxString buf
= ::wxGetCwd();
287 if ( !wxEndsWithPathSeparator(buf
) )
289 buf
+= wxFILE_SEP_PATH
;
296 // ----------------------------------------------------------------------------
297 // miscellaneous global functions (TOFIX!)
298 // ----------------------------------------------------------------------------
300 static inline wxChar
* MYcopystring(const wxString
& s
)
302 wxChar
* copy
= new wxChar
[s
.length() + 1];
303 return wxStrcpy(copy
, s
.c_str());
306 template<typename CharType
>
307 static inline CharType
* MYcopystring(const CharType
* s
)
309 CharType
* copy
= new CharType
[wxStrlen(s
) + 1];
310 return wxStrcpy(copy
, s
);
315 wxFileExists (const wxString
& filename
)
317 #if defined(__WXPALMOS__)
319 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
320 // we must use GetFileAttributes() instead of the ANSI C functions because
321 // it can cope with network (UNC) paths unlike them
322 DWORD ret
= ::GetFileAttributes(filename
.fn_str());
324 return (ret
!= INVALID_FILE_ATTRIBUTES
) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
327 #define S_ISREG(mode) ((mode) & S_IFREG)
330 #ifndef wxNEED_WX_UNISTD_H
331 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
333 || (errno
== EACCES
) // if access is denied something with that name
334 // exists and is opened in exclusive mode.
338 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
340 #endif // __WIN32__/!__WIN32__
344 wxIsAbsolutePath (const wxString
& filename
)
346 if (!filename
.empty())
348 // Unix like or Windows
349 if (filename
[0] == wxT('/'))
352 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
355 #if defined(__WINDOWS__) || defined(__OS2__)
357 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
364 #if WXWIN_COMPATIBILITY_2_8
366 * Strip off any extension (dot something) from end of file,
367 * IF one exists. Inserts zero into buffer.
372 static void wxDoStripExtension(T
*buffer
)
374 int len
= wxStrlen(buffer
);
378 if (buffer
[i
] == wxT('.'))
387 void wxStripExtension(char *buffer
) { wxDoStripExtension(buffer
); }
388 void wxStripExtension(wchar_t *buffer
) { wxDoStripExtension(buffer
); }
390 void wxStripExtension(wxString
& buffer
)
392 //RN: Be careful about the handling the case where
393 //buffer.length() == 0
394 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
396 if (buffer
.GetChar(i
) == wxT('.'))
398 buffer
= buffer
.Left(i
);
404 // Destructive removal of /./ and /../ stuff
405 template<typename CharType
>
406 static CharType
*wxDoRealPath (CharType
*path
)
408 static const CharType SEP
= wxFILE_SEP_PATH
;
410 wxUnix2DosFilename(path
);
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');
542 static const CharType SEP
= wxFILE_SEP_PATH
;
544 //wxUnix2DosFilename(path);
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 #endif // #if WXWIN_COMPATIBILITY_2_8
762 // Return just the filename, not the path (basename)
763 wxChar
*wxFileNameFromPath (wxChar
*path
)
766 wxString n
= wxFileNameFromPath(p
);
768 return path
+ p
.length() - n
.length();
771 wxString
wxFileNameFromPath (const wxString
& path
)
774 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
776 wxString fullname
= name
;
779 fullname
<< wxFILE_SEP_EXT
<< ext
;
785 // Return just the directory, or NULL if no directory
787 wxPathOnly (wxChar
*path
)
791 static wxChar buf
[_MAXPATHLEN
];
794 wxStrcpy (buf
, path
);
796 int l
= wxStrlen(path
);
799 // Search backward for a backward or forward slash
802 // Unix like or Windows
803 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
809 if (path
[i
] == wxT(']'))
818 #if defined(__WXMSW__) || defined(__OS2__)
819 // Try Drive specifier
820 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
822 // A:junk --> A:. (since A:.\junk Not A:\junk)
829 return (wxChar
*) NULL
;
832 // Return just the directory, or NULL if no directory
833 wxString
wxPathOnly (const wxString
& path
)
837 wxChar buf
[_MAXPATHLEN
];
842 int l
= path
.length();
845 // Search backward for a backward or forward slash
848 // Unix like or Windows
849 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
851 // Don't return an empty string
855 return wxString(buf
);
858 if (path
[i
] == wxT(']'))
861 return wxString(buf
);
867 #if defined(__WXMSW__) || defined(__OS2__)
868 // Try Drive specifier
869 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
871 // A:junk --> A:. (since A:.\junk Not A:\junk)
874 return wxString(buf
);
878 return wxEmptyString
;
881 // Utility for converting delimiters in DOS filenames to UNIX style
882 // and back again - or we get nasty problems with delimiters.
883 // Also, convert to lower case, since case is significant in UNIX.
885 #if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
887 #define kDefaultPathStyle kCFURLPOSIXPathStyle
889 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
892 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
893 if ( additionalPathComponent
)
895 CFURLRef parentURLRef
= fullURLRef
;
896 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
897 additionalPathComponent
,false);
898 CFRelease( parentURLRef
) ;
900 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
901 CFRelease( fullURLRef
) ;
902 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
903 CFRelease( cfString
);
904 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
905 return wxCFStringRef(cfMutableString
).AsString();
908 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
910 OSStatus err
= noErr
;
911 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxCFStringRef(path
));
912 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
913 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
914 CFRelease( cfMutableString
);
917 if ( CFURLGetFSRef(url
, fsRef
) == false )
928 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
930 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
933 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
935 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
936 return wxCFStringRef(cfMutableString
).AsString() ;
941 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
944 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
946 return wxMacFSRefToPath( &fsRef
) ;
948 return wxEmptyString
;
951 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
953 OSStatus err
= noErr
;
955 wxMacPathToFSRef( path
, &fsRef
);
956 err
= FSGetCatalogInfo(&fsRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
964 #if WXWIN_COMPATIBILITY_2_8
967 static void wxDoDos2UnixFilename(T
*s
)
976 *s
= wxTolower(*s
); // Case INDEPENDENT
982 void wxDos2UnixFilename(char *s
) { wxDoDos2UnixFilename(s
); }
983 void wxDos2UnixFilename(wchar_t *s
) { wxDoDos2UnixFilename(s
); }
987 #if defined(__WXMSW__) || defined(__OS2__)
988 wxDoUnix2DosFilename(T
*s
)
990 wxDoUnix2DosFilename(T
*WXUNUSED(s
) )
993 // Yes, I really mean this to happen under DOS only! JACS
994 #if defined(__WXMSW__) || defined(__OS2__)
1005 void wxUnix2DosFilename(char *s
) { wxDoUnix2DosFilename(s
); }
1006 void wxUnix2DosFilename(wchar_t *s
) { wxDoUnix2DosFilename(s
); }
1008 #endif // #if WXWIN_COMPATIBILITY_2_8
1010 // Concatenate two files to form third
1012 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1016 wxFile
in1(file1
), in2(file2
);
1017 wxTempFile
out(file3
);
1019 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
1023 unsigned char buf
[1024];
1025 for( int i
=0; i
<2; i
++)
1027 wxFile
*in
= i
==0 ? &in1
: &in2
;
1029 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
1031 if ( !out
.Write(buf
,ofs
) )
1033 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1036 return out
.Commit();
1048 // helper of generic implementation of wxCopyFile()
1049 #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1053 wxDoCopyFile(wxFile
& fileIn
,
1054 const wxStructStat
& fbuf
,
1055 const wxString
& filenameDst
,
1058 // reset the umask as we want to create the file with exactly the same
1059 // permissions as the original one
1062 // create file2 with the same permissions than file1 and open it for
1066 if ( !fileOut
.Create(filenameDst
, overwrite
, fbuf
.st_mode
& 0777) )
1069 // copy contents of file1 to file2
1073 ssize_t count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1074 if ( count
== wxInvalidOffset
)
1081 if ( fileOut
.Write(buf
, count
) < (size_t)count
)
1085 // we can expect fileIn to be closed successfully, but we should ensure
1086 // that fileOut was closed as some write errors (disk full) might not be
1087 // detected before doing this
1088 return fileIn
.Close() && fileOut
.Close();
1091 #endif // generic implementation of wxCopyFile
1095 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1097 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1098 // CopyFile() copies file attributes and modification time too, so use it
1099 // instead of our code if available
1101 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1102 if ( !::CopyFile(file1
.fn_str(), file2
.fn_str(), !overwrite
) )
1104 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1105 file1
.c_str(), file2
.c_str());
1109 #elif defined(__OS2__)
1110 if ( ::DosCopy(file1
.c_str(), file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1112 #elif defined(__PALMOS__)
1113 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1115 #elif wxUSE_FILE // !Win32
1118 // get permissions of file1
1119 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1121 // the file probably doesn't exist or we haven't the rights to read
1123 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1128 // open file1 for reading
1129 wxFile
fileIn(file1
, wxFile::read
);
1130 if ( !fileIn
.IsOpened() )
1133 // remove file2, if it exists. This is needed for creating
1134 // file2 with the correct permissions in the next step
1135 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1137 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1142 wxDoCopyFile(fileIn
, fbuf
, file2
, overwrite
);
1144 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1145 // copy the resource fork of the file too if it's present
1146 wxString pathRsrcOut
;
1150 // suppress error messages from this block as resource forks don't have
1154 // it's not enough to check for file existence: it always does on HFS
1155 // but is empty for files without resources
1156 if ( fileRsrcIn
.Open(file1
+ wxT("/..namedfork/rsrc")) &&
1157 fileRsrcIn
.Length() > 0 )
1159 // we must be using HFS or another filesystem with resource fork
1160 // support, suppose that destination file system also is HFS[-like]
1161 pathRsrcOut
= file2
+ wxT("/..namedfork/rsrc");
1163 else // check if we have resource fork in separate file (non-HFS case)
1165 wxFileName
fnRsrc(file1
);
1166 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1169 if ( fileRsrcIn
.Open( fnRsrc
.GetFullPath() ) )
1172 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1174 pathRsrcOut
= fnRsrc
.GetFullPath();
1179 if ( !pathRsrcOut
.empty() )
1181 if ( !wxDoCopyFile(fileRsrcIn
, fbuf
, pathRsrcOut
, overwrite
) )
1184 #endif // wxMac || wxCocoa
1186 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1187 // no chmod in VA. Should be some permission API for HPFS386 partitions
1189 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1191 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1195 #endif // OS/2 || Mac
1197 #else // !Win32 && ! wxUSE_FILE
1199 // impossible to simulate with wxWidgets API
1202 wxUnusedVar(overwrite
);
1205 #endif // __WXMSW__ && __WIN32__
1211 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1213 if ( !overwrite
&& wxFileExists(file2
) )
1217 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1218 file1
.c_str(), file2
.c_str()
1224 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1225 // Normal system call
1226 if ( wxRename (file1
, file2
) == 0 )
1231 if (wxCopyFile(file1
, file2
, overwrite
)) {
1232 wxRemoveFile(file1
);
1239 bool wxRemoveFile(const wxString
& file
)
1241 #if defined(__VISUALC__) \
1242 || defined(__BORLANDC__) \
1243 || defined(__WATCOMC__) \
1244 || defined(__DMC__) \
1245 || defined(__GNUWIN32__) \
1246 || (defined(__MWERKS__) && defined(__MSL__))
1247 int res
= wxRemove(file
);
1248 #elif defined(__WXMAC__)
1249 int res
= unlink(file
.fn_str());
1250 #elif defined(__WXPALMOS__)
1252 // TODO with VFSFileDelete()
1254 int res
= unlink(OS_FILENAME(file
));
1260 bool wxMkdir(const wxString
& dir
, int perm
)
1262 #if defined(__WXPALMOS__)
1264 #elif defined(__WXMAC__) && !defined(__UNIX__)
1265 return (mkdir(dir
.fn_str() , 0 ) == 0);
1267 const wxChar
*dirname
= dir
.c_str();
1269 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1270 // for the GNU compiler
1271 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1274 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1276 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1278 #elif defined(__OS2__)
1280 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1281 #elif defined(__DOS__)
1282 #if defined(__WATCOMC__)
1284 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1285 #elif defined(__DJGPP__)
1286 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1288 #error "Unsupported DOS compiler!"
1290 #else // !MSW, !DOS and !OS/2 VAC++
1293 if ( !CreateDirectory(dirname
, NULL
) )
1295 if ( wxMkDir(dir
.fn_str()) != 0 )
1299 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1308 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1310 #if defined(__VMS__)
1311 return false; //to be changed since rmdir exists in VMS7.x
1312 #elif defined(__OS2__)
1313 return (::DosDeleteDir(dir
.c_str()) == 0);
1314 #elif defined(__WXWINCE__)
1315 return (RemoveDirectory(dir
) != 0);
1316 #elif defined(__WXPALMOS__)
1317 // TODO with VFSFileRename()
1320 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1324 // does the path exists? (may have or not '/' or '\\' at the end)
1325 bool wxDirExists(const wxString
& pathName
)
1327 wxString
strPath(pathName
);
1329 #if defined(__WINDOWS__) || defined(__OS2__)
1330 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1331 // so remove all trailing backslashes from the path - but don't do this for
1332 // the paths "d:\" (which are different from "d:") nor for just "\"
1333 while ( wxEndsWithPathSeparator(strPath
) )
1335 size_t len
= strPath
.length();
1336 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1339 strPath
.Truncate(len
- 1);
1341 #endif // __WINDOWS__
1344 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1345 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1349 #if defined(__WXPALMOS__)
1351 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1352 // stat() can't cope with network paths
1353 DWORD ret
= ::GetFileAttributes(strPath
.fn_str());
1355 return (ret
!= INVALID_FILE_ATTRIBUTES
) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1356 #elif defined(__OS2__)
1357 FILESTATUS3 Info
= {{0}};
1358 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1359 (void*) &Info
, sizeof(FILESTATUS3
));
1361 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1362 (rc
== ERROR_SHARING_VIOLATION
);
1363 // If we got a sharing violation, there must be something with this name.
1367 #ifndef __VISAGECPP__
1368 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1370 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1371 return wxStat(strPath
.c_str(), &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1374 #endif // __WIN32__/!__WIN32__
1377 #if WXWIN_COMPATIBILITY_2_8
1379 // Get a temporary filename, opening and closing the file.
1380 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1383 if ( !wxGetTempFileName(prefix
, filename
) )
1388 // work around the PalmOS pacc compiler bug
1389 wxStrcpy(buf
, filename
.data());
1391 wxStrcpy(buf
, filename
);
1394 buf
= MYcopystring(filename
);
1399 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1402 buf
= wxFileName::CreateTempFileName(prefix
);
1404 return !buf
.empty();
1405 #else // !wxUSE_FILE
1406 wxUnusedVar(prefix
);
1410 #endif // wxUSE_FILE/!wxUSE_FILE
1413 #endif // #if WXWIN_COMPATIBILITY_2_8
1415 // Get first file name matching given wild card.
1417 static wxDir
*gs_dir
= NULL
;
1418 static wxString gs_dirPath
;
1420 wxString
wxFindFirstFile(const wxString
& spec
, int flags
)
1422 wxFileName::SplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1423 if ( gs_dirPath
.empty() )
1424 gs_dirPath
= wxT(".");
1425 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1426 gs_dirPath
<< wxFILE_SEP_PATH
;
1428 delete gs_dir
; // can be NULL, this is ok
1429 gs_dir
= new wxDir(gs_dirPath
);
1431 if ( !gs_dir
->IsOpened() )
1433 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1434 return wxEmptyString
;
1440 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1441 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1442 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1446 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1447 if ( result
.empty() )
1453 return gs_dirPath
+ result
;
1456 wxString
wxFindNextFile()
1458 wxCHECK_MSG( gs_dir
, "", "You must call wxFindFirstFile before!" );
1461 gs_dir
->GetNext(&result
);
1463 if ( result
.empty() )
1469 return gs_dirPath
+ result
;
1473 // Get current working directory.
1474 // If buf is NULL, allocates space using new, else copies into buf.
1475 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1476 // wxDoGetCwd() is their common core to be moved
1477 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1478 // Do not expose wxDoGetCwd in headers!
1480 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1482 #if defined(__WXPALMOS__)
1484 if(buf
&& sz
>0) buf
[0] = _T('\0');
1486 #elif defined(__WXWINCE__)
1488 if(buf
&& sz
>0) buf
[0] = _T('\0');
1493 buf
= new wxChar
[sz
+ 1];
1496 bool ok
wxDUMMY_INITIALIZE(false);
1498 // for the compilers which have Unicode version of _getcwd(), call it
1499 // directly, for the others call the ANSI version and do the translation
1502 #else // wxUSE_UNICODE
1503 bool needsANSI
= true;
1505 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1506 char cbuf
[_MAXPATHLEN
];
1510 #if wxUSE_UNICODE_MSLU
1511 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1513 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1516 ok
= _wgetcwd(buf
, sz
) != NULL
;
1522 #endif // wxUSE_UNICODE
1524 #if defined(_MSC_VER) || defined(__MINGW32__)
1525 ok
= _getcwd(cbuf
, sz
) != NULL
;
1526 #elif defined(__OS2__)
1528 ULONG ulDriveNum
= 0;
1529 ULONG ulDriveMap
= 0;
1530 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1535 rc
= ::DosQueryCurrentDir( 0 // current drive
1539 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1544 #else // !Win32/VC++ !Mac !OS2
1545 ok
= getcwd(cbuf
, sz
) != NULL
;
1549 // finally convert the result to Unicode if needed
1550 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1551 #endif // wxUSE_UNICODE
1556 wxLogSysError(_("Failed to get the working directory"));
1558 // VZ: the old code used to return "." on error which didn't make any
1559 // sense at all to me - empty string is a better error indicator
1560 // (NULL might be even better but I'm afraid this could lead to
1561 // problems with the old code assuming the return is never NULL)
1564 else // ok, but we might need to massage the path into the right format
1567 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1568 // with / deliminers. We don't like that.
1569 for (wxChar
*ch
= buf
; *ch
; ch
++)
1571 if (*ch
== wxT('/'))
1576 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1577 // he needs Unix as opposed to Win32 pathnames
1578 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1579 // another example of DOS/Unix mix (Cygwin)
1580 wxString pathUnix
= buf
;
1582 char bufA
[_MAXPATHLEN
];
1583 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1584 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1586 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1587 #endif // wxUSE_UNICODE
1588 #endif // __CYGWIN__
1601 #if WXWIN_COMPATIBILITY_2_6
1602 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1604 return wxDoGetCwd(buf
,sz
);
1606 #endif // WXWIN_COMPATIBILITY_2_6
1611 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1615 bool wxSetWorkingDirectory(const wxString
& d
)
1617 #if defined(__OS2__)
1620 ::DosSetDefaultDisk(wxToupper(d
[0]) - _T('A') + 1);
1621 // do not call DosSetCurrentDir when just changing drive,
1622 // since it requires e.g. "d:." instead of "d:"!
1623 if (d
.length() == 2)
1626 return (::DosSetCurrentDir(d
.c_str()) == 0);
1627 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1628 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1629 #elif defined(__WINDOWS__)
1633 // No equivalent in WinCE
1637 return (bool)(SetCurrentDirectory(d
.fn_str()) != 0);
1640 // Must change drive, too.
1641 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1644 wxChar firstChar
= d
[0];
1648 firstChar
= firstChar
- 32;
1650 // To a drive number
1651 unsigned int driveNo
= firstChar
- 64;
1654 unsigned int noDrives
;
1655 _dos_setdrive(driveNo
, &noDrives
);
1658 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1666 // Get the OS directory if appropriate (such as the Windows directory).
1667 // On non-Windows platform, probably just return the empty string.
1668 wxString
wxGetOSDirectory()
1671 return wxString(wxT("\\Windows"));
1672 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1674 GetWindowsDirectory(buf
, 256);
1675 return wxString(buf
);
1676 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1677 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1679 return wxEmptyString
;
1683 bool wxEndsWithPathSeparator(const wxString
& filename
)
1685 return !filename
.empty() && wxIsPathSeparator(filename
.Last());
1688 // find a file in a list of directories, returns false if not found
1689 bool wxFindFileInPath(wxString
*pStr
, const wxString
& szPath
, const wxString
& szFile
)
1691 // we assume that it's not empty
1692 wxCHECK_MSG( !szFile
.empty(), false,
1693 _T("empty file name in wxFindFileInPath"));
1695 // skip path separator in the beginning of the file name if present
1697 if ( wxIsPathSeparator(szFile
[0u]) )
1698 szFile2
= szFile
.Mid(1);
1702 wxStringTokenizer
tkn(szPath
, wxPATH_SEP
);
1704 while ( tkn
.HasMoreTokens() )
1706 wxString strFile
= tkn
.GetNextToken();
1707 if ( !wxEndsWithPathSeparator(strFile
) )
1708 strFile
+= wxFILE_SEP_PATH
;
1711 if ( wxFileExists(strFile
) )
1721 #if WXWIN_COMPATIBILITY_2_8
1722 void WXDLLIMPEXP_BASE
wxSplitPath(const wxString
& fileName
,
1727 wxFileName::SplitPath(fileName
, pstrPath
, pstrName
, pstrExt
);
1729 #endif // #if WXWIN_COMPATIBILITY_2_8
1733 time_t WXDLLIMPEXP_BASE
wxFileModificationTime(const wxString
& filename
)
1736 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1739 return mtime
.GetTicks();
1742 #endif // wxUSE_DATETIME
1745 // Parses the filterStr, returning the number of filters.
1746 // Returns 0 if none or if there's a problem.
1747 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1749 int WXDLLIMPEXP_BASE
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1750 wxArrayString
& descriptions
,
1751 wxArrayString
& filters
)
1753 descriptions
.Clear();
1756 wxString
str(filterStr
);
1758 wxString description
, filter
;
1760 while( pos
!= wxNOT_FOUND
)
1762 pos
= str
.Find(wxT('|'));
1763 if ( pos
== wxNOT_FOUND
)
1765 // if there are no '|'s at all in the string just take the entire
1766 // string as filter and make description empty for later autocompletion
1767 if ( filters
.IsEmpty() )
1769 descriptions
.Add(wxEmptyString
);
1770 filters
.Add(filterStr
);
1774 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1780 description
= str
.Left(pos
);
1781 str
= str
.Mid(pos
+ 1);
1782 pos
= str
.Find(wxT('|'));
1783 if ( pos
== wxNOT_FOUND
)
1789 filter
= str
.Left(pos
);
1790 str
= str
.Mid(pos
+ 1);
1793 descriptions
.Add(description
);
1794 filters
.Add(filter
);
1797 #if defined(__WXMOTIF__)
1798 // split it so there is one wildcard per entry
1799 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1801 pos
= filters
[i
].Find(wxT(';'));
1802 if (pos
!= wxNOT_FOUND
)
1804 // first split only filters
1805 descriptions
.Insert(descriptions
[i
],i
+1);
1806 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1807 filters
[i
]=filters
[i
].Left(pos
);
1809 // autoreplace new filter in description with pattern:
1810 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1811 // cause split into:
1812 // C/C++ Files(*.cpp)|*.cpp
1813 // C/C++ Files(*.c;*.h)|*.c;*.h
1814 // and next iteration cause another split into:
1815 // C/C++ Files(*.cpp)|*.cpp
1816 // C/C++ Files(*.c)|*.c
1817 // C/C++ Files(*.h)|*.h
1818 for ( size_t k
=i
;k
<i
+2;k
++ )
1820 pos
= descriptions
[k
].Find(filters
[k
]);
1821 if (pos
!= wxNOT_FOUND
)
1823 wxString before
= descriptions
[k
].Left(pos
);
1824 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1825 pos
= before
.Find(_T('('),true);
1826 if (pos
>before
.Find(_T(')'),true))
1828 before
= before
.Left(pos
+1);
1829 before
<< filters
[k
];
1830 pos
= after
.Find(_T(')'));
1831 int pos1
= after
.Find(_T('('));
1832 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1834 before
<< after
.Mid(pos
);
1835 descriptions
[k
] = before
;
1845 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1847 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1849 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1853 return filters
.GetCount();
1856 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1857 static bool wxCheckWin32Permission(const wxString
& path
, DWORD access
)
1859 // quoting the MSDN: "To obtain a handle to a directory, call the
1860 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1861 // doesn't work under Win9x/ME but then it's not needed there anyhow
1862 const DWORD dwAttr
= ::GetFileAttributes(path
.fn_str());
1863 if ( dwAttr
== INVALID_FILE_ATTRIBUTES
)
1865 // file probably doesn't exist at all
1869 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
1871 // FAT directories always allow all access, even if they have the
1872 // readonly flag set, and FAT files can only be read-only
1873 return (dwAttr
& FILE_ATTRIBUTE_DIRECTORY
) ||
1874 (access
!= GENERIC_WRITE
||
1875 !(dwAttr
& FILE_ATTRIBUTE_READONLY
));
1878 HANDLE h
= ::CreateFile
1882 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1885 dwAttr
& FILE_ATTRIBUTE_DIRECTORY
1886 ? FILE_FLAG_BACKUP_SEMANTICS
1890 if ( h
!= INVALID_HANDLE_VALUE
)
1893 return h
!= INVALID_HANDLE_VALUE
;
1895 #endif // __WINDOWS__
1897 bool wxIsWritable(const wxString
&path
)
1899 #if defined( __UNIX__ ) || defined(__OS2__)
1900 // access() will take in count also symbolic links
1901 return wxAccess(path
.c_str(), W_OK
) == 0;
1902 #elif defined( __WINDOWS__ )
1903 return wxCheckWin32Permission(path
, GENERIC_WRITE
);
1911 bool wxIsReadable(const wxString
&path
)
1913 #if defined( __UNIX__ ) || defined(__OS2__)
1914 // access() will take in count also symbolic links
1915 return wxAccess(path
.c_str(), R_OK
) == 0;
1916 #elif defined( __WINDOWS__ )
1917 return wxCheckWin32Permission(path
, GENERIC_READ
);
1925 bool wxIsExecutable(const wxString
&path
)
1927 #if defined( __UNIX__ ) || defined(__OS2__)
1928 // access() will take in count also symbolic links
1929 return wxAccess(path
.c_str(), X_OK
) == 0;
1930 #elif defined( __WINDOWS__ )
1931 return wxCheckWin32Permission(path
, GENERIC_EXECUTE
);
1939 // Return the type of an open file
1941 // Some file types on some platforms seem seekable but in fact are not.
1942 // The main use of this function is to allow such cases to be detected
1943 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1945 // This is important for the archive streams, which benefit greatly from
1946 // being able to seek on a stream, but which will produce corrupt archives
1947 // if they unknowingly seek on a non-seekable stream.
1949 // wxFILE_KIND_DISK is a good catch all return value, since other values
1950 // disable features of the archive streams. Some other value must be returned
1951 // for a file type that appears seekable but isn't.
1954 // * Pipes on Windows
1955 // * Files on VMS with a record format other than StreamLF
1957 wxFileKind
wxGetFileKind(int fd
)
1959 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1960 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1962 case FILE_TYPE_CHAR
:
1963 return wxFILE_KIND_TERMINAL
;
1964 case FILE_TYPE_DISK
:
1965 return wxFILE_KIND_DISK
;
1966 case FILE_TYPE_PIPE
:
1967 return wxFILE_KIND_PIPE
;
1970 return wxFILE_KIND_UNKNOWN
;
1972 #elif defined(__UNIX__)
1974 return wxFILE_KIND_TERMINAL
;
1979 if (S_ISFIFO(st
.st_mode
))
1980 return wxFILE_KIND_PIPE
;
1981 if (!S_ISREG(st
.st_mode
))
1982 return wxFILE_KIND_UNKNOWN
;
1984 #if defined(__VMS__)
1985 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1986 return wxFILE_KIND_UNKNOWN
;
1989 return wxFILE_KIND_DISK
;
1992 #define wxFILEKIND_STUB
1994 return wxFILE_KIND_DISK
;
1998 wxFileKind
wxGetFileKind(FILE *fp
)
2000 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
2001 // Should be fixed in version 1.4.
2002 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
2004 return wxFILE_KIND_DISK
;
2005 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
2006 return fp
? wxGetFileKind(_fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2008 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2013 //------------------------------------------------------------------------
2014 // wild character routines
2015 //------------------------------------------------------------------------
2017 bool wxIsWild( const wxString
& pattern
)
2019 for ( wxString::const_iterator p
= pattern
.begin(); p
!= pattern
.end(); ++p
)
2021 switch ( (*p
).GetValue() )
2030 if ( ++p
== pattern
.end() )
2038 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
2040 * The match procedure is public domain code (from ircII's reg.c)
2041 * but modified to suit our tastes (RN: No "%" syntax I guess)
2044 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
2048 /* Match if both are empty. */
2052 const wxChar
*m
= pat
.c_str(),
2060 if (dot_special
&& (*n
== wxT('.')))
2062 /* Never match so that hidden Unix files
2063 * are never found. */
2076 else if (*m
== wxT('?'))
2084 if (*m
== wxT('\\'))
2087 /* Quoting "nothing" is a bad thing */
2094 * If we are out of both strings or we just
2095 * saw a wildcard, then we can say we have a
2106 * We could check for *n == NULL at this point, but
2107 * since it's more common to have a character there,
2108 * check to see if they match first (m and n) and
2109 * then if they don't match, THEN we can check for
2125 * If there are no more characters in the
2126 * string, but we still need to find another
2127 * character (*m != NULL), then it will be
2128 * impossible to match it
2147 #pragma warning(default:4706) // assignment within conditional expression