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/filename.h"
39 #include "wx/tokenzr.h"
41 // there are just too many of those...
43 #pragma warning(disable:4706) // assignment within conditional expression
50 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
51 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
56 #if defined(__WXMAC__)
57 #include "wx/mac/private.h" // includes mac headers
61 #include "wx/msw/private.h"
62 #include "wx/msw/mslu.h"
64 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
66 // note that it must be included after <windows.h>
69 #include <sys/cygwin.h>
71 #endif // __GNUWIN32__
73 // io.h is needed for _get_osfhandle()
74 // Already included by filefn.h for many Windows compilers
75 #if defined __MWERKS__ || defined __CYGWIN__
84 // TODO: Borland probably has _wgetcwd as well?
89 // ----------------------------------------------------------------------------
91 // ----------------------------------------------------------------------------
94 #define _MAXPATHLEN 1024
98 # include "MoreFilesX.h"
101 // ----------------------------------------------------------------------------
103 // ----------------------------------------------------------------------------
105 // MT-FIXME: get rid of this horror and all code using it
106 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
108 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
110 // VisualAge C++ V4.0 cannot have any external linkage const decs
111 // in headers included by more than one primary source
113 const int wxInvalidOffset
= -1;
116 // ----------------------------------------------------------------------------
118 // ----------------------------------------------------------------------------
120 // translate the filenames before passing them to OS functions
121 #define OS_FILENAME(s) (s.fn_str())
123 // ============================================================================
125 // ============================================================================
127 // ----------------------------------------------------------------------------
128 // wrappers around standard POSIX functions
129 // ----------------------------------------------------------------------------
131 #if wxUSE_UNICODE && defined __BORLANDC__ \
132 && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
134 // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
135 // regardless of the mode parameter. This hack works around the problem by
136 // setting the mode with _wchmod.
138 int wxCRT_Open(const wchar_t *pathname
, int flags
, mode_t mode
)
142 // we only want to fix the mode when the file is actually created, so
143 // when creating first try doing it O_EXCL so we can tell if the file
144 // was already there.
145 if ((flags
& O_CREAT
) && !(flags
& O_EXCL
) && (mode
& wxS_IWUSR
) != 0)
148 int fd
= _wopen(pathname
, flags
| moreflags
, mode
);
150 // the file was actually created and needs fixing
151 if (fd
!= -1 && (flags
& O_CREAT
) != 0 && (mode
& wxS_IWUSR
) != 0)
154 _wchmod(pathname
, mode
);
155 fd
= _wopen(pathname
, flags
& ~(O_EXCL
| O_CREAT
));
157 // the open failed, but it may have been because the added O_EXCL stopped
158 // the opening of an existing file, so try again without.
159 else if (fd
== -1 && moreflags
!= 0)
161 fd
= _wopen(pathname
, flags
& ~O_CREAT
);
169 // ----------------------------------------------------------------------------
171 // ----------------------------------------------------------------------------
173 bool wxPathList::Add(const wxString
& path
)
175 // add a path separator to force wxFileName to interpret it always as a directory
176 // (i.e. if we are called with '/home/user' we want to consider it a folder and
177 // not, as wxFileName would consider, a filename).
178 wxFileName
fn(path
+ wxFileName::GetPathSeparator());
180 // add only normalized relative/absolute paths
181 // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
182 // normalize paths which starts with ".." (which can be normalized only if
183 // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
184 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
187 wxString toadd
= fn
.GetPath();
188 if (Index(toadd
) == wxNOT_FOUND
)
189 wxArrayString::Add(toadd
); // do not add duplicates
194 void wxPathList::Add(const wxArrayString
&arr
)
196 for (size_t j
=0; j
< arr
.GetCount(); j
++)
200 // Add paths e.g. from the PATH environment variable
201 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
203 // No environment variables on WinCE
206 // The space has been removed from the tokenizers, otherwise a
207 // path such as "C:\Program Files" would be split into 2 paths:
208 // "C:\Program" and "Files"; this is true for both Windows and Unix.
210 static const wxChar PATH_TOKS
[] =
211 #if defined(__WINDOWS__) || defined(__OS2__)
212 wxT(";"); // Don't separate with colon in DOS (used for drive)
218 if ( wxGetEnv(envVariable
, &val
) )
220 // split into an array of string the value of the env var
221 wxArrayString arr
= wxStringTokenize(val
, PATH_TOKS
);
222 WX_APPEND_ARRAY(*this, arr
);
224 #endif // !__WXWINCE__
227 // Given a full filename (with path), ensure that that file can
228 // be accessed again USING FILENAME ONLY by adding the path
229 // to the list if not already there.
230 bool wxPathList::EnsureFileAccessible (const wxString
& path
)
232 return Add(wxPathOnly(path
));
235 #if WXWIN_COMPATIBILITY_2_6
236 bool wxPathList::Member (const wxString
& path
) const
238 return Index(path
) != wxNOT_FOUND
;
242 wxString
wxPathList::FindValidPath (const wxString
& file
) const
244 // normalize the given string as it could be a path + a filename
245 // and not only a filename
249 // NB: normalize without making absolute otherwise calling this function with
250 // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
251 // below would only add to the paths of this list the 'c.txt' part when doing
252 // the existence checks...
253 // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
254 if (!fn
.Normalize(wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
))
255 return wxEmptyString
;
257 wxASSERT_MSG(!fn
.IsDir(), wxT("Cannot search for directories; only for files"));
259 strend
= fn
.GetFullName(); // search for the file name and ignore the path part
261 strend
= fn
.GetFullPath();
263 for (size_t i
=0; i
<GetCount(); i
++)
265 wxString strstart
= Item(i
);
266 if (!strstart
.IsEmpty() && strstart
.Last() != wxFileName::GetPathSeparator())
267 strstart
+= wxFileName::GetPathSeparator();
269 if (wxFileExists(strstart
+ strend
))
270 return strstart
+ strend
; // Found!
273 return wxEmptyString
; // Not found
276 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
) const
278 wxString f
= FindValidPath(file
);
279 if ( f
.empty() || wxIsAbsolutePath(f
) )
282 wxString buf
= ::wxGetCwd();
284 if ( !wxEndsWithPathSeparator(buf
) )
286 buf
+= wxFILE_SEP_PATH
;
293 // ----------------------------------------------------------------------------
294 // miscellaneous global functions (TOFIX!)
295 // ----------------------------------------------------------------------------
297 static inline wxChar
* MYcopystring(const wxString
& s
)
299 wxChar
* copy
= new wxChar
[s
.length() + 1];
300 return wxStrcpy(copy
, s
.c_str());
303 template<typename CharType
>
304 static inline CharType
* MYcopystring(const CharType
* s
)
306 CharType
* copy
= new CharType
[wxStrlen(s
) + 1];
307 return wxStrcpy(copy
, s
);
312 wxFileExists (const wxString
& filename
)
314 #if defined(__WXPALMOS__)
316 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
317 // we must use GetFileAttributes() instead of the ANSI C functions because
318 // it can cope with network (UNC) paths unlike them
319 DWORD ret
= ::GetFileAttributes(filename
);
321 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
324 #define S_ISREG(mode) ((mode) & S_IFREG)
327 #ifndef wxNEED_WX_UNISTD_H
328 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
330 || (errno
== EACCES
) // if access is denied something with that name
331 // exists and is opened in exclusive mode.
335 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
337 #endif // __WIN32__/!__WIN32__
341 wxIsAbsolutePath (const wxString
& filename
)
343 if (!filename
.empty())
345 #if defined(__WXMAC__) && !defined(__DARWIN__)
346 // Classic or Carbon CodeWarrior like
347 // Carbon with Apple DevTools is Unix like
349 // This seems wrong to me, but there is no fix. since
350 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
351 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
352 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
355 // Unix like or Windows
356 if (filename
[0] == wxT('/'))
360 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
363 #if defined(__WINDOWS__) || defined(__OS2__)
365 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
373 * Strip off any extension (dot something) from end of file,
374 * IF one exists. Inserts zero into buffer.
379 static void wxDoStripExtension(T
*buffer
)
381 int len
= wxStrlen(buffer
);
385 if (buffer
[i
] == wxT('.'))
394 void wxStripExtension(char *buffer
) { wxDoStripExtension(buffer
); }
395 void wxStripExtension(wchar_t *buffer
) { wxDoStripExtension(buffer
); }
397 void wxStripExtension(wxString
& buffer
)
399 //RN: Be careful about the handling the case where
400 //buffer.length() == 0
401 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
403 if (buffer
.GetChar(i
) == wxT('.'))
405 buffer
= buffer
.Left(i
);
411 // Destructive removal of /./ and /../ stuff
412 template<typename CharType
>
413 static CharType
*wxDoRealPath (CharType
*path
)
416 static const CharType SEP
= wxT('\\');
417 wxUnix2DosFilename(path
);
419 static const CharType SEP
= wxT('/');
421 if (path
[0] && path
[1]) {
422 /* MATTHEW: special case "/./x" */
424 if (path
[2] == SEP
&& path
[1] == wxT('.'))
432 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
435 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
440 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
441 && (q
- 1 <= path
|| q
[-1] != SEP
))
444 if (path
[0] == wxT('\0'))
449 #if defined(__WXMSW__) || defined(__OS2__)
450 /* Check that path[2] is NULL! */
451 else if (path
[1] == wxT(':') && !path
[2])
460 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
468 char *wxRealPath(char *path
)
470 return wxDoRealPath(path
);
473 wchar_t *wxRealPath(wchar_t *path
)
475 return wxDoRealPath(path
);
478 wxString
wxRealPath(const wxString
& path
)
480 wxChar
*buf1
=MYcopystring(path
);
481 wxChar
*buf2
=wxRealPath(buf1
);
489 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
491 if (filename
.empty())
492 return (wxChar
*) NULL
;
494 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
496 wxString buf
= ::wxGetCwd();
497 wxChar ch
= buf
.Last();
499 if (ch
!= wxT('\\') && ch
!= wxT('/'))
505 buf
<< wxFileFunctionsBuffer
;
506 buf
= wxRealPath( buf
);
507 return MYcopystring( buf
);
509 return MYcopystring( wxFileFunctionsBuffer
);
515 ~user/ => user's home dir
516 If the environment variable a = "foo" and b = "bar" then:
533 /* input name in name, pathname output to buf. */
535 template<typename CharType
>
536 static CharType
*wxDoExpandPath(CharType
*buf
, const wxString
& name
)
538 register CharType
*d
, *s
, *nm
;
539 CharType lnm
[_MAXPATHLEN
];
542 // Some compilers don't like this line.
543 // const CharType trimchars[] = wxT("\n \t");
545 CharType trimchars
[4];
546 trimchars
[0] = wxT('\n');
547 trimchars
[1] = wxT(' ');
548 trimchars
[2] = wxT('\t');
552 const CharType SEP
= wxT('\\');
554 const CharType SEP
= wxT('/');
559 nm
= MYcopystring((const CharType
*)name
.c_str()); // Make a scratch copy
560 CharType
*nm_tmp
= nm
;
562 /* Skip leading whitespace and cr */
563 while (wxStrchr(trimchars
, *nm
) != NULL
)
565 /* And strip off trailing whitespace and cr */
566 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
567 while (q
-- && wxStrchr(trimchars
, *s
) != NULL
)
575 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
578 /* Expand inline environment variables */
596 while ((*d
++ = *s
) != 0) {
598 if (*s
== wxT('\\')) {
599 if ((*(d
- 1) = *++s
)!=0) {
607 // No env variables on WinCE
610 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
612 if (*s
++ == wxT('$'))
615 register CharType
*start
= d
;
616 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
617 register CharType
*value
;
618 while ((*d
++ = *s
) != 0)
619 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
624 value
= wxGetenv(braces
? start
+ 1 : start
);
626 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
640 /* Expand ~ and ~user */
643 if (nm
[0] == wxT('~') && !q
)
646 if (nm
[1] == SEP
|| nm
[1] == 0)
648 homepath
= wxGetUserHome(wxEmptyString
);
649 if (!homepath
.empty()) {
650 s
= (CharType
*)(const CharType
*)homepath
.c_str();
655 { /* ~user/filename */
656 register CharType
*nnm
;
657 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
661 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
662 was_sep
= (*s
== SEP
);
663 nnm
= *s
? s
+ 1 : s
;
665 homepath
= wxGetUserHome(wxString(nm
+ 1));
666 if (homepath
.empty())
668 if (was_sep
) /* replace only if it was there: */
675 s
= (CharType
*)(const CharType
*)homepath
.c_str();
681 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
683 while (wxT('\0') != (*d
++ = *s
++))
686 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
690 while ((*d
++ = *s
++) != 0)
694 delete[] nm_tmp
; // clean up alloc
695 /* Now clean up the buffer */
696 return wxRealPath(buf
);
699 char *wxExpandPath(char *buf
, const wxString
& name
)
701 return wxDoExpandPath(buf
, name
);
704 wchar_t *wxExpandPath(wchar_t *buf
, const wxString
& name
)
706 return wxDoExpandPath(buf
, name
);
710 /* Contract Paths to be build upon an environment variable
713 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
715 The call wxExpandPath can convert these back!
718 wxContractPath (const wxString
& filename
,
719 const wxString
& WXUNUSED_IN_WINCE(envname
),
720 const wxString
& user
)
722 static wxChar dest
[_MAXPATHLEN
];
724 if (filename
.empty())
725 return (wxChar
*) NULL
;
727 wxStrcpy (dest
, filename
);
729 wxUnix2DosFilename(dest
);
732 // Handle environment
736 if (!envname
.empty() && !(val
= wxGetenv (envname
)).empty() &&
737 (tcp
= wxStrstr (dest
, val
)) != NULL
)
739 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ val
.length());
742 wxStrcpy (tcp
, envname
);
743 wxStrcat (tcp
, wxT("}"));
744 wxStrcat (tcp
, wxFileFunctionsBuffer
);
748 // Handle User's home (ignore root homes!)
749 val
= wxGetUserHome (user
);
753 const size_t len
= val
.length();
757 if (wxStrncmp(dest
, val
, len
) == 0)
759 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
761 wxStrcat(wxFileFunctionsBuffer
, user
);
762 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
763 wxStrcpy (dest
, wxFileFunctionsBuffer
);
769 // Return just the filename, not the path (basename)
770 wxChar
*wxFileNameFromPath (wxChar
*path
)
773 wxString n
= wxFileNameFromPath(p
);
775 return path
+ p
.length() - n
.length();
778 wxString
wxFileNameFromPath (const wxString
& path
)
781 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
783 wxString fullname
= name
;
786 fullname
<< wxFILE_SEP_EXT
<< ext
;
792 // Return just the directory, or NULL if no directory
794 wxPathOnly (wxChar
*path
)
798 static wxChar buf
[_MAXPATHLEN
];
801 wxStrcpy (buf
, path
);
803 int l
= wxStrlen(path
);
806 // Search backward for a backward or forward slash
809 #if defined(__WXMAC__) && !defined(__DARWIN__)
810 // Classic or Carbon CodeWarrior like
811 // Carbon with Apple DevTools is Unix like
812 if (path
[i
] == wxT(':') )
818 // Unix like or Windows
819 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
826 if (path
[i
] == wxT(']'))
835 #if defined(__WXMSW__) || defined(__OS2__)
836 // Try Drive specifier
837 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
839 // A:junk --> A:. (since A:.\junk Not A:\junk)
846 return (wxChar
*) NULL
;
849 // Return just the directory, or NULL if no directory
850 wxString
wxPathOnly (const wxString
& path
)
854 wxChar buf
[_MAXPATHLEN
];
859 int l
= path
.length();
862 // Search backward for a backward or forward slash
865 #if defined(__WXMAC__) && !defined(__DARWIN__)
866 // Classic or Carbon CodeWarrior like
867 // Carbon with Apple DevTools is Unix like
868 if (path
[i
] == wxT(':') )
871 return wxString(buf
);
874 // Unix like or Windows
875 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
877 // Don't return an empty string
881 return wxString(buf
);
885 if (path
[i
] == wxT(']'))
888 return wxString(buf
);
894 #if defined(__WXMSW__) || defined(__OS2__)
895 // Try Drive specifier
896 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
898 // A:junk --> A:. (since A:.\junk Not A:\junk)
901 return wxString(buf
);
905 return wxEmptyString
;
908 // Utility for converting delimiters in DOS filenames to UNIX style
909 // and back again - or we get nasty problems with delimiters.
910 // Also, convert to lower case, since case is significant in UNIX.
912 #if defined(__WXMAC__)
914 #if TARGET_API_MAC_OSX
915 #define kDefaultPathStyle kCFURLPOSIXPathStyle
917 #define kDefaultPathStyle kCFURLHFSPathStyle
920 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
923 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
924 if ( additionalPathComponent
)
926 CFURLRef parentURLRef
= fullURLRef
;
927 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
928 additionalPathComponent
,false);
929 CFRelease( parentURLRef
) ;
931 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
932 CFRelease( fullURLRef
) ;
933 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
934 CFRelease( cfString
);
935 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
936 return wxMacCFStringHolder(cfMutableString
).AsString();
939 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
941 OSStatus err
= noErr
;
942 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxMacCFStringHolder(path
));
943 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
944 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
945 CFRelease( cfMutableString
);
948 if ( CFURLGetFSRef(url
, fsRef
) == false )
959 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
961 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
964 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
966 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
967 return wxMacCFStringHolder(cfMutableString
).AsString() ;
972 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
975 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
977 return wxMacFSRefToPath( &fsRef
) ;
979 return wxEmptyString
;
982 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
984 OSStatus err
= noErr
;
986 wxMacPathToFSRef( path
, &fsRef
) ;
987 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
994 static void wxDoDos2UnixFilename(T
*s
)
1003 *s
= wxTolower(*s
); // Case INDEPENDENT
1009 void wxDos2UnixFilename(char *s
) { wxDoDos2UnixFilename(s
); }
1010 void wxDos2UnixFilename(wchar_t *s
) { wxDoDos2UnixFilename(s
); }
1012 template<typename T
>
1014 #if defined(__WXMSW__) || defined(__OS2__)
1015 wxDoUnix2DosFilename(T
*s
)
1017 wxDoUnix2DosFilename(T
*WXUNUSED(s
) )
1020 // Yes, I really mean this to happen under DOS only! JACS
1021 #if defined(__WXMSW__) || defined(__OS2__)
1032 void wxUnix2DosFilename(char *s
) { wxDoUnix2DosFilename(s
); }
1033 void wxUnix2DosFilename(wchar_t *s
) { wxDoUnix2DosFilename(s
); }
1035 // Concatenate two files to form third
1037 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1041 wxFile
in1(file1
), in2(file2
);
1042 wxTempFile
out(file3
);
1044 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
1048 unsigned char buf
[1024];
1050 for( int i
=0; i
<2; i
++)
1052 wxFile
*in
= i
==0 ? &in1
: &in2
;
1054 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
1056 if ( !out
.Write(buf
,ofs
) )
1058 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1061 return out
.Commit();
1073 // helper of generic implementation of wxCopyFile()
1074 #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1078 wxDoCopyFile(wxFile
& fileIn
,
1079 const wxStructStat
& fbuf
,
1080 const wxString
& filenameDst
,
1083 // reset the umask as we want to create the file with exactly the same
1084 // permissions as the original one
1087 // create file2 with the same permissions than file1 and open it for
1091 if ( !fileOut
.Create(filenameDst
, overwrite
, fbuf
.st_mode
& 0777) )
1094 // copy contents of file1 to file2
1098 ssize_t count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1099 if ( count
== wxInvalidOffset
)
1106 if ( fileOut
.Write(buf
, count
) < (size_t)count
)
1110 // we can expect fileIn to be closed successfully, but we should ensure
1111 // that fileOut was closed as some write errors (disk full) might not be
1112 // detected before doing this
1113 return fileIn
.Close() && fileOut
.Close();
1116 #endif // generic implementation of wxCopyFile
1120 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1122 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1123 // CopyFile() copies file attributes and modification time too, so use it
1124 // instead of our code if available
1126 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1127 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1129 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1130 file1
.c_str(), file2
.c_str());
1134 #elif defined(__OS2__)
1135 if ( ::DosCopy(file1
.c_str(), file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1137 #elif defined(__PALMOS__)
1138 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1140 #elif wxUSE_FILE // !Win32
1143 // get permissions of file1
1144 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1146 // the file probably doesn't exist or we haven't the rights to read
1148 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1153 // open file1 for reading
1154 wxFile
fileIn(file1
, wxFile::read
);
1155 if ( !fileIn
.IsOpened() )
1158 // remove file2, if it exists. This is needed for creating
1159 // file2 with the correct permissions in the next step
1160 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1162 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1167 wxDoCopyFile(fileIn
, fbuf
, file2
, overwrite
);
1169 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1170 // copy the resource fork of the file too if it's present
1171 wxString pathRsrcOut
;
1175 // suppress error messages from this block as resource forks don't have
1179 // it's not enough to check for file existence: it always does on HFS
1180 // but is empty for files without resources
1181 if ( fileRsrcIn
.Open(file1
+ wxT("/..namedfork/rsrc")) &&
1182 fileRsrcIn
.Length() > 0 )
1184 // we must be using HFS or another filesystem with resource fork
1185 // support, suppose that destination file system also is HFS[-like]
1186 pathRsrcOut
= file2
+ wxT("/..namedfork/rsrc");
1188 else // check if we have resource fork in separate file (non-HFS case)
1190 wxFileName
fnRsrc(file1
);
1191 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1194 if ( fileRsrcIn
.Open( fnRsrc
.GetFullPath() ) )
1197 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1199 pathRsrcOut
= fnRsrc
.GetFullPath();
1204 if ( !pathRsrcOut
.empty() )
1206 if ( !wxDoCopyFile(fileRsrcIn
, fbuf
, pathRsrcOut
, overwrite
) )
1209 #endif // wxMac || wxCocoa
1211 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1212 // no chmod in VA. Should be some permission API for HPFS386 partitions
1214 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1216 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1220 #endif // OS/2 || Mac
1222 #else // !Win32 && ! wxUSE_FILE
1224 // impossible to simulate with wxWidgets API
1227 wxUnusedVar(overwrite
);
1230 #endif // __WXMSW__ && __WIN32__
1236 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1238 if ( !overwrite
&& wxFileExists(file2
) )
1242 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1243 file1
.c_str(), file2
.c_str()
1249 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1250 // Normal system call
1251 if ( wxRename (file1
, file2
) == 0 )
1256 if (wxCopyFile(file1
, file2
, overwrite
)) {
1257 wxRemoveFile(file1
);
1264 bool wxRemoveFile(const wxString
& file
)
1266 #if defined(__VISUALC__) \
1267 || defined(__BORLANDC__) \
1268 || defined(__WATCOMC__) \
1269 || defined(__DMC__) \
1270 || defined(__GNUWIN32__) \
1271 || (defined(__MWERKS__) && defined(__MSL__))
1272 int res
= wxRemove(file
);
1273 #elif defined(__WXMAC__)
1274 int res
= unlink(wxFNCONV(file
));
1275 #elif defined(__WXPALMOS__)
1277 // TODO with VFSFileDelete()
1279 int res
= unlink(OS_FILENAME(file
));
1285 bool wxMkdir(const wxString
& dir
, int perm
)
1287 #if defined(__WXPALMOS__)
1289 #elif defined(__WXMAC__) && !defined(__UNIX__)
1290 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1292 const wxChar
*dirname
= dir
.c_str();
1294 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1295 // for the GNU compiler
1296 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1299 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1301 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1303 #elif defined(__OS2__)
1305 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1306 #elif defined(__DOS__)
1307 #if defined(__WATCOMC__)
1309 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1310 #elif defined(__DJGPP__)
1311 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1313 #error "Unsupported DOS compiler!"
1315 #else // !MSW, !DOS and !OS/2 VAC++
1318 if ( !CreateDirectory(dirname
, NULL
) )
1320 if ( wxMkDir(dir
.fn_str()) != 0 )
1324 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1333 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1335 #if defined(__VMS__)
1336 return false; //to be changed since rmdir exists in VMS7.x
1337 #elif defined(__OS2__)
1338 return (::DosDeleteDir(dir
.c_str()) == 0);
1339 #elif defined(__WXWINCE__)
1340 return (RemoveDirectory(dir
) != 0);
1341 #elif defined(__WXPALMOS__)
1342 // TODO with VFSFileRename()
1345 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1349 // does the path exists? (may have or not '/' or '\\' at the end)
1350 bool wxDirExists(const wxString
& pathName
)
1352 wxString
strPath(pathName
);
1354 #if defined(__WINDOWS__) || defined(__OS2__)
1355 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1356 // so remove all trailing backslashes from the path - but don't do this for
1357 // the paths "d:\" (which are different from "d:") nor for just "\"
1358 while ( wxEndsWithPathSeparator(strPath
) )
1360 size_t len
= strPath
.length();
1361 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1364 strPath
.Truncate(len
- 1);
1366 #endif // __WINDOWS__
1369 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1370 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1374 #if defined(__WXPALMOS__)
1376 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1377 // stat() can't cope with network paths
1378 DWORD ret
= ::GetFileAttributes(strPath
);
1380 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1381 #elif defined(__OS2__)
1382 FILESTATUS3 Info
= {{0}};
1383 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1384 (void*) &Info
, sizeof(FILESTATUS3
));
1386 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1387 (rc
== ERROR_SHARING_VIOLATION
);
1388 // If we got a sharing violation, there must be something with this name.
1392 #ifndef __VISAGECPP__
1393 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1395 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1396 return wxStat(strPath
.c_str(), &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1399 #endif // __WIN32__/!__WIN32__
1402 // Get a temporary filename, opening and closing the file.
1403 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1406 if ( !wxGetTempFileName(prefix
, filename
) )
1410 wxStrcpy(buf
, filename
);
1412 buf
= MYcopystring(filename
);
1417 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1420 buf
= wxFileName::CreateTempFileName(prefix
);
1422 return !buf
.empty();
1423 #else // !wxUSE_FILE
1424 wxUnusedVar(prefix
);
1428 #endif // wxUSE_FILE/!wxUSE_FILE
1431 // Get first file name matching given wild card.
1433 static wxDir
*gs_dir
= NULL
;
1434 static wxString gs_dirPath
;
1436 wxString
wxFindFirstFile(const wxString
& spec
, int flags
)
1438 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1439 if ( gs_dirPath
.empty() )
1440 gs_dirPath
= wxT(".");
1441 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1442 gs_dirPath
<< wxFILE_SEP_PATH
;
1446 gs_dir
= new wxDir(gs_dirPath
);
1448 if ( !gs_dir
->IsOpened() )
1450 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1451 return wxEmptyString
;
1457 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1458 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1459 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1463 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1464 if ( result
.empty() )
1470 return gs_dirPath
+ result
;
1473 wxString
wxFindNextFile()
1475 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1478 gs_dir
->GetNext(&result
);
1480 if ( result
.empty() )
1486 return gs_dirPath
+ result
;
1490 // Get current working directory.
1491 // If buf is NULL, allocates space using new, else copies into buf.
1492 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1493 // wxDoGetCwd() is their common core to be moved
1494 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1495 // Do not expose wxDoGetCwd in headers!
1497 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1499 #if defined(__WXPALMOS__)
1501 if(buf
&& sz
>0) buf
[0] = _T('\0');
1503 #elif defined(__WXWINCE__)
1505 if(buf
&& sz
>0) buf
[0] = _T('\0');
1510 buf
= new wxChar
[sz
+ 1];
1513 bool ok
wxDUMMY_INITIALIZE(false);
1515 // for the compilers which have Unicode version of _getcwd(), call it
1516 // directly, for the others call the ANSI version and do the translation
1519 #else // wxUSE_UNICODE
1520 bool needsANSI
= true;
1522 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1523 char cbuf
[_MAXPATHLEN
];
1527 #if wxUSE_UNICODE_MSLU
1528 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1530 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1533 ok
= _wgetcwd(buf
, sz
) != NULL
;
1539 #endif // wxUSE_UNICODE
1541 #if defined(_MSC_VER) || defined(__MINGW32__)
1542 ok
= _getcwd(cbuf
, sz
) != NULL
;
1543 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1545 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1547 wxString
res( lbuf
, *wxConvCurrent
) ;
1548 wxStrcpy( buf
, res
) ;
1553 #elif defined(__OS2__)
1555 ULONG ulDriveNum
= 0;
1556 ULONG ulDriveMap
= 0;
1557 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1562 rc
= ::DosQueryCurrentDir( 0 // current drive
1566 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1571 #else // !Win32/VC++ !Mac !OS2
1572 ok
= getcwd(cbuf
, sz
) != NULL
;
1575 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1576 // finally convert the result to Unicode if needed
1577 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1578 #endif // wxUSE_UNICODE
1583 wxLogSysError(_("Failed to get the working directory"));
1585 // VZ: the old code used to return "." on error which didn't make any
1586 // sense at all to me - empty string is a better error indicator
1587 // (NULL might be even better but I'm afraid this could lead to
1588 // problems with the old code assuming the return is never NULL)
1591 else // ok, but we might need to massage the path into the right format
1594 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1595 // with / deliminers. We don't like that.
1596 for (wxChar
*ch
= buf
; *ch
; ch
++)
1598 if (*ch
== wxT('/'))
1603 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1604 // he needs Unix as opposed to Win32 pathnames
1605 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1606 // another example of DOS/Unix mix (Cygwin)
1607 wxString pathUnix
= buf
;
1609 char bufA
[_MAXPATHLEN
];
1610 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1611 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1613 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1614 #endif // wxUSE_UNICODE
1615 #endif // __CYGWIN__
1628 #if WXWIN_COMPATIBILITY_2_6
1629 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1631 return wxDoGetCwd(buf
,sz
);
1633 #endif // WXWIN_COMPATIBILITY_2_6
1638 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1642 bool wxSetWorkingDirectory(const wxString
& d
)
1644 #if defined(__OS2__)
1647 ::DosSetDefaultDisk(1 + wxToupper(d
[0]) - _T('A'));
1648 // do not call DosSetCurrentDir when just changing drive,
1649 // since it requires e.g. "d:." instead of "d:"!
1650 if (d
.length() == 2)
1653 return (::DosSetCurrentDir(d
.c_str()) == 0);
1654 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1655 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1656 #elif defined(__WINDOWS__)
1660 // No equivalent in WinCE
1664 return (bool)(SetCurrentDirectory(d
) != 0);
1667 // Must change drive, too.
1668 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1671 wxChar firstChar
= d
[0];
1675 firstChar
= firstChar
- 32;
1677 // To a drive number
1678 unsigned int driveNo
= firstChar
- 64;
1681 unsigned int noDrives
;
1682 _dos_setdrive(driveNo
, &noDrives
);
1685 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1693 // Get the OS directory if appropriate (such as the Windows directory).
1694 // On non-Windows platform, probably just return the empty string.
1695 wxString
wxGetOSDirectory()
1698 return wxString(wxT("\\Windows"));
1699 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1701 GetWindowsDirectory(buf
, 256);
1702 return wxString(buf
);
1703 #elif defined(__WXMAC__)
1704 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1706 return wxEmptyString
;
1710 bool wxEndsWithPathSeparator(const wxString
& filename
)
1712 return !filename
.empty() && wxIsPathSeparator(filename
.Last());
1715 // find a file in a list of directories, returns false if not found
1716 bool wxFindFileInPath(wxString
*pStr
, const wxString
& szPath
, const wxString
& szFile
)
1718 // we assume that it's not empty
1719 wxCHECK_MSG( !szFile
.empty(), false,
1720 _T("empty file name in wxFindFileInPath"));
1722 // skip path separator in the beginning of the file name if present
1724 if ( wxIsPathSeparator(szFile
[0u]) )
1725 szFile2
= szFile
.Mid(1);
1729 wxStringTokenizer
tkn(szPath
, wxPATH_SEP
);
1731 while ( tkn
.HasMoreTokens() )
1733 wxString strFile
= tkn
.GetNextToken();
1734 if ( !wxEndsWithPathSeparator(strFile
) )
1735 strFile
+= wxFILE_SEP_PATH
;
1738 if ( wxFileExists(strFile
) )
1748 void WXDLLEXPORT
wxSplitPath(const wxString
& fileName
,
1753 wxFileName::SplitPath(fileName
, pstrPath
, pstrName
, pstrExt
);
1758 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1761 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1764 return mtime
.GetTicks();
1767 #endif // wxUSE_DATETIME
1770 // Parses the filterStr, returning the number of filters.
1771 // Returns 0 if none or if there's a problem.
1772 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1774 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1775 wxArrayString
& descriptions
,
1776 wxArrayString
& filters
)
1778 descriptions
.Clear();
1781 wxString
str(filterStr
);
1783 wxString description
, filter
;
1785 while( pos
!= wxNOT_FOUND
)
1787 pos
= str
.Find(wxT('|'));
1788 if ( pos
== wxNOT_FOUND
)
1790 // if there are no '|'s at all in the string just take the entire
1791 // string as filter and make description empty for later autocompletion
1792 if ( filters
.IsEmpty() )
1794 descriptions
.Add(wxEmptyString
);
1795 filters
.Add(filterStr
);
1799 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1805 description
= str
.Left(pos
);
1806 str
= str
.Mid(pos
+ 1);
1807 pos
= str
.Find(wxT('|'));
1808 if ( pos
== wxNOT_FOUND
)
1814 filter
= str
.Left(pos
);
1815 str
= str
.Mid(pos
+ 1);
1818 descriptions
.Add(description
);
1819 filters
.Add(filter
);
1822 #if defined(__WXMOTIF__)
1823 // split it so there is one wildcard per entry
1824 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1826 pos
= filters
[i
].Find(wxT(';'));
1827 if (pos
!= wxNOT_FOUND
)
1829 // first split only filters
1830 descriptions
.Insert(descriptions
[i
],i
+1);
1831 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1832 filters
[i
]=filters
[i
].Left(pos
);
1834 // autoreplace new filter in description with pattern:
1835 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1836 // cause split into:
1837 // C/C++ Files(*.cpp)|*.cpp
1838 // C/C++ Files(*.c;*.h)|*.c;*.h
1839 // and next iteration cause another split into:
1840 // C/C++ Files(*.cpp)|*.cpp
1841 // C/C++ Files(*.c)|*.c
1842 // C/C++ Files(*.h)|*.h
1843 for ( size_t k
=i
;k
<i
+2;k
++ )
1845 pos
= descriptions
[k
].Find(filters
[k
]);
1846 if (pos
!= wxNOT_FOUND
)
1848 wxString before
= descriptions
[k
].Left(pos
);
1849 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1850 pos
= before
.Find(_T('('),true);
1851 if (pos
>before
.Find(_T(')'),true))
1853 before
= before
.Left(pos
+1);
1854 before
<< filters
[k
];
1855 pos
= after
.Find(_T(')'));
1856 int pos1
= after
.Find(_T('('));
1857 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1859 before
<< after
.Mid(pos
);
1860 descriptions
[k
] = before
;
1870 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1872 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1874 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1878 return filters
.GetCount();
1881 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1882 static bool wxCheckWin32Permission(const wxString
& path
, DWORD access
)
1884 // quoting the MSDN: "To obtain a handle to a directory, call the
1885 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1886 // doesn't work under Win9x/ME but then it's not needed there anyhow
1887 bool isdir
= wxDirExists(path
);
1888 if ( isdir
&& wxGetOsVersion() == wxOS_WINDOWS_9X
)
1890 // FAT directories always allow all access, even if they have the
1891 // readonly flag set
1895 HANDLE h
= ::CreateFile
1899 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1902 isdir
? FILE_FLAG_BACKUP_SEMANTICS
: 0,
1905 if ( h
!= INVALID_HANDLE_VALUE
)
1908 return h
!= INVALID_HANDLE_VALUE
;
1910 #endif // __WINDOWS__
1912 bool wxIsWritable(const wxString
&path
)
1914 #if defined( __UNIX__ ) || defined(__OS2__)
1915 // access() will take in count also symbolic links
1916 return access(path
.fn_str(), W_OK
) == 0;
1917 #elif defined( __WINDOWS__ )
1918 return wxCheckWin32Permission(path
, GENERIC_WRITE
);
1926 bool wxIsReadable(const wxString
&path
)
1928 #if defined( __UNIX__ ) || defined(__OS2__)
1929 // access() will take in count also symbolic links
1930 return access(path
.fn_str(), R_OK
) == 0;
1931 #elif defined( __WINDOWS__ )
1932 return wxCheckWin32Permission(path
, GENERIC_READ
);
1940 bool wxIsExecutable(const wxString
&path
)
1942 #if defined( __UNIX__ ) || defined(__OS2__)
1943 // access() will take in count also symbolic links
1944 return access(path
.fn_str(), X_OK
) == 0;
1945 #elif defined( __WINDOWS__ )
1946 return wxCheckWin32Permission(path
, GENERIC_EXECUTE
);
1954 // Return the type of an open file
1956 // Some file types on some platforms seem seekable but in fact are not.
1957 // The main use of this function is to allow such cases to be detected
1958 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1960 // This is important for the archive streams, which benefit greatly from
1961 // being able to seek on a stream, but which will produce corrupt archives
1962 // if they unknowingly seek on a non-seekable stream.
1964 // wxFILE_KIND_DISK is a good catch all return value, since other values
1965 // disable features of the archive streams. Some other value must be returned
1966 // for a file type that appears seekable but isn't.
1969 // * Pipes on Windows
1970 // * Files on VMS with a record format other than StreamLF
1972 wxFileKind
wxGetFileKind(int fd
)
1974 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1975 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1977 case FILE_TYPE_CHAR
:
1978 return wxFILE_KIND_TERMINAL
;
1979 case FILE_TYPE_DISK
:
1980 return wxFILE_KIND_DISK
;
1981 case FILE_TYPE_PIPE
:
1982 return wxFILE_KIND_PIPE
;
1985 return wxFILE_KIND_UNKNOWN
;
1987 #elif defined(__UNIX__)
1989 return wxFILE_KIND_TERMINAL
;
1994 if (S_ISFIFO(st
.st_mode
))
1995 return wxFILE_KIND_PIPE
;
1996 if (!S_ISREG(st
.st_mode
))
1997 return wxFILE_KIND_UNKNOWN
;
1999 #if defined(__VMS__)
2000 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
2001 return wxFILE_KIND_UNKNOWN
;
2004 return wxFILE_KIND_DISK
;
2007 #define wxFILEKIND_STUB
2009 return wxFILE_KIND_DISK
;
2013 wxFileKind
wxGetFileKind(FILE *fp
)
2015 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
2016 // Should be fixed in version 1.4.
2017 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
2019 return wxFILE_KIND_DISK
;
2020 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
2021 return fp
? wxGetFileKind(_fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2023 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2028 //------------------------------------------------------------------------
2029 // wild character routines
2030 //------------------------------------------------------------------------
2032 bool wxIsWild( const wxString
& pattern
)
2034 for ( wxString::const_iterator p
= pattern
.begin(); p
!= pattern
.end(); ++p
)
2036 switch ( (*p
).GetValue() )
2045 if ( ++p
== pattern
.end() )
2053 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
2055 * The match procedure is public domain code (from ircII's reg.c)
2056 * but modified to suit our tastes (RN: No "%" syntax I guess)
2059 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
2063 /* Match if both are empty. */
2067 const wxChar
*m
= pat
.c_str(),
2075 if (dot_special
&& (*n
== wxT('.')))
2077 /* Never match so that hidden Unix files
2078 * are never found. */
2091 else if (*m
== wxT('?'))
2099 if (*m
== wxT('\\'))
2102 /* Quoting "nothing" is a bad thing */
2109 * If we are out of both strings or we just
2110 * saw a wildcard, then we can say we have a
2121 * We could check for *n == NULL at this point, but
2122 * since it's more common to have a character there,
2123 * check to see if they match first (m and n) and
2124 * then if they don't match, THEN we can check for
2140 * If there are no more characters in the
2141 * string, but we still need to find another
2142 * character (*m != NULL), then it will be
2143 * impossible to match it
2162 #pragma warning(default:4706) // assignment within conditional expression