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"
37 #include "wx/filename.h"
40 #include "wx/tokenzr.h"
42 // there are just too many of those...
44 #pragma warning(disable:4706) // assignment within conditional expression
51 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
52 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
57 #if defined(__WXMAC__)
58 #include "wx/mac/private.h" // includes mac headers
62 #include "wx/msw/private.h"
63 #include "wx/msw/mslu.h"
65 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
67 // note that it must be included after <windows.h>
70 #include <sys/cygwin.h>
72 #endif // __GNUWIN32__
74 // io.h is needed for _get_osfhandle()
75 // Already included by filefn.h for many Windows compilers
76 #if defined __MWERKS__ || defined __CYGWIN__
85 // TODO: Borland probably has _wgetcwd as well?
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
95 #define _MAXPATHLEN 1024
99 # include "MoreFilesX.h"
102 // ----------------------------------------------------------------------------
104 // ----------------------------------------------------------------------------
106 // MT-FIXME: get rid of this horror and all code using it
107 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
109 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
111 // VisualAge C++ V4.0 cannot have any external linkage const decs
112 // in headers included by more than one primary source
114 const int wxInvalidOffset
= -1;
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 // translate the filenames before passing them to OS functions
122 #define OS_FILENAME(s) (s.fn_str())
124 // ============================================================================
126 // ============================================================================
128 // ----------------------------------------------------------------------------
129 // wrappers around standard POSIX functions
130 // ----------------------------------------------------------------------------
132 #if wxUSE_UNICODE && defined __BORLANDC__ \
133 && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
135 // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
136 // regardless of the mode parameter. This hack works around the problem by
137 // setting the mode with _wchmod.
139 int wxCRT_Open(const wchar_t *pathname
, int flags
, mode_t mode
)
143 // we only want to fix the mode when the file is actually created, so
144 // when creating first try doing it O_EXCL so we can tell if the file
145 // was already there.
146 if ((flags
& O_CREAT
) && !(flags
& O_EXCL
) && (mode
& wxS_IWUSR
) != 0)
149 int fd
= _wopen(pathname
, flags
| moreflags
, mode
);
151 // the file was actually created and needs fixing
152 if (fd
!= -1 && (flags
& O_CREAT
) != 0 && (mode
& wxS_IWUSR
) != 0)
155 _wchmod(pathname
, mode
);
156 fd
= _wopen(pathname
, flags
& ~(O_EXCL
| O_CREAT
));
158 // the open failed, but it may have been because the added O_EXCL stopped
159 // the opening of an existing file, so try again without.
160 else if (fd
== -1 && moreflags
!= 0)
162 fd
= _wopen(pathname
, flags
& ~O_CREAT
);
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 bool wxPathList::Add(const wxString
& path
)
176 // add a path separator to force wxFileName to interpret it always as a directory
177 // (i.e. if we are called with '/home/user' we want to consider it a folder and
178 // not, as wxFileName would consider, a filename).
179 wxFileName
fn(path
+ wxFileName::GetPathSeparator());
181 // add only normalized relative/absolute paths
182 // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
183 // normalize paths which starts with ".." (which can be normalized only if
184 // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
185 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
188 wxString toadd
= fn
.GetPath();
189 if (Index(toadd
) == wxNOT_FOUND
)
190 wxArrayString::Add(toadd
); // do not add duplicates
195 void wxPathList::Add(const wxArrayString
&arr
)
197 for (size_t j
=0; j
< arr
.GetCount(); j
++)
201 // Add paths e.g. from the PATH environment variable
202 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
204 // No environment variables on WinCE
207 // The space has been removed from the tokenizers, otherwise a
208 // path such as "C:\Program Files" would be split into 2 paths:
209 // "C:\Program" and "Files"; this is true for both Windows and Unix.
211 static const wxChar PATH_TOKS
[] =
212 #if defined(__WINDOWS__) || defined(__OS2__)
213 wxT(";"); // Don't separate with colon in DOS (used for drive)
219 if ( wxGetEnv(envVariable
, &val
) )
221 // split into an array of string the value of the env var
222 wxArrayString arr
= wxStringTokenize(val
, PATH_TOKS
);
223 WX_APPEND_ARRAY(*this, arr
);
225 #endif // !__WXWINCE__
228 // Given a full filename (with path), ensure that that file can
229 // be accessed again USING FILENAME ONLY by adding the path
230 // to the list if not already there.
231 bool wxPathList::EnsureFileAccessible (const wxString
& path
)
233 return Add(wxPathOnly(path
));
236 #if WXWIN_COMPATIBILITY_2_6
237 bool wxPathList::Member (const wxString
& path
) const
239 return Index(path
) != wxNOT_FOUND
;
243 wxString
wxPathList::FindValidPath (const wxString
& file
) const
245 // normalize the given string as it could be a path + a filename
246 // and not only a filename
250 // NB: normalize without making absolute otherwise calling this function with
251 // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
252 // below would only add to the paths of this list the 'c.txt' part when doing
253 // the existence checks...
254 // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
255 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
256 return wxEmptyString
;
258 wxASSERT_MSG(!fn
.IsDir(), wxT("Cannot search for directories; only for files"));
260 strend
= fn
.GetFullName(); // search for the file name and ignore the path part
262 strend
= fn
.GetFullPath();
264 for (size_t i
=0; i
<GetCount(); i
++)
266 wxString strstart
= Item(i
);
267 if (!strstart
.IsEmpty() && strstart
.Last() != wxFileName::GetPathSeparator())
268 strstart
+= wxFileName::GetPathSeparator();
270 if (wxFileExists(strstart
+ strend
))
271 return strstart
+ strend
; // Found!
274 return wxEmptyString
; // Not found
277 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
) const
279 wxString f
= FindValidPath(file
);
280 if ( f
.empty() || wxIsAbsolutePath(f
) )
283 wxString buf
= ::wxGetCwd();
285 if ( !wxEndsWithPathSeparator(buf
) )
287 buf
+= wxFILE_SEP_PATH
;
294 // ----------------------------------------------------------------------------
295 // miscellaneous global functions (TOFIX!)
296 // ----------------------------------------------------------------------------
298 static inline wxChar
* MYcopystring(const wxString
& s
)
300 wxChar
* copy
= new wxChar
[s
.length() + 1];
301 return wxStrcpy(copy
, s
.c_str());
304 template<typename CharType
>
305 static inline CharType
* MYcopystring(const CharType
* s
)
307 CharType
* copy
= new CharType
[wxStrlen(s
) + 1];
308 return wxStrcpy(copy
, s
);
313 wxFileExists (const wxString
& filename
)
315 #if defined(__WXPALMOS__)
317 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
318 // we must use GetFileAttributes() instead of the ANSI C functions because
319 // it can cope with network (UNC) paths unlike them
320 DWORD ret
= ::GetFileAttributes(filename
);
322 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
325 #define S_ISREG(mode) ((mode) & S_IFREG)
328 #ifndef wxNEED_WX_UNISTD_H
329 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
331 || (errno
== EACCES
) // if access is denied something with that name
332 // exists and is opened in exclusive mode.
336 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
338 #endif // __WIN32__/!__WIN32__
342 wxIsAbsolutePath (const wxString
& filename
)
344 if (!filename
.empty())
346 #if defined(__WXMAC__) && !defined(__DARWIN__)
347 // Classic or Carbon CodeWarrior like
348 // Carbon with Apple DevTools is Unix like
350 // This seems wrong to me, but there is no fix. since
351 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
352 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
353 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
356 // Unix like or Windows
357 if (filename
[0] == wxT('/'))
361 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
364 #if defined(__WINDOWS__) || defined(__OS2__)
366 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
374 * Strip off any extension (dot something) from end of file,
375 * IF one exists. Inserts zero into buffer.
380 static void wxDoStripExtension(T
*buffer
)
382 int len
= wxStrlen(buffer
);
386 if (buffer
[i
] == wxT('.'))
395 void wxStripExtension(char *buffer
) { wxDoStripExtension(buffer
); }
396 void wxStripExtension(wchar_t *buffer
) { wxDoStripExtension(buffer
); }
398 void wxStripExtension(wxString
& buffer
)
400 //RN: Be careful about the handling the case where
401 //buffer.length() == 0
402 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
404 if (buffer
.GetChar(i
) == wxT('.'))
406 buffer
= buffer
.Left(i
);
412 // Destructive removal of /./ and /../ stuff
413 template<typename CharType
>
414 static CharType
*wxDoRealPath (CharType
*path
)
417 static const CharType SEP
= wxT('\\');
418 wxUnix2DosFilename(path
);
420 static const CharType SEP
= wxT('/');
422 if (path
[0] && path
[1]) {
423 /* MATTHEW: special case "/./x" */
425 if (path
[2] == SEP
&& path
[1] == wxT('.'))
433 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
436 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
441 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
442 && (q
- 1 <= path
|| q
[-1] != SEP
))
445 if (path
[0] == wxT('\0'))
450 #if defined(__WXMSW__) || defined(__OS2__)
451 /* Check that path[2] is NULL! */
452 else if (path
[1] == wxT(':') && !path
[2])
461 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
469 char *wxRealPath(char *path
)
471 return wxDoRealPath(path
);
474 wchar_t *wxRealPath(wchar_t *path
)
476 return wxDoRealPath(path
);
479 wxString
wxRealPath(const wxString
& path
)
481 wxChar
*buf1
=MYcopystring(path
);
482 wxChar
*buf2
=wxRealPath(buf1
);
490 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
492 if (filename
.empty())
493 return (wxChar
*) NULL
;
495 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
497 wxString buf
= ::wxGetCwd();
498 wxChar ch
= buf
.Last();
500 if (ch
!= wxT('\\') && ch
!= wxT('/'))
506 buf
<< wxFileFunctionsBuffer
;
507 buf
= wxRealPath( buf
);
508 return MYcopystring( buf
);
510 return MYcopystring( wxFileFunctionsBuffer
);
516 ~user/ => user's home dir
517 If the environment variable a = "foo" and b = "bar" then:
534 /* input name in name, pathname output to buf. */
536 template<typename CharType
>
537 static CharType
*wxDoExpandPath(CharType
*buf
, const wxString
& name
)
539 register CharType
*d
, *s
, *nm
;
540 CharType lnm
[_MAXPATHLEN
];
543 // Some compilers don't like this line.
544 // const CharType trimchars[] = wxT("\n \t");
546 CharType trimchars
[4];
547 trimchars
[0] = wxT('\n');
548 trimchars
[1] = wxT(' ');
549 trimchars
[2] = wxT('\t');
553 const CharType SEP
= wxT('\\');
555 const CharType SEP
= wxT('/');
560 nm
= MYcopystring((const CharType
*)name
.c_str()); // Make a scratch copy
561 CharType
*nm_tmp
= nm
;
563 /* Skip leading whitespace and cr */
564 while (wxStrchr(trimchars
, *nm
) != NULL
)
566 /* And strip off trailing whitespace and cr */
567 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
568 while (q
-- && wxStrchr(trimchars
, *s
) != NULL
)
576 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
579 /* Expand inline environment variables */
597 while ((*d
++ = *s
) != 0) {
599 if (*s
== wxT('\\')) {
600 if ((*(d
- 1) = *++s
)!=0) {
608 // No env variables on WinCE
611 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
613 if (*s
++ == wxT('$'))
616 register CharType
*start
= d
;
617 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
618 register CharType
*value
;
619 while ((*d
++ = *s
) != 0)
620 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
625 value
= wxGetenv(braces
? start
+ 1 : start
);
627 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
641 /* Expand ~ and ~user */
644 if (nm
[0] == wxT('~') && !q
)
647 if (nm
[1] == SEP
|| nm
[1] == 0)
649 homepath
= wxGetUserHome(wxEmptyString
);
650 if (!homepath
.empty()) {
651 s
= (CharType
*)(const CharType
*)homepath
.c_str();
656 { /* ~user/filename */
657 register CharType
*nnm
;
658 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
662 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
663 was_sep
= (*s
== SEP
);
664 nnm
= *s
? s
+ 1 : s
;
666 homepath
= wxGetUserHome(wxString(nm
+ 1));
667 if (homepath
.empty())
669 if (was_sep
) /* replace only if it was there: */
676 s
= (CharType
*)(const CharType
*)homepath
.c_str();
682 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
684 while (wxT('\0') != (*d
++ = *s
++))
687 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
691 while ((*d
++ = *s
++) != 0)
695 delete[] nm_tmp
; // clean up alloc
696 /* Now clean up the buffer */
697 return wxRealPath(buf
);
700 char *wxExpandPath(char *buf
, const wxString
& name
)
702 return wxDoExpandPath(buf
, name
);
705 wchar_t *wxExpandPath(wchar_t *buf
, const wxString
& name
)
707 return wxDoExpandPath(buf
, name
);
711 /* Contract Paths to be build upon an environment variable
714 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
716 The call wxExpandPath can convert these back!
719 wxContractPath (const wxString
& filename
,
720 const wxString
& WXUNUSED_IN_WINCE(envname
),
721 const wxString
& user
)
723 static wxChar dest
[_MAXPATHLEN
];
725 if (filename
.empty())
726 return (wxChar
*) NULL
;
728 wxStrcpy (dest
, filename
);
730 wxUnix2DosFilename(dest
);
733 // Handle environment
737 if (!envname
.empty() && !(val
= wxGetenv (envname
)).empty() &&
738 (tcp
= wxStrstr (dest
, val
)) != NULL
)
740 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ val
.length());
743 wxStrcpy (tcp
, envname
);
744 wxStrcat (tcp
, wxT("}"));
745 wxStrcat (tcp
, wxFileFunctionsBuffer
);
749 // Handle User's home (ignore root homes!)
750 val
= wxGetUserHome (user
);
754 const size_t len
= val
.length();
758 if (wxStrncmp(dest
, val
, len
) == 0)
760 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
762 wxStrcat(wxFileFunctionsBuffer
, user
);
763 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
764 wxStrcpy (dest
, wxFileFunctionsBuffer
);
770 // Return just the filename, not the path (basename)
771 wxChar
*wxFileNameFromPath (wxChar
*path
)
774 wxString n
= wxFileNameFromPath(p
);
776 return path
+ p
.length() - n
.length();
779 wxString
wxFileNameFromPath (const wxString
& path
)
782 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
784 wxString fullname
= name
;
787 fullname
<< wxFILE_SEP_EXT
<< ext
;
793 // Return just the directory, or NULL if no directory
795 wxPathOnly (wxChar
*path
)
799 static wxChar buf
[_MAXPATHLEN
];
802 wxStrcpy (buf
, path
);
804 int l
= wxStrlen(path
);
807 // Search backward for a backward or forward slash
810 #if defined(__WXMAC__) && !defined(__DARWIN__)
811 // Classic or Carbon CodeWarrior like
812 // Carbon with Apple DevTools is Unix like
813 if (path
[i
] == wxT(':') )
819 // Unix like or Windows
820 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
827 if (path
[i
] == wxT(']'))
836 #if defined(__WXMSW__) || defined(__OS2__)
837 // Try Drive specifier
838 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
840 // A:junk --> A:. (since A:.\junk Not A:\junk)
847 return (wxChar
*) NULL
;
850 // Return just the directory, or NULL if no directory
851 wxString
wxPathOnly (const wxString
& path
)
855 wxChar buf
[_MAXPATHLEN
];
860 int l
= path
.length();
863 // Search backward for a backward or forward slash
866 #if defined(__WXMAC__) && !defined(__DARWIN__)
867 // Classic or Carbon CodeWarrior like
868 // Carbon with Apple DevTools is Unix like
869 if (path
[i
] == wxT(':') )
872 return wxString(buf
);
875 // Unix like or Windows
876 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
878 // Don't return an empty string
882 return wxString(buf
);
886 if (path
[i
] == wxT(']'))
889 return wxString(buf
);
895 #if defined(__WXMSW__) || defined(__OS2__)
896 // Try Drive specifier
897 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
899 // A:junk --> A:. (since A:.\junk Not A:\junk)
902 return wxString(buf
);
906 return wxEmptyString
;
909 // Utility for converting delimiters in DOS filenames to UNIX style
910 // and back again - or we get nasty problems with delimiters.
911 // Also, convert to lower case, since case is significant in UNIX.
913 #if defined(__WXMAC__)
915 #if TARGET_API_MAC_OSX
916 #define kDefaultPathStyle kCFURLPOSIXPathStyle
918 #define kDefaultPathStyle kCFURLHFSPathStyle
921 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
924 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
925 if ( additionalPathComponent
)
927 CFURLRef parentURLRef
= fullURLRef
;
928 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
929 additionalPathComponent
,false);
930 CFRelease( parentURLRef
) ;
932 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
933 CFRelease( fullURLRef
) ;
934 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
935 CFRelease( cfString
);
936 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
937 return wxMacCFStringHolder(cfMutableString
).AsString();
940 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
942 OSStatus err
= noErr
;
943 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxMacCFStringHolder(path
));
944 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
945 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
946 CFRelease( cfMutableString
);
949 if ( CFURLGetFSRef(url
, fsRef
) == false )
960 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
962 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
965 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
967 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
968 return wxMacCFStringHolder(cfMutableString
).AsString() ;
973 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
976 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
978 return wxMacFSRefToPath( &fsRef
) ;
980 return wxEmptyString
;
983 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
985 OSStatus err
= noErr
;
987 wxMacPathToFSRef( path
, &fsRef
) ;
988 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
995 static void wxDoDos2UnixFilename(T
*s
)
1004 *s
= wxTolower(*s
); // Case INDEPENDENT
1010 void wxDos2UnixFilename(char *s
) { wxDoDos2UnixFilename(s
); }
1011 void wxDos2UnixFilename(wchar_t *s
) { wxDoDos2UnixFilename(s
); }
1013 template<typename T
>
1015 #if defined(__WXMSW__) || defined(__OS2__)
1016 wxDoUnix2DosFilename(T
*s
)
1018 wxDoUnix2DosFilename(T
*WXUNUSED(s
) )
1021 // Yes, I really mean this to happen under DOS only! JACS
1022 #if defined(__WXMSW__) || defined(__OS2__)
1033 void wxUnix2DosFilename(char *s
) { wxDoUnix2DosFilename(s
); }
1034 void wxUnix2DosFilename(wchar_t *s
) { wxDoUnix2DosFilename(s
); }
1036 // Concatenate two files to form third
1038 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1042 wxFile
in1(file1
), in2(file2
);
1043 wxTempFile
out(file3
);
1045 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
1049 unsigned char buf
[1024];
1051 for( int i
=0; i
<2; i
++)
1053 wxFile
*in
= i
==0 ? &in1
: &in2
;
1055 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
1057 if ( !out
.Write(buf
,ofs
) )
1059 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1062 return out
.Commit();
1074 // helper of generic implementation of wxCopyFile()
1075 #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1079 wxDoCopyFile(wxFile
& fileIn
,
1080 const wxStructStat
& fbuf
,
1081 const wxString
& filenameDst
,
1084 // reset the umask as we want to create the file with exactly the same
1085 // permissions as the original one
1088 // create file2 with the same permissions than file1 and open it for
1092 if ( !fileOut
.Create(filenameDst
, overwrite
, fbuf
.st_mode
& 0777) )
1095 // copy contents of file1 to file2
1099 ssize_t count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1100 if ( count
== wxInvalidOffset
)
1107 if ( fileOut
.Write(buf
, count
) < (size_t)count
)
1111 // we can expect fileIn to be closed successfully, but we should ensure
1112 // that fileOut was closed as some write errors (disk full) might not be
1113 // detected before doing this
1114 return fileIn
.Close() && fileOut
.Close();
1117 #endif // generic implementation of wxCopyFile
1121 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1123 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1124 // CopyFile() copies file attributes and modification time too, so use it
1125 // instead of our code if available
1127 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1128 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1130 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1131 file1
.c_str(), file2
.c_str());
1135 #elif defined(__OS2__)
1136 if ( ::DosCopy(file1
.c_str(), file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1138 #elif defined(__PALMOS__)
1139 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1141 #elif wxUSE_FILE // !Win32
1144 // get permissions of file1
1145 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1147 // the file probably doesn't exist or we haven't the rights to read
1149 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1154 // open file1 for reading
1155 wxFile
fileIn(file1
, wxFile::read
);
1156 if ( !fileIn
.IsOpened() )
1159 // remove file2, if it exists. This is needed for creating
1160 // file2 with the correct permissions in the next step
1161 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1163 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1168 wxDoCopyFile(fileIn
, fbuf
, file2
, overwrite
);
1170 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1171 // copy the resource fork of the file too if it's present
1172 wxString pathRsrcOut
;
1176 // suppress error messages from this block as resource forks don't have
1180 // it's not enough to check for file existence: it always does on HFS
1181 // but is empty for files without resources
1182 if ( fileRsrcIn
.Open(file1
+ wxT("/..namedfork/rsrc")) &&
1183 fileRsrcIn
.Length() > 0 )
1185 // we must be using HFS or another filesystem with resource fork
1186 // support, suppose that destination file system also is HFS[-like]
1187 pathRsrcOut
= file2
+ wxT("/..namedfork/rsrc");
1189 else // check if we have resource fork in separate file (non-HFS case)
1191 wxFileName
fnRsrc(file1
);
1192 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1195 if ( fileRsrcIn
.Open( fnRsrc
.GetFullPath() ) )
1198 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1200 pathRsrcOut
= fnRsrc
.GetFullPath();
1205 if ( !pathRsrcOut
.empty() )
1207 if ( !wxDoCopyFile(fileRsrcIn
, fbuf
, pathRsrcOut
, overwrite
) )
1210 #endif // wxMac || wxCocoa
1212 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1213 // no chmod in VA. Should be some permission API for HPFS386 partitions
1215 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1217 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1221 #endif // OS/2 || Mac
1223 #else // !Win32 && ! wxUSE_FILE
1225 // impossible to simulate with wxWidgets API
1228 wxUnusedVar(overwrite
);
1231 #endif // __WXMSW__ && __WIN32__
1237 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1239 if ( !overwrite
&& wxFileExists(file2
) )
1243 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1244 file1
.c_str(), file2
.c_str()
1250 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1251 // Normal system call
1252 if ( wxRename (file1
, file2
) == 0 )
1257 if (wxCopyFile(file1
, file2
, overwrite
)) {
1258 wxRemoveFile(file1
);
1265 bool wxRemoveFile(const wxString
& file
)
1267 #if defined(__VISUALC__) \
1268 || defined(__BORLANDC__) \
1269 || defined(__WATCOMC__) \
1270 || defined(__DMC__) \
1271 || defined(__GNUWIN32__) \
1272 || (defined(__MWERKS__) && defined(__MSL__))
1273 int res
= wxRemove(file
);
1274 #elif defined(__WXMAC__)
1275 int res
= unlink(wxFNCONV(file
));
1276 #elif defined(__WXPALMOS__)
1278 // TODO with VFSFileDelete()
1280 int res
= unlink(OS_FILENAME(file
));
1286 bool wxMkdir(const wxString
& dir
, int perm
)
1288 #if defined(__WXPALMOS__)
1290 #elif defined(__WXMAC__) && !defined(__UNIX__)
1291 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1293 const wxChar
*dirname
= dir
.c_str();
1295 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1296 // for the GNU compiler
1297 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1300 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1302 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1304 #elif defined(__OS2__)
1306 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1307 #elif defined(__DOS__)
1308 #if defined(__WATCOMC__)
1310 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1311 #elif defined(__DJGPP__)
1312 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1314 #error "Unsupported DOS compiler!"
1316 #else // !MSW, !DOS and !OS/2 VAC++
1319 if ( !CreateDirectory(dirname
, NULL
) )
1321 if ( wxMkDir(dir
.fn_str()) != 0 )
1325 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1334 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1336 #if defined(__VMS__)
1337 return false; //to be changed since rmdir exists in VMS7.x
1338 #elif defined(__OS2__)
1339 return (::DosDeleteDir(dir
.c_str()) == 0);
1340 #elif defined(__WXWINCE__)
1341 return (RemoveDirectory(dir
) != 0);
1342 #elif defined(__WXPALMOS__)
1343 // TODO with VFSFileRename()
1346 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1350 // does the path exists? (may have or not '/' or '\\' at the end)
1351 bool wxDirExists(const wxString
& pathName
)
1353 wxString
strPath(pathName
);
1355 #if defined(__WINDOWS__) || defined(__OS2__)
1356 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1357 // so remove all trailing backslashes from the path - but don't do this for
1358 // the paths "d:\" (which are different from "d:") nor for just "\"
1359 while ( wxEndsWithPathSeparator(strPath
) )
1361 size_t len
= strPath
.length();
1362 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1365 strPath
.Truncate(len
- 1);
1367 #endif // __WINDOWS__
1370 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1371 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1375 #if defined(__WXPALMOS__)
1377 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1378 // stat() can't cope with network paths
1379 DWORD ret
= ::GetFileAttributes(strPath
);
1381 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1382 #elif defined(__OS2__)
1383 FILESTATUS3 Info
= {{0}};
1384 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1385 (void*) &Info
, sizeof(FILESTATUS3
));
1387 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1388 (rc
== ERROR_SHARING_VIOLATION
);
1389 // If we got a sharing violation, there must be something with this name.
1393 #ifndef __VISAGECPP__
1394 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1396 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1397 return wxStat(strPath
.c_str(), &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1400 #endif // __WIN32__/!__WIN32__
1403 // Get a temporary filename, opening and closing the file.
1404 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1407 if ( !wxGetTempFileName(prefix
, filename
) )
1411 wxStrcpy(buf
, filename
);
1413 buf
= MYcopystring(filename
);
1418 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1421 buf
= wxFileName::CreateTempFileName(prefix
);
1423 return !buf
.empty();
1424 #else // !wxUSE_FILE
1425 wxUnusedVar(prefix
);
1429 #endif // wxUSE_FILE/!wxUSE_FILE
1432 // Get first file name matching given wild card.
1434 static wxDir
*gs_dir
= NULL
;
1435 static wxString gs_dirPath
;
1437 wxString
wxFindFirstFile(const wxString
& spec
, int flags
)
1439 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1440 if ( gs_dirPath
.empty() )
1441 gs_dirPath
= wxT(".");
1442 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1443 gs_dirPath
<< wxFILE_SEP_PATH
;
1447 gs_dir
= new wxDir(gs_dirPath
);
1449 if ( !gs_dir
->IsOpened() )
1451 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1452 return wxEmptyString
;
1458 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1459 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1460 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1464 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1465 if ( result
.empty() )
1471 return gs_dirPath
+ result
;
1474 wxString
wxFindNextFile()
1476 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1479 gs_dir
->GetNext(&result
);
1481 if ( result
.empty() )
1487 return gs_dirPath
+ result
;
1491 // Get current working directory.
1492 // If buf is NULL, allocates space using new, else copies into buf.
1493 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1494 // wxDoGetCwd() is their common core to be moved
1495 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1496 // Do not expose wxDoGetCwd in headers!
1498 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1500 #if defined(__WXPALMOS__)
1502 if(buf
&& sz
>0) buf
[0] = _T('\0');
1504 #elif defined(__WXWINCE__)
1506 if(buf
&& sz
>0) buf
[0] = _T('\0');
1511 buf
= new wxChar
[sz
+ 1];
1514 bool ok
wxDUMMY_INITIALIZE(false);
1516 // for the compilers which have Unicode version of _getcwd(), call it
1517 // directly, for the others call the ANSI version and do the translation
1520 #else // wxUSE_UNICODE
1521 bool needsANSI
= true;
1523 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1524 char cbuf
[_MAXPATHLEN
];
1528 #if wxUSE_UNICODE_MSLU
1529 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1531 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1534 ok
= _wgetcwd(buf
, sz
) != NULL
;
1540 #endif // wxUSE_UNICODE
1542 #if defined(_MSC_VER) || defined(__MINGW32__)
1543 ok
= _getcwd(cbuf
, sz
) != NULL
;
1544 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1546 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1548 wxString
res( lbuf
, *wxConvCurrent
) ;
1549 wxStrcpy( buf
, res
) ;
1554 #elif defined(__OS2__)
1556 ULONG ulDriveNum
= 0;
1557 ULONG ulDriveMap
= 0;
1558 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1563 rc
= ::DosQueryCurrentDir( 0 // current drive
1567 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1572 #else // !Win32/VC++ !Mac !OS2
1573 ok
= getcwd(cbuf
, sz
) != NULL
;
1576 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1577 // finally convert the result to Unicode if needed
1578 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1579 #endif // wxUSE_UNICODE
1584 wxLogSysError(_("Failed to get the working directory"));
1586 // VZ: the old code used to return "." on error which didn't make any
1587 // sense at all to me - empty string is a better error indicator
1588 // (NULL might be even better but I'm afraid this could lead to
1589 // problems with the old code assuming the return is never NULL)
1592 else // ok, but we might need to massage the path into the right format
1595 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1596 // with / deliminers. We don't like that.
1597 for (wxChar
*ch
= buf
; *ch
; ch
++)
1599 if (*ch
== wxT('/'))
1604 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1605 // he needs Unix as opposed to Win32 pathnames
1606 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1607 // another example of DOS/Unix mix (Cygwin)
1608 wxString pathUnix
= buf
;
1610 char bufA
[_MAXPATHLEN
];
1611 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1612 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1614 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1615 #endif // wxUSE_UNICODE
1616 #endif // __CYGWIN__
1629 #if WXWIN_COMPATIBILITY_2_6
1630 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1632 return wxDoGetCwd(buf
,sz
);
1634 #endif // WXWIN_COMPATIBILITY_2_6
1639 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1643 bool wxSetWorkingDirectory(const wxString
& d
)
1645 #if defined(__OS2__)
1648 ::DosSetDefaultDisk(1 + wxToupper(d
[0]) - _T('A'));
1649 // do not call DosSetCurrentDir when just changing drive,
1650 // since it requires e.g. "d:." instead of "d:"!
1651 if (d
.length() == 2)
1654 return (::DosSetCurrentDir(d
.c_str()) == 0);
1655 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1656 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1657 #elif defined(__WINDOWS__)
1661 // No equivalent in WinCE
1665 return (bool)(SetCurrentDirectory(d
) != 0);
1668 // Must change drive, too.
1669 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1672 wxChar firstChar
= d
[0];
1676 firstChar
= firstChar
- 32;
1678 // To a drive number
1679 unsigned int driveNo
= firstChar
- 64;
1682 unsigned int noDrives
;
1683 _dos_setdrive(driveNo
, &noDrives
);
1686 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1694 // Get the OS directory if appropriate (such as the Windows directory).
1695 // On non-Windows platform, probably just return the empty string.
1696 wxString
wxGetOSDirectory()
1699 return wxString(wxT("\\Windows"));
1700 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1702 GetWindowsDirectory(buf
, 256);
1703 return wxString(buf
);
1704 #elif defined(__WXMAC__)
1705 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1707 return wxEmptyString
;
1711 bool wxEndsWithPathSeparator(const wxString
& filename
)
1713 return !filename
.empty() && wxIsPathSeparator(filename
.Last());
1716 // find a file in a list of directories, returns false if not found
1717 bool wxFindFileInPath(wxString
*pStr
, const wxString
& szPath
, const wxString
& szFile
)
1719 // we assume that it's not empty
1720 wxCHECK_MSG( !szFile
.empty(), false,
1721 _T("empty file name in wxFindFileInPath"));
1723 // skip path separator in the beginning of the file name if present
1725 if ( wxIsPathSeparator(szFile
[0u]) )
1726 szFile2
= szFile
.Mid(1);
1730 wxStringTokenizer
tkn(szPath
, wxPATH_SEP
);
1732 while ( tkn
.HasMoreTokens() )
1734 wxString strFile
= tkn
.GetNextToken();
1735 if ( !wxEndsWithPathSeparator(strFile
) )
1736 strFile
+= wxFILE_SEP_PATH
;
1739 if ( wxFileExists(strFile
) )
1749 void WXDLLEXPORT
wxSplitPath(const wxString
& fileName
,
1754 wxFileName::SplitPath(fileName
, pstrPath
, pstrName
, pstrExt
);
1759 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1762 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1765 return mtime
.GetTicks();
1768 #endif // wxUSE_DATETIME
1771 // Parses the filterStr, returning the number of filters.
1772 // Returns 0 if none or if there's a problem.
1773 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1775 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1776 wxArrayString
& descriptions
,
1777 wxArrayString
& filters
)
1779 descriptions
.Clear();
1782 wxString
str(filterStr
);
1784 wxString description
, filter
;
1786 while( pos
!= wxNOT_FOUND
)
1788 pos
= str
.Find(wxT('|'));
1789 if ( pos
== wxNOT_FOUND
)
1791 // if there are no '|'s at all in the string just take the entire
1792 // string as filter and make description empty for later autocompletion
1793 if ( filters
.IsEmpty() )
1795 descriptions
.Add(wxEmptyString
);
1796 filters
.Add(filterStr
);
1800 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1806 description
= str
.Left(pos
);
1807 str
= str
.Mid(pos
+ 1);
1808 pos
= str
.Find(wxT('|'));
1809 if ( pos
== wxNOT_FOUND
)
1815 filter
= str
.Left(pos
);
1816 str
= str
.Mid(pos
+ 1);
1819 descriptions
.Add(description
);
1820 filters
.Add(filter
);
1823 #if defined(__WXMOTIF__)
1824 // split it so there is one wildcard per entry
1825 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1827 pos
= filters
[i
].Find(wxT(';'));
1828 if (pos
!= wxNOT_FOUND
)
1830 // first split only filters
1831 descriptions
.Insert(descriptions
[i
],i
+1);
1832 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1833 filters
[i
]=filters
[i
].Left(pos
);
1835 // autoreplace new filter in description with pattern:
1836 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1837 // cause split into:
1838 // C/C++ Files(*.cpp)|*.cpp
1839 // C/C++ Files(*.c;*.h)|*.c;*.h
1840 // and next iteration cause another split into:
1841 // C/C++ Files(*.cpp)|*.cpp
1842 // C/C++ Files(*.c)|*.c
1843 // C/C++ Files(*.h)|*.h
1844 for ( size_t k
=i
;k
<i
+2;k
++ )
1846 pos
= descriptions
[k
].Find(filters
[k
]);
1847 if (pos
!= wxNOT_FOUND
)
1849 wxString before
= descriptions
[k
].Left(pos
);
1850 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1851 pos
= before
.Find(_T('('),true);
1852 if (pos
>before
.Find(_T(')'),true))
1854 before
= before
.Left(pos
+1);
1855 before
<< filters
[k
];
1856 pos
= after
.Find(_T(')'));
1857 int pos1
= after
.Find(_T('('));
1858 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1860 before
<< after
.Mid(pos
);
1861 descriptions
[k
] = before
;
1871 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1873 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1875 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1879 return filters
.GetCount();
1882 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1883 static bool wxCheckWin32Permission(const wxString
& path
, DWORD access
)
1885 // quoting the MSDN: "To obtain a handle to a directory, call the
1886 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1887 // doesn't work under Win9x/ME but then it's not needed there anyhow
1888 bool isdir
= wxDirExists(path
);
1889 if ( isdir
&& wxGetOsVersion() == wxOS_WINDOWS_9X
)
1891 // FAT directories always allow all access, even if they have the
1892 // readonly flag set
1896 HANDLE h
= ::CreateFile
1900 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1903 isdir
? FILE_FLAG_BACKUP_SEMANTICS
: 0,
1906 if ( h
!= INVALID_HANDLE_VALUE
)
1909 return h
!= INVALID_HANDLE_VALUE
;
1911 #endif // __WINDOWS__
1913 bool wxIsWritable(const wxString
&path
)
1915 #if defined( __UNIX__ ) || defined(__OS2__)
1916 // access() will take in count also symbolic links
1917 return access(path
.fn_str(), W_OK
) == 0;
1918 #elif defined( __WINDOWS__ )
1919 return wxCheckWin32Permission(path
, GENERIC_WRITE
);
1927 bool wxIsReadable(const wxString
&path
)
1929 #if defined( __UNIX__ ) || defined(__OS2__)
1930 // access() will take in count also symbolic links
1931 return access(path
.fn_str(), R_OK
) == 0;
1932 #elif defined( __WINDOWS__ )
1933 return wxCheckWin32Permission(path
, GENERIC_READ
);
1941 bool wxIsExecutable(const wxString
&path
)
1943 #if defined( __UNIX__ ) || defined(__OS2__)
1944 // access() will take in count also symbolic links
1945 return access(path
.fn_str(), X_OK
) == 0;
1946 #elif defined( __WINDOWS__ )
1947 return wxCheckWin32Permission(path
, GENERIC_EXECUTE
);
1955 // Return the type of an open file
1957 // Some file types on some platforms seem seekable but in fact are not.
1958 // The main use of this function is to allow such cases to be detected
1959 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1961 // This is important for the archive streams, which benefit greatly from
1962 // being able to seek on a stream, but which will produce corrupt archives
1963 // if they unknowingly seek on a non-seekable stream.
1965 // wxFILE_KIND_DISK is a good catch all return value, since other values
1966 // disable features of the archive streams. Some other value must be returned
1967 // for a file type that appears seekable but isn't.
1970 // * Pipes on Windows
1971 // * Files on VMS with a record format other than StreamLF
1973 wxFileKind
wxGetFileKind(int fd
)
1975 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1976 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1978 case FILE_TYPE_CHAR
:
1979 return wxFILE_KIND_TERMINAL
;
1980 case FILE_TYPE_DISK
:
1981 return wxFILE_KIND_DISK
;
1982 case FILE_TYPE_PIPE
:
1983 return wxFILE_KIND_PIPE
;
1986 return wxFILE_KIND_UNKNOWN
;
1988 #elif defined(__UNIX__)
1990 return wxFILE_KIND_TERMINAL
;
1995 if (S_ISFIFO(st
.st_mode
))
1996 return wxFILE_KIND_PIPE
;
1997 if (!S_ISREG(st
.st_mode
))
1998 return wxFILE_KIND_UNKNOWN
;
2000 #if defined(__VMS__)
2001 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
2002 return wxFILE_KIND_UNKNOWN
;
2005 return wxFILE_KIND_DISK
;
2008 #define wxFILEKIND_STUB
2010 return wxFILE_KIND_DISK
;
2014 wxFileKind
wxGetFileKind(FILE *fp
)
2016 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
2017 // Should be fixed in version 1.4.
2018 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
2020 return wxFILE_KIND_DISK
;
2021 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
2022 return fp
? wxGetFileKind(_fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2024 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2029 //------------------------------------------------------------------------
2030 // wild character routines
2031 //------------------------------------------------------------------------
2033 bool wxIsWild( const wxString
& pattern
)
2035 for ( wxString::const_iterator p
= pattern
.begin(); p
!= pattern
.end(); ++p
)
2037 switch ( (*p
).GetValue() )
2046 if ( ++p
== pattern
.end() )
2054 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
2056 * The match procedure is public domain code (from ircII's reg.c)
2057 * but modified to suit our tastes (RN: No "%" syntax I guess)
2060 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
2064 /* Match if both are empty. */
2068 const wxChar
*m
= pat
.c_str(),
2076 if (dot_special
&& (*n
== wxT('.')))
2078 /* Never match so that hidden Unix files
2079 * are never found. */
2092 else if (*m
== wxT('?'))
2100 if (*m
== wxT('\\'))
2103 /* Quoting "nothing" is a bad thing */
2110 * If we are out of both strings or we just
2111 * saw a wildcard, then we can say we have a
2122 * We could check for *n == NULL at this point, but
2123 * since it's more common to have a character there,
2124 * check to see if they match first (m and n) and
2125 * then if they don't match, THEN we can check for
2141 * If there are no more characters in the
2142 * string, but we still need to find another
2143 * character (*m != NULL), then it will be
2144 * impossible to match it
2163 #pragma warning(default:4706) // assignment within conditional expression