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
298 // ----------------------------------------------------------------------------
300 #if WXWIN_COMPATIBILITY_2_8
301 static inline wxChar
* MYcopystring(const wxString
& s
)
303 wxChar
* copy
= new wxChar
[s
.length() + 1];
304 return wxStrcpy(copy
, s
.c_str());
307 template<typename CharType
>
308 static inline CharType
* MYcopystring(const CharType
* s
)
310 CharType
* copy
= new CharType
[wxStrlen(s
) + 1];
311 return wxStrcpy(copy
, s
);
317 wxFileExists (const wxString
& filename
)
319 #if defined(__WXPALMOS__)
321 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
322 // we must use GetFileAttributes() instead of the ANSI C functions because
323 // it can cope with network (UNC) paths unlike them
324 DWORD ret
= ::GetFileAttributes(filename
.fn_str());
326 return (ret
!= INVALID_FILE_ATTRIBUTES
) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
329 #define S_ISREG(mode) ((mode) & S_IFREG)
332 #ifndef wxNEED_WX_UNISTD_H
333 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
335 || (errno
== EACCES
) // if access is denied something with that name
336 // exists and is opened in exclusive mode.
340 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
342 #endif // __WIN32__/!__WIN32__
346 wxIsAbsolutePath (const wxString
& filename
)
348 if (!filename
.empty())
350 // Unix like or Windows
351 if (filename
[0] == wxT('/'))
354 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
357 #if defined(__WINDOWS__) || defined(__OS2__)
359 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
366 #if WXWIN_COMPATIBILITY_2_8
368 * Strip off any extension (dot something) from end of file,
369 * IF one exists. Inserts zero into buffer.
374 static void wxDoStripExtension(T
*buffer
)
376 int len
= wxStrlen(buffer
);
380 if (buffer
[i
] == wxT('.'))
389 void wxStripExtension(char *buffer
) { wxDoStripExtension(buffer
); }
390 void wxStripExtension(wchar_t *buffer
) { wxDoStripExtension(buffer
); }
392 void wxStripExtension(wxString
& buffer
)
394 //RN: Be careful about the handling the case where
395 //buffer.length() == 0
396 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
398 if (buffer
.GetChar(i
) == wxT('.'))
400 buffer
= buffer
.Left(i
);
406 // Destructive removal of /./ and /../ stuff
407 template<typename CharType
>
408 static CharType
*wxDoRealPath (CharType
*path
)
410 static const CharType SEP
= wxFILE_SEP_PATH
;
412 wxUnix2DosFilename(path
);
414 if (path
[0] && path
[1]) {
415 /* MATTHEW: special case "/./x" */
417 if (path
[2] == SEP
&& path
[1] == wxT('.'))
425 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
428 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
433 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
434 && (q
- 1 <= path
|| q
[-1] != SEP
))
437 if (path
[0] == wxT('\0'))
442 #if defined(__WXMSW__) || defined(__OS2__)
443 /* Check that path[2] is NULL! */
444 else if (path
[1] == wxT(':') && !path
[2])
453 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
461 char *wxRealPath(char *path
)
463 return wxDoRealPath(path
);
466 wchar_t *wxRealPath(wchar_t *path
)
468 return wxDoRealPath(path
);
471 wxString
wxRealPath(const wxString
& path
)
473 wxChar
*buf1
=MYcopystring(path
);
474 wxChar
*buf2
=wxRealPath(buf1
);
482 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
484 if (filename
.empty())
485 return (wxChar
*) NULL
;
487 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
489 wxString buf
= ::wxGetCwd();
490 wxChar ch
= buf
.Last();
492 if (ch
!= wxT('\\') && ch
!= wxT('/'))
498 buf
<< wxFileFunctionsBuffer
;
499 buf
= wxRealPath( buf
);
500 return MYcopystring( buf
);
502 return MYcopystring( wxFileFunctionsBuffer
);
508 ~user/ => user's home dir
509 If the environment variable a = "foo" and b = "bar" then:
526 /* input name in name, pathname output to buf. */
528 template<typename CharType
>
529 static CharType
*wxDoExpandPath(CharType
*buf
, const wxString
& name
)
531 register CharType
*d
, *s
, *nm
;
532 CharType lnm
[_MAXPATHLEN
];
535 // Some compilers don't like this line.
536 // const CharType trimchars[] = wxT("\n \t");
538 CharType trimchars
[4];
539 trimchars
[0] = wxT('\n');
540 trimchars
[1] = wxT(' ');
541 trimchars
[2] = wxT('\t');
544 static const CharType SEP
= wxFILE_SEP_PATH
;
546 //wxUnix2DosFilename(path);
552 nm
= ::MYcopystring(static_cast<const CharType
*>(name
.c_str())); // Make a scratch copy
553 CharType
*nm_tmp
= nm
;
555 /* Skip leading whitespace and cr */
556 while (wxStrchr(trimchars
, *nm
) != NULL
)
558 /* And strip off trailing whitespace and cr */
559 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
560 while (q
-- && wxStrchr(trimchars
, *s
) != NULL
)
568 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
571 /* Expand inline environment variables */
589 while ((*d
++ = *s
) != 0) {
591 if (*s
== wxT('\\')) {
592 if ((*(d
- 1) = *++s
)!=0) {
600 // No env variables on WinCE
603 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
605 if (*s
++ == wxT('$'))
608 register CharType
*start
= d
;
609 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
610 register CharType
*value
;
611 while ((*d
++ = *s
) != 0)
612 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
617 value
= wxGetenv(braces
? start
+ 1 : start
);
619 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
633 /* Expand ~ and ~user */
636 if (nm
[0] == wxT('~') && !q
)
639 if (nm
[1] == SEP
|| nm
[1] == 0)
641 homepath
= wxGetUserHome(wxEmptyString
);
642 if (!homepath
.empty()) {
643 s
= (CharType
*)(const CharType
*)homepath
.c_str();
648 { /* ~user/filename */
649 register CharType
*nnm
;
650 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
654 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
655 was_sep
= (*s
== SEP
);
656 nnm
= *s
? s
+ 1 : s
;
658 homepath
= wxGetUserHome(wxString(nm
+ 1));
659 if (homepath
.empty())
661 if (was_sep
) /* replace only if it was there: */
668 s
= (CharType
*)(const CharType
*)homepath
.c_str();
674 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
676 while (wxT('\0') != (*d
++ = *s
++))
679 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
683 while ((*d
++ = *s
++) != 0)
687 delete[] nm_tmp
; // clean up alloc
688 /* Now clean up the buffer */
689 return wxRealPath(buf
);
692 char *wxExpandPath(char *buf
, const wxString
& name
)
694 return wxDoExpandPath(buf
, name
);
697 wchar_t *wxExpandPath(wchar_t *buf
, const wxString
& name
)
699 return wxDoExpandPath(buf
, name
);
703 /* Contract Paths to be build upon an environment variable
706 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
708 The call wxExpandPath can convert these back!
711 wxContractPath (const wxString
& filename
,
712 const wxString
& WXUNUSED_IN_WINCE(envname
),
713 const wxString
& user
)
715 static wxChar dest
[_MAXPATHLEN
];
717 if (filename
.empty())
718 return (wxChar
*) NULL
;
720 wxStrcpy (dest
, filename
);
722 wxUnix2DosFilename(dest
);
725 // Handle environment
729 if (!envname
.empty() && !(val
= wxGetenv (envname
)).empty() &&
730 (tcp
= wxStrstr (dest
, val
)) != NULL
)
732 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ val
.length());
735 wxStrcpy (tcp
, envname
);
736 wxStrcat (tcp
, wxT("}"));
737 wxStrcat (tcp
, wxFileFunctionsBuffer
);
741 // Handle User's home (ignore root homes!)
742 val
= wxGetUserHome (user
);
746 const size_t len
= val
.length();
750 if (wxStrncmp(dest
, val
, len
) == 0)
752 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
754 wxStrcat(wxFileFunctionsBuffer
, user
);
755 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
756 wxStrcpy (dest
, wxFileFunctionsBuffer
);
762 #endif // #if WXWIN_COMPATIBILITY_2_8
764 // Return just the filename, not the path (basename)
765 wxChar
*wxFileNameFromPath (wxChar
*path
)
768 wxString n
= wxFileNameFromPath(p
);
770 return path
+ p
.length() - n
.length();
773 wxString
wxFileNameFromPath (const wxString
& path
)
776 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
778 wxString fullname
= name
;
781 fullname
<< wxFILE_SEP_EXT
<< ext
;
787 // Return just the directory, or NULL if no directory
789 wxPathOnly (wxChar
*path
)
793 static wxChar buf
[_MAXPATHLEN
];
796 wxStrcpy (buf
, path
);
798 int l
= wxStrlen(path
);
801 // Search backward for a backward or forward slash
804 // Unix like or Windows
805 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
811 if (path
[i
] == wxT(']'))
820 #if defined(__WXMSW__) || defined(__OS2__)
821 // Try Drive specifier
822 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
824 // A:junk --> A:. (since A:.\junk Not A:\junk)
831 return (wxChar
*) NULL
;
834 // Return just the directory, or NULL if no directory
835 wxString
wxPathOnly (const wxString
& path
)
839 wxChar buf
[_MAXPATHLEN
];
844 int l
= path
.length();
847 // Search backward for a backward or forward slash
850 // Unix like or Windows
851 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
853 // Don't return an empty string
857 return wxString(buf
);
860 if (path
[i
] == wxT(']'))
863 return wxString(buf
);
869 #if defined(__WXMSW__) || defined(__OS2__)
870 // Try Drive specifier
871 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
873 // A:junk --> A:. (since A:.\junk Not A:\junk)
876 return wxString(buf
);
880 return wxEmptyString
;
883 // Utility for converting delimiters in DOS filenames to UNIX style
884 // and back again - or we get nasty problems with delimiters.
885 // Also, convert to lower case, since case is significant in UNIX.
887 #if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
889 #define kDefaultPathStyle kCFURLPOSIXPathStyle
891 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
894 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
895 if ( additionalPathComponent
)
897 CFURLRef parentURLRef
= fullURLRef
;
898 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
899 additionalPathComponent
,false);
900 CFRelease( parentURLRef
) ;
902 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
903 CFRelease( fullURLRef
) ;
904 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
905 CFRelease( cfString
);
906 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
907 return wxCFStringRef(cfMutableString
).AsString();
910 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
912 OSStatus err
= noErr
;
913 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxCFStringRef(path
));
914 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
915 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
916 CFRelease( cfMutableString
);
919 if ( CFURLGetFSRef(url
, fsRef
) == false )
930 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
932 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
935 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
937 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
938 return wxCFStringRef(cfMutableString
).AsString() ;
943 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
946 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
948 return wxMacFSRefToPath( &fsRef
) ;
950 return wxEmptyString
;
953 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
955 OSStatus err
= noErr
;
957 wxMacPathToFSRef( path
, &fsRef
);
958 err
= FSGetCatalogInfo(&fsRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
966 #if WXWIN_COMPATIBILITY_2_8
969 static void wxDoDos2UnixFilename(T
*s
)
978 *s
= wxTolower(*s
); // Case INDEPENDENT
984 void wxDos2UnixFilename(char *s
) { wxDoDos2UnixFilename(s
); }
985 void wxDos2UnixFilename(wchar_t *s
) { wxDoDos2UnixFilename(s
); }
989 #if defined(__WXMSW__) || defined(__OS2__)
990 wxDoUnix2DosFilename(T
*s
)
992 wxDoUnix2DosFilename(T
*WXUNUSED(s
) )
995 // Yes, I really mean this to happen under DOS only! JACS
996 #if defined(__WXMSW__) || defined(__OS2__)
1007 void wxUnix2DosFilename(char *s
) { wxDoUnix2DosFilename(s
); }
1008 void wxUnix2DosFilename(wchar_t *s
) { wxDoUnix2DosFilename(s
); }
1010 #endif // #if WXWIN_COMPATIBILITY_2_8
1012 // Concatenate two files to form third
1014 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1018 wxFile
in1(file1
), in2(file2
);
1019 wxTempFile
out(file3
);
1021 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
1025 unsigned char buf
[1024];
1027 for( int i
=0; i
<2; i
++)
1029 wxFile
*in
= i
==0 ? &in1
: &in2
;
1031 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
1033 if ( !out
.Write(buf
,ofs
) )
1035 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1038 return out
.Commit();
1050 // helper of generic implementation of wxCopyFile()
1051 #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1055 wxDoCopyFile(wxFile
& fileIn
,
1056 const wxStructStat
& fbuf
,
1057 const wxString
& filenameDst
,
1060 // reset the umask as we want to create the file with exactly the same
1061 // permissions as the original one
1064 // create file2 with the same permissions than file1 and open it for
1068 if ( !fileOut
.Create(filenameDst
, overwrite
, fbuf
.st_mode
& 0777) )
1071 // copy contents of file1 to file2
1075 ssize_t count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1076 if ( count
== wxInvalidOffset
)
1083 if ( fileOut
.Write(buf
, count
) < (size_t)count
)
1087 // we can expect fileIn to be closed successfully, but we should ensure
1088 // that fileOut was closed as some write errors (disk full) might not be
1089 // detected before doing this
1090 return fileIn
.Close() && fileOut
.Close();
1093 #endif // generic implementation of wxCopyFile
1097 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1099 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1100 // CopyFile() copies file attributes and modification time too, so use it
1101 // instead of our code if available
1103 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1104 if ( !::CopyFile(file1
.fn_str(), file2
.fn_str(), !overwrite
) )
1106 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1107 file1
.c_str(), file2
.c_str());
1111 #elif defined(__OS2__)
1112 if ( ::DosCopy(file1
.c_str(), file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1114 #elif defined(__PALMOS__)
1115 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1117 #elif wxUSE_FILE // !Win32
1120 // get permissions of file1
1121 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1123 // the file probably doesn't exist or we haven't the rights to read
1125 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1130 // open file1 for reading
1131 wxFile
fileIn(file1
, wxFile::read
);
1132 if ( !fileIn
.IsOpened() )
1135 // remove file2, if it exists. This is needed for creating
1136 // file2 with the correct permissions in the next step
1137 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1139 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1144 wxDoCopyFile(fileIn
, fbuf
, file2
, overwrite
);
1146 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1147 // copy the resource fork of the file too if it's present
1148 wxString pathRsrcOut
;
1152 // suppress error messages from this block as resource forks don't have
1156 // it's not enough to check for file existence: it always does on HFS
1157 // but is empty for files without resources
1158 if ( fileRsrcIn
.Open(file1
+ wxT("/..namedfork/rsrc")) &&
1159 fileRsrcIn
.Length() > 0 )
1161 // we must be using HFS or another filesystem with resource fork
1162 // support, suppose that destination file system also is HFS[-like]
1163 pathRsrcOut
= file2
+ wxT("/..namedfork/rsrc");
1165 else // check if we have resource fork in separate file (non-HFS case)
1167 wxFileName
fnRsrc(file1
);
1168 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1171 if ( fileRsrcIn
.Open( fnRsrc
.GetFullPath() ) )
1174 fnRsrc
.SetName(wxT("._") + fnRsrc
.GetName());
1176 pathRsrcOut
= fnRsrc
.GetFullPath();
1181 if ( !pathRsrcOut
.empty() )
1183 if ( !wxDoCopyFile(fileRsrcIn
, fbuf
, pathRsrcOut
, overwrite
) )
1186 #endif // wxMac || wxCocoa
1188 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1189 // no chmod in VA. Should be some permission API for HPFS386 partitions
1191 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1193 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1197 #endif // OS/2 || Mac
1199 #else // !Win32 && ! wxUSE_FILE
1201 // impossible to simulate with wxWidgets API
1204 wxUnusedVar(overwrite
);
1207 #endif // __WXMSW__ && __WIN32__
1213 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1215 if ( !overwrite
&& wxFileExists(file2
) )
1219 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1220 file1
.c_str(), file2
.c_str()
1226 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1227 // Normal system call
1228 if ( wxRename (file1
, file2
) == 0 )
1233 if (wxCopyFile(file1
, file2
, overwrite
)) {
1234 wxRemoveFile(file1
);
1241 bool wxRemoveFile(const wxString
& file
)
1243 #if defined(__VISUALC__) \
1244 || defined(__BORLANDC__) \
1245 || defined(__WATCOMC__) \
1246 || defined(__DMC__) \
1247 || defined(__GNUWIN32__) \
1248 || (defined(__MWERKS__) && defined(__MSL__))
1249 int res
= wxRemove(file
);
1250 #elif defined(__WXMAC__)
1251 int res
= unlink(file
.fn_str());
1252 #elif defined(__WXPALMOS__)
1254 // TODO with VFSFileDelete()
1256 int res
= unlink(OS_FILENAME(file
));
1262 bool wxMkdir(const wxString
& dir
, int perm
)
1264 #if defined(__WXPALMOS__)
1266 #elif defined(__WXMAC__) && !defined(__UNIX__)
1267 return (mkdir(dir
.fn_str() , 0 ) == 0);
1269 const wxChar
*dirname
= dir
.c_str();
1271 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1272 // for the GNU compiler
1273 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1276 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1278 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1280 #elif defined(__OS2__)
1282 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1283 #elif defined(__DOS__)
1284 #if defined(__WATCOMC__)
1286 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1287 #elif defined(__DJGPP__)
1288 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1290 #error "Unsupported DOS compiler!"
1292 #else // !MSW, !DOS and !OS/2 VAC++
1295 if ( !CreateDirectory(dirname
, NULL
) )
1297 if ( wxMkDir(dir
.fn_str()) != 0 )
1301 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1310 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1312 #if defined(__VMS__)
1313 return false; //to be changed since rmdir exists in VMS7.x
1314 #elif defined(__OS2__)
1315 return (::DosDeleteDir(dir
.c_str()) == 0);
1316 #elif defined(__WXWINCE__)
1317 return (RemoveDirectory(dir
) != 0);
1318 #elif defined(__WXPALMOS__)
1319 // TODO with VFSFileRename()
1322 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1326 // does the path exists? (may have or not '/' or '\\' at the end)
1327 bool wxDirExists(const wxString
& pathName
)
1329 wxString
strPath(pathName
);
1331 #if defined(__WINDOWS__) || defined(__OS2__)
1332 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1333 // so remove all trailing backslashes from the path - but don't do this for
1334 // the paths "d:\" (which are different from "d:") nor for just "\"
1335 while ( wxEndsWithPathSeparator(strPath
) )
1337 size_t len
= strPath
.length();
1338 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1341 strPath
.Truncate(len
- 1);
1343 #endif // __WINDOWS__
1346 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1347 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1351 #if defined(__WXPALMOS__)
1353 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1354 // stat() can't cope with network paths
1355 DWORD ret
= ::GetFileAttributes(strPath
.fn_str());
1357 return (ret
!= INVALID_FILE_ATTRIBUTES
) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1358 #elif defined(__OS2__)
1359 FILESTATUS3 Info
= {{0}};
1360 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1361 (void*) &Info
, sizeof(FILESTATUS3
));
1363 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1364 (rc
== ERROR_SHARING_VIOLATION
);
1365 // If we got a sharing violation, there must be something with this name.
1369 #ifndef __VISAGECPP__
1370 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1372 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1373 return wxStat(strPath
.c_str(), &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1376 #endif // __WIN32__/!__WIN32__
1379 #if WXWIN_COMPATIBILITY_2_8
1381 // Get a temporary filename, opening and closing the file.
1382 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1385 if ( !wxGetTempFileName(prefix
, filename
) )
1390 // work around the PalmOS pacc compiler bug
1391 wxStrcpy(buf
, filename
.data());
1393 wxStrcpy(buf
, filename
);
1396 buf
= MYcopystring(filename
);
1401 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1404 buf
= wxFileName::CreateTempFileName(prefix
);
1406 return !buf
.empty();
1407 #else // !wxUSE_FILE
1408 wxUnusedVar(prefix
);
1412 #endif // wxUSE_FILE/!wxUSE_FILE
1415 #endif // #if WXWIN_COMPATIBILITY_2_8
1417 // Get first file name matching given wild card.
1419 static wxDir
*gs_dir
= NULL
;
1420 static wxString gs_dirPath
;
1422 wxString
wxFindFirstFile(const wxString
& spec
, int flags
)
1424 wxFileName::SplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1425 if ( gs_dirPath
.empty() )
1426 gs_dirPath
= wxT(".");
1427 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1428 gs_dirPath
<< wxFILE_SEP_PATH
;
1430 delete gs_dir
; // can be NULL, this is ok
1431 gs_dir
= new wxDir(gs_dirPath
);
1433 if ( !gs_dir
->IsOpened() )
1435 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1436 return wxEmptyString
;
1442 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1443 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1444 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1448 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1449 if ( result
.empty() )
1455 return gs_dirPath
+ result
;
1458 wxString
wxFindNextFile()
1460 wxCHECK_MSG( gs_dir
, "", "You must call wxFindFirstFile before!" );
1463 gs_dir
->GetNext(&result
);
1465 if ( result
.empty() )
1471 return gs_dirPath
+ result
;
1475 // Get current working directory.
1476 // If buf is NULL, allocates space using new, else copies into buf.
1477 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1478 // wxDoGetCwd() is their common core to be moved
1479 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1480 // Do not expose wxDoGetCwd in headers!
1482 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1484 #if defined(__WXPALMOS__)
1486 if(buf
&& sz
>0) buf
[0] = _T('\0');
1488 #elif defined(__WXWINCE__)
1490 if(buf
&& sz
>0) buf
[0] = _T('\0');
1495 buf
= new wxChar
[sz
+ 1];
1498 bool ok
wxDUMMY_INITIALIZE(false);
1500 // for the compilers which have Unicode version of _getcwd(), call it
1501 // directly, for the others call the ANSI version and do the translation
1504 #else // wxUSE_UNICODE
1505 bool needsANSI
= true;
1507 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1508 char cbuf
[_MAXPATHLEN
];
1512 #if wxUSE_UNICODE_MSLU
1513 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1515 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1518 ok
= _wgetcwd(buf
, sz
) != NULL
;
1524 #endif // wxUSE_UNICODE
1526 #if defined(_MSC_VER) || defined(__MINGW32__)
1527 ok
= _getcwd(cbuf
, sz
) != NULL
;
1528 #elif defined(__OS2__)
1530 ULONG ulDriveNum
= 0;
1531 ULONG ulDriveMap
= 0;
1532 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1537 rc
= ::DosQueryCurrentDir( 0 // current drive
1541 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1546 #else // !Win32/VC++ !Mac !OS2
1547 ok
= getcwd(cbuf
, sz
) != NULL
;
1551 // finally convert the result to Unicode if needed
1552 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1553 #endif // wxUSE_UNICODE
1558 wxLogSysError(_("Failed to get the working directory"));
1560 // VZ: the old code used to return "." on error which didn't make any
1561 // sense at all to me - empty string is a better error indicator
1562 // (NULL might be even better but I'm afraid this could lead to
1563 // problems with the old code assuming the return is never NULL)
1566 else // ok, but we might need to massage the path into the right format
1569 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1570 // with / deliminers. We don't like that.
1571 for (wxChar
*ch
= buf
; *ch
; ch
++)
1573 if (*ch
== wxT('/'))
1578 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1579 // he needs Unix as opposed to Win32 pathnames
1580 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1581 // another example of DOS/Unix mix (Cygwin)
1582 wxString pathUnix
= buf
;
1584 char bufA
[_MAXPATHLEN
];
1585 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1586 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1588 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1589 #endif // wxUSE_UNICODE
1590 #endif // __CYGWIN__
1603 #if WXWIN_COMPATIBILITY_2_6
1604 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1606 return wxDoGetCwd(buf
,sz
);
1608 #endif // WXWIN_COMPATIBILITY_2_6
1613 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1617 bool wxSetWorkingDirectory(const wxString
& d
)
1619 #if defined(__OS2__)
1622 ::DosSetDefaultDisk(wxToupper(d
[0]) - _T('A') + 1);
1623 // do not call DosSetCurrentDir when just changing drive,
1624 // since it requires e.g. "d:." instead of "d:"!
1625 if (d
.length() == 2)
1628 return (::DosSetCurrentDir(d
.c_str()) == 0);
1629 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1630 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1631 #elif defined(__WINDOWS__)
1635 // No equivalent in WinCE
1639 return (bool)(SetCurrentDirectory(d
.fn_str()) != 0);
1642 // Must change drive, too.
1643 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1646 wxChar firstChar
= d
[0];
1650 firstChar
= firstChar
- 32;
1652 // To a drive number
1653 unsigned int driveNo
= firstChar
- 64;
1656 unsigned int noDrives
;
1657 _dos_setdrive(driveNo
, &noDrives
);
1660 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1668 // Get the OS directory if appropriate (such as the Windows directory).
1669 // On non-Windows platform, probably just return the empty string.
1670 wxString
wxGetOSDirectory()
1673 return wxString(wxT("\\Windows"));
1674 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1676 GetWindowsDirectory(buf
, 256);
1677 return wxString(buf
);
1678 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1679 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1681 return wxEmptyString
;
1685 bool wxEndsWithPathSeparator(const wxString
& filename
)
1687 return !filename
.empty() && wxIsPathSeparator(filename
.Last());
1690 // find a file in a list of directories, returns false if not found
1691 bool wxFindFileInPath(wxString
*pStr
, const wxString
& szPath
, const wxString
& szFile
)
1693 // we assume that it's not empty
1694 wxCHECK_MSG( !szFile
.empty(), false,
1695 _T("empty file name in wxFindFileInPath"));
1697 // skip path separator in the beginning of the file name if present
1699 if ( wxIsPathSeparator(szFile
[0u]) )
1700 szFile2
= szFile
.Mid(1);
1704 wxStringTokenizer
tkn(szPath
, wxPATH_SEP
);
1706 while ( tkn
.HasMoreTokens() )
1708 wxString strFile
= tkn
.GetNextToken();
1709 if ( !wxEndsWithPathSeparator(strFile
) )
1710 strFile
+= wxFILE_SEP_PATH
;
1713 if ( wxFileExists(strFile
) )
1723 #if WXWIN_COMPATIBILITY_2_8
1724 void WXDLLIMPEXP_BASE
wxSplitPath(const wxString
& fileName
,
1729 wxFileName::SplitPath(fileName
, pstrPath
, pstrName
, pstrExt
);
1731 #endif // #if WXWIN_COMPATIBILITY_2_8
1735 time_t WXDLLIMPEXP_BASE
wxFileModificationTime(const wxString
& filename
)
1738 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1741 return mtime
.GetTicks();
1744 #endif // wxUSE_DATETIME
1747 // Parses the filterStr, returning the number of filters.
1748 // Returns 0 if none or if there's a problem.
1749 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1751 int WXDLLIMPEXP_BASE
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1752 wxArrayString
& descriptions
,
1753 wxArrayString
& filters
)
1755 descriptions
.Clear();
1758 wxString
str(filterStr
);
1760 wxString description
, filter
;
1762 while( pos
!= wxNOT_FOUND
)
1764 pos
= str
.Find(wxT('|'));
1765 if ( pos
== wxNOT_FOUND
)
1767 // if there are no '|'s at all in the string just take the entire
1768 // string as filter and make description empty for later autocompletion
1769 if ( filters
.IsEmpty() )
1771 descriptions
.Add(wxEmptyString
);
1772 filters
.Add(filterStr
);
1776 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1782 description
= str
.Left(pos
);
1783 str
= str
.Mid(pos
+ 1);
1784 pos
= str
.Find(wxT('|'));
1785 if ( pos
== wxNOT_FOUND
)
1791 filter
= str
.Left(pos
);
1792 str
= str
.Mid(pos
+ 1);
1795 descriptions
.Add(description
);
1796 filters
.Add(filter
);
1799 #if defined(__WXMOTIF__)
1800 // split it so there is one wildcard per entry
1801 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1803 pos
= filters
[i
].Find(wxT(';'));
1804 if (pos
!= wxNOT_FOUND
)
1806 // first split only filters
1807 descriptions
.Insert(descriptions
[i
],i
+1);
1808 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1809 filters
[i
]=filters
[i
].Left(pos
);
1811 // autoreplace new filter in description with pattern:
1812 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1813 // cause split into:
1814 // C/C++ Files(*.cpp)|*.cpp
1815 // C/C++ Files(*.c;*.h)|*.c;*.h
1816 // and next iteration cause another split into:
1817 // C/C++ Files(*.cpp)|*.cpp
1818 // C/C++ Files(*.c)|*.c
1819 // C/C++ Files(*.h)|*.h
1820 for ( size_t k
=i
;k
<i
+2;k
++ )
1822 pos
= descriptions
[k
].Find(filters
[k
]);
1823 if (pos
!= wxNOT_FOUND
)
1825 wxString before
= descriptions
[k
].Left(pos
);
1826 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1827 pos
= before
.Find(_T('('),true);
1828 if (pos
>before
.Find(_T(')'),true))
1830 before
= before
.Left(pos
+1);
1831 before
<< filters
[k
];
1832 pos
= after
.Find(_T(')'));
1833 int pos1
= after
.Find(_T('('));
1834 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1836 before
<< after
.Mid(pos
);
1837 descriptions
[k
] = before
;
1847 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1849 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1851 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1855 return filters
.GetCount();
1858 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1859 static bool wxCheckWin32Permission(const wxString
& path
, DWORD access
)
1861 // quoting the MSDN: "To obtain a handle to a directory, call the
1862 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1863 // doesn't work under Win9x/ME but then it's not needed there anyhow
1864 const DWORD dwAttr
= ::GetFileAttributes(path
.fn_str());
1865 if ( dwAttr
== INVALID_FILE_ATTRIBUTES
)
1867 // file probably doesn't exist at all
1871 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
1873 // FAT directories always allow all access, even if they have the
1874 // readonly flag set, and FAT files can only be read-only
1875 return (dwAttr
& FILE_ATTRIBUTE_DIRECTORY
) ||
1876 (access
!= GENERIC_WRITE
||
1877 !(dwAttr
& FILE_ATTRIBUTE_READONLY
));
1880 HANDLE h
= ::CreateFile
1884 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
1887 dwAttr
& FILE_ATTRIBUTE_DIRECTORY
1888 ? FILE_FLAG_BACKUP_SEMANTICS
1892 if ( h
!= INVALID_HANDLE_VALUE
)
1895 return h
!= INVALID_HANDLE_VALUE
;
1897 #endif // __WINDOWS__
1899 bool wxIsWritable(const wxString
&path
)
1901 #if defined( __UNIX__ ) || defined(__OS2__)
1902 // access() will take in count also symbolic links
1903 return wxAccess(path
.c_str(), W_OK
) == 0;
1904 #elif defined( __WINDOWS__ )
1905 return wxCheckWin32Permission(path
, GENERIC_WRITE
);
1913 bool wxIsReadable(const wxString
&path
)
1915 #if defined( __UNIX__ ) || defined(__OS2__)
1916 // access() will take in count also symbolic links
1917 return wxAccess(path
.c_str(), R_OK
) == 0;
1918 #elif defined( __WINDOWS__ )
1919 return wxCheckWin32Permission(path
, GENERIC_READ
);
1927 bool wxIsExecutable(const wxString
&path
)
1929 #if defined( __UNIX__ ) || defined(__OS2__)
1930 // access() will take in count also symbolic links
1931 return wxAccess(path
.c_str(), X_OK
) == 0;
1932 #elif defined( __WINDOWS__ )
1933 return wxCheckWin32Permission(path
, GENERIC_EXECUTE
);
1941 // Return the type of an open file
1943 // Some file types on some platforms seem seekable but in fact are not.
1944 // The main use of this function is to allow such cases to be detected
1945 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1947 // This is important for the archive streams, which benefit greatly from
1948 // being able to seek on a stream, but which will produce corrupt archives
1949 // if they unknowingly seek on a non-seekable stream.
1951 // wxFILE_KIND_DISK is a good catch all return value, since other values
1952 // disable features of the archive streams. Some other value must be returned
1953 // for a file type that appears seekable but isn't.
1956 // * Pipes on Windows
1957 // * Files on VMS with a record format other than StreamLF
1959 wxFileKind
wxGetFileKind(int fd
)
1961 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1962 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1964 case FILE_TYPE_CHAR
:
1965 return wxFILE_KIND_TERMINAL
;
1966 case FILE_TYPE_DISK
:
1967 return wxFILE_KIND_DISK
;
1968 case FILE_TYPE_PIPE
:
1969 return wxFILE_KIND_PIPE
;
1972 return wxFILE_KIND_UNKNOWN
;
1974 #elif defined(__UNIX__)
1976 return wxFILE_KIND_TERMINAL
;
1981 if (S_ISFIFO(st
.st_mode
))
1982 return wxFILE_KIND_PIPE
;
1983 if (!S_ISREG(st
.st_mode
))
1984 return wxFILE_KIND_UNKNOWN
;
1986 #if defined(__VMS__)
1987 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1988 return wxFILE_KIND_UNKNOWN
;
1991 return wxFILE_KIND_DISK
;
1994 #define wxFILEKIND_STUB
1996 return wxFILE_KIND_DISK
;
2000 wxFileKind
wxGetFileKind(FILE *fp
)
2002 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
2003 // Should be fixed in version 1.4.
2004 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
2006 return wxFILE_KIND_DISK
;
2007 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
2008 return fp
? wxGetFileKind(_fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2010 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2015 //------------------------------------------------------------------------
2016 // wild character routines
2017 //------------------------------------------------------------------------
2019 bool wxIsWild( const wxString
& pattern
)
2021 for ( wxString::const_iterator p
= pattern
.begin(); p
!= pattern
.end(); ++p
)
2023 switch ( (*p
).GetValue() )
2032 if ( ++p
== pattern
.end() )
2040 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
2042 * The match procedure is public domain code (from ircII's reg.c)
2043 * but modified to suit our tastes (RN: No "%" syntax I guess)
2046 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
2050 /* Match if both are empty. */
2054 const wxChar
*m
= pat
.c_str(),
2062 if (dot_special
&& (*n
== wxT('.')))
2064 /* Never match so that hidden Unix files
2065 * are never found. */
2078 else if (*m
== wxT('?'))
2086 if (*m
== wxT('\\'))
2089 /* Quoting "nothing" is a bad thing */
2096 * If we are out of both strings or we just
2097 * saw a wildcard, then we can say we have a
2108 * We could check for *n == NULL at this point, but
2109 * since it's more common to have a character there,
2110 * check to see if they match first (m and n) and
2111 * then if they don't match, THEN we can check for
2127 * If there are no more characters in the
2128 * string, but we still need to find another
2129 * character (*m != NULL), then it will be
2130 * impossible to match it
2149 #pragma warning(default:4706) // assignment within conditional expression