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"
33 #include "wx/file.h" // This does include filefn.h
34 #include "wx/filename.h"
37 #include "wx/tokenzr.h"
39 // there are just too many of those...
41 #pragma warning(disable:4706) // assignment within conditional expression
48 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
49 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
54 #if defined(__WXMAC__)
55 #include "wx/mac/private.h" // includes mac headers
59 #include "wx/msw/private.h"
60 #include "wx/msw/mslu.h"
62 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
64 // note that it must be included after <windows.h>
67 #include <sys/cygwin.h>
69 #endif // __GNUWIN32__
71 // io.h is needed for _get_osfhandle()
72 // Already included by filefn.h for many Windows compilers
73 #if defined __MWERKS__ || defined __CYGWIN__
82 // TODO: Borland probably has _wgetcwd as well?
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
92 #define _MAXPATHLEN 1024
96 # include "MoreFilesX.h"
99 // ----------------------------------------------------------------------------
101 // ----------------------------------------------------------------------------
103 // MT-FIXME: get rid of this horror and all code using it
104 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
106 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
108 // VisualAge C++ V4.0 cannot have any external linkage const decs
109 // in headers included by more than one primary source
111 const int wxInvalidOffset
= -1;
114 // ----------------------------------------------------------------------------
116 // ----------------------------------------------------------------------------
118 // we need to translate Mac filenames before passing them to OS functions
119 #define OS_FILENAME(s) (s.fn_str())
121 // ============================================================================
123 // ============================================================================
125 #ifdef wxNEED_WX_UNISTD_H
127 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
129 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
132 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
134 return access( wxConvFile
.cWX2MB( pathname
), mode
);
137 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
139 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
143 // wxNEED_WX_UNISTD_H
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
149 void wxPathList::Add(const wxString
& path
)
151 // add a path separator to force wxFileName to interpret it always as a directory
152 // (i.e. if we are called with '/home/user' we want to consider it a folder and
153 // not, as wxFileName would consider, a filename).
154 wxFileName
fn(path
+ wxFileName::GetPathSeparator());
156 // add only normalized relative/absolute paths
157 fn
.Normalize(wxPATH_NORM_DOTS
|wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
);
159 wxString toadd
= fn
.GetPath();
160 if (Index(toadd
) == wxNOT_FOUND
)
161 wxArrayString::Add(toadd
); // do not add duplicates
164 void wxPathList::Add(const wxArrayString
&arr
)
166 for (size_t j
=0; j
< arr
.GetCount(); j
++)
170 // Add paths e.g. from the PATH environment variable
171 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
173 // No environment variables on WinCE
176 // The space has been removed from the tokenizers, otherwise a
177 // path such as "C:\Program Files" would be split into 2 paths:
178 // "C:\Program" and "Files"; this is true for both Windows and Unix.
180 static const wxChar PATH_TOKS
[] =
181 #if defined(__WINDOWS__) || defined(__OS2__)
182 wxT(";"); // Don't separate with colon in DOS (used for drive)
188 if ( wxGetEnv(envVariable
, &val
) )
190 // split into an array of string the value of the env var
191 wxArrayString arr
= wxStringTokenize(val
, PATH_TOKS
);
192 WX_APPEND_ARRAY(*this, arr
);
194 #endif // !__WXWINCE__
197 // Given a full filename (with path), ensure that that file can
198 // be accessed again USING FILENAME ONLY by adding the path
199 // to the list if not already there.
200 void wxPathList::EnsureFileAccessible (const wxString
& path
)
202 wxString
path_only(wxPathOnly(path
));
203 if ( !path_only
.empty() )
205 if ( Index(path_only
) == wxNOT_FOUND
)
211 bool wxPathList::Member (const wxString
& path
) const
213 return Index(path
) != wxNOT_FOUND
;
216 wxString
wxPathList::FindValidPath (const wxString
& file
) const
218 // normalize the given string as it could be a path + a filename
219 // and not only a filename
223 // NB: normalize without making absolute !
224 fn
.Normalize(wxPATH_NORM_DOTS
|wxPATH_NORM_TILDE
|wxPATH_NORM_LONG
|wxPATH_NORM_ENV_VARS
);
226 wxASSERT_MSG(!fn
.IsDir(), wxT("Cannot search for directories; only for files"));
228 strend
= fn
.GetFullName(); // search for the file name and ignore the path part
230 strend
= fn
.GetFullPath();
232 for (size_t i
=0; i
<GetCount(); i
++)
234 wxString strstart
= Item(i
);
235 if (!strstart
.IsEmpty() && strstart
.Last() != wxFileName::GetPathSeparator())
236 strstart
+= wxFileName::GetPathSeparator();
238 if (wxFileExists(strstart
+ strend
))
239 return strstart
+ strend
; // Found!
242 return wxEmptyString
; // Not found
245 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
) const
247 wxString f
= FindValidPath(file
);
248 if ( f
.empty() || wxIsAbsolutePath(f
) )
251 wxString buf
= ::wxGetCwd();
253 if ( !wxEndsWithPathSeparator(buf
) )
255 buf
+= wxFILE_SEP_PATH
;
262 // ----------------------------------------------------------------------------
263 // miscellaneous global functions (TOFIX!)
264 // ----------------------------------------------------------------------------
266 static inline wxChar
* MYcopystring(const wxString
& s
)
268 wxChar
* copy
= new wxChar
[s
.length() + 1];
269 return wxStrcpy(copy
, s
.c_str());
272 static inline wxChar
* MYcopystring(const wxChar
* s
)
274 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
275 return wxStrcpy(copy
, s
);
280 wxFileExists (const wxString
& filename
)
282 #if defined(__WXPALMOS__)
284 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
285 // we must use GetFileAttributes() instead of the ANSI C functions because
286 // it can cope with network (UNC) paths unlike them
287 DWORD ret
= ::GetFileAttributes(filename
);
289 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
292 #define S_ISREG(mode) ((mode) & S_IFREG)
295 #ifndef wxNEED_WX_UNISTD_H
296 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
298 || (errno
== EACCES
) // if access is denied something with that name
299 // exists and is opened in exclusive mode.
303 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
305 #endif // __WIN32__/!__WIN32__
309 wxIsAbsolutePath (const wxString
& filename
)
311 if (!filename
.empty())
313 #if defined(__WXMAC__) && !defined(__DARWIN__)
314 // Classic or Carbon CodeWarrior like
315 // Carbon with Apple DevTools is Unix like
317 // This seems wrong to me, but there is no fix. since
318 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
319 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
320 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
323 // Unix like or Windows
324 if (filename
[0] == wxT('/'))
328 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
331 #if defined(__WINDOWS__) || defined(__OS2__)
333 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
341 * Strip off any extension (dot something) from end of file,
342 * IF one exists. Inserts zero into buffer.
346 void wxStripExtension(wxChar
*buffer
)
348 int len
= wxStrlen(buffer
);
352 if (buffer
[i
] == wxT('.'))
361 void wxStripExtension(wxString
& buffer
)
363 //RN: Be careful about the handling the case where
364 //buffer.length() == 0
365 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
367 if (buffer
.GetChar(i
) == wxT('.'))
369 buffer
= buffer
.Left(i
);
375 // Destructive removal of /./ and /../ stuff
376 wxChar
*wxRealPath (wxChar
*path
)
379 static const wxChar SEP
= wxT('\\');
380 wxUnix2DosFilename(path
);
382 static const wxChar SEP
= wxT('/');
384 if (path
[0] && path
[1]) {
385 /* MATTHEW: special case "/./x" */
387 if (path
[2] == SEP
&& path
[1] == wxT('.'))
395 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
398 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
403 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
404 && (q
- 1 <= path
|| q
[-1] != SEP
))
407 if (path
[0] == wxT('\0'))
412 #if defined(__WXMSW__) || defined(__OS2__)
413 /* Check that path[2] is NULL! */
414 else if (path
[1] == wxT(':') && !path
[2])
423 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
431 wxString
wxRealPath(const wxString
& path
)
433 wxChar
*buf1
=MYcopystring(path
);
434 wxChar
*buf2
=wxRealPath(buf1
);
442 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
444 if (filename
.empty())
445 return (wxChar
*) NULL
;
447 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
449 wxString buf
= ::wxGetCwd();
450 wxChar ch
= buf
.Last();
452 if (ch
!= wxT('\\') && ch
!= wxT('/'))
458 buf
<< wxFileFunctionsBuffer
;
459 buf
= wxRealPath( buf
);
460 return MYcopystring( buf
);
462 return MYcopystring( wxFileFunctionsBuffer
);
468 ~user/ => user's home dir
469 If the environment variable a = "foo" and b = "bar" then:
486 /* input name in name, pathname output to buf. */
488 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
490 register wxChar
*d
, *s
, *nm
;
491 wxChar lnm
[_MAXPATHLEN
];
494 // Some compilers don't like this line.
495 // const wxChar trimchars[] = wxT("\n \t");
498 trimchars
[0] = wxT('\n');
499 trimchars
[1] = wxT(' ');
500 trimchars
[2] = wxT('\t');
504 const wxChar SEP
= wxT('\\');
506 const wxChar SEP
= wxT('/');
509 if (name
== NULL
|| *name
== wxT('\0'))
511 nm
= MYcopystring(name
); // Make a scratch copy
514 /* Skip leading whitespace and cr */
515 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
517 /* And strip off trailing whitespace and cr */
518 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
519 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
527 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
530 /* Expand inline environment variables */
548 while ((*d
++ = *s
) != 0) {
550 if (*s
== wxT('\\')) {
551 if ((*(d
- 1) = *++s
)!=0) {
559 // No env variables on WinCE
562 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
564 if (*s
++ == wxT('$'))
567 register wxChar
*start
= d
;
568 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
569 register wxChar
*value
;
570 while ((*d
++ = *s
) != 0)
571 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
576 value
= wxGetenv(braces
? start
+ 1 : start
);
578 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
592 /* Expand ~ and ~user */
594 if (nm
[0] == wxT('~') && !q
)
597 if (nm
[1] == SEP
|| nm
[1] == 0)
599 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
600 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
605 { /* ~user/filename */
606 register wxChar
*nnm
;
607 register wxChar
*home
;
608 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
612 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
613 was_sep
= (*s
== SEP
);
614 nnm
= *s
? s
+ 1 : s
;
616 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
617 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
)
619 if (was_sep
) /* replace only if it was there: */
632 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
634 while (wxT('\0') != (*d
++ = *s
++))
637 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
641 while ((*d
++ = *s
++) != 0)
645 delete[] nm_tmp
; // clean up alloc
646 /* Now clean up the buffer */
647 return wxRealPath(buf
);
650 /* Contract Paths to be build upon an environment variable
653 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
655 The call wxExpandPath can convert these back!
658 wxContractPath (const wxString
& filename
,
659 const wxString
& WXUNUSED_IN_WINCE(envname
),
660 const wxString
& user
)
662 static wxChar dest
[_MAXPATHLEN
];
664 if (filename
.empty())
665 return (wxChar
*) NULL
;
667 wxStrcpy (dest
, WXSTRINGCAST filename
);
669 wxUnix2DosFilename(dest
);
672 // Handle environment
676 if (!envname
.empty() && (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
677 (tcp
= wxStrstr (dest
, val
)) != NULL
)
679 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
682 wxStrcpy (tcp
, WXSTRINGCAST envname
);
683 wxStrcat (tcp
, wxT("}"));
684 wxStrcat (tcp
, wxFileFunctionsBuffer
);
688 // Handle User's home (ignore root homes!)
689 val
= wxGetUserHome (user
);
693 const size_t len
= wxStrlen(val
);
697 if (wxStrncmp(dest
, val
, len
) == 0)
699 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
701 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
702 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
703 wxStrcpy (dest
, wxFileFunctionsBuffer
);
709 // Return just the filename, not the path (basename)
710 wxChar
*wxFileNameFromPath (wxChar
*path
)
713 wxString n
= wxFileNameFromPath(p
);
715 return path
+ p
.length() - n
.length();
718 wxString
wxFileNameFromPath (const wxString
& path
)
721 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
723 wxString fullname
= name
;
726 fullname
<< wxFILE_SEP_EXT
<< ext
;
732 // Return just the directory, or NULL if no directory
734 wxPathOnly (wxChar
*path
)
738 static wxChar buf
[_MAXPATHLEN
];
741 wxStrcpy (buf
, path
);
743 int l
= wxStrlen(path
);
746 // Search backward for a backward or forward slash
749 #if defined(__WXMAC__) && !defined(__DARWIN__)
750 // Classic or Carbon CodeWarrior like
751 // Carbon with Apple DevTools is Unix like
752 if (path
[i
] == wxT(':') )
758 // Unix like or Windows
759 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
766 if (path
[i
] == wxT(']'))
775 #if defined(__WXMSW__) || defined(__OS2__)
776 // Try Drive specifier
777 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
779 // A:junk --> A:. (since A:.\junk Not A:\junk)
786 return (wxChar
*) NULL
;
789 // Return just the directory, or NULL if no directory
790 wxString
wxPathOnly (const wxString
& path
)
794 wxChar buf
[_MAXPATHLEN
];
797 wxStrcpy (buf
, WXSTRINGCAST path
);
799 int l
= path
.length();
802 // Search backward for a backward or forward slash
805 #if defined(__WXMAC__) && !defined(__DARWIN__)
806 // Classic or Carbon CodeWarrior like
807 // Carbon with Apple DevTools is Unix like
808 if (path
[i
] == wxT(':') )
811 return wxString(buf
);
814 // Unix like or Windows
815 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
817 // Don't return an empty string
821 return wxString(buf
);
825 if (path
[i
] == wxT(']'))
828 return wxString(buf
);
834 #if defined(__WXMSW__) || defined(__OS2__)
835 // Try Drive specifier
836 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
838 // A:junk --> A:. (since A:.\junk Not A:\junk)
841 return wxString(buf
);
845 return wxEmptyString
;
848 // Utility for converting delimiters in DOS filenames to UNIX style
849 // and back again - or we get nasty problems with delimiters.
850 // Also, convert to lower case, since case is significant in UNIX.
852 #if defined(__WXMAC__)
854 #if TARGET_API_MAC_OSX
855 #define kDefaultPathStyle kCFURLPOSIXPathStyle
857 #define kDefaultPathStyle kCFURLHFSPathStyle
860 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
863 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
864 if ( additionalPathComponent
)
866 CFURLRef parentURLRef
= fullURLRef
;
867 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
868 additionalPathComponent
,false);
869 CFRelease( parentURLRef
) ;
871 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
872 CFRelease( fullURLRef
) ;
873 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
874 CFRelease( cfString
);
875 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
876 return wxMacCFStringHolder(cfMutableString
).AsString();
879 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
881 OSStatus err
= noErr
;
882 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxMacCFStringHolder(path
));
883 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
884 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
885 CFRelease( cfMutableString
);
888 if ( CFURLGetFSRef(url
, fsRef
) == false )
899 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
901 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
904 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
906 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
907 return wxMacCFStringHolder(cfMutableString
).AsString() ;
912 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
915 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
917 return wxMacFSRefToPath( &fsRef
) ;
919 return wxEmptyString
;
922 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
924 OSStatus err
= noErr
;
926 wxMacPathToFSRef( path
, &fsRef
) ;
927 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
934 wxDos2UnixFilename (wxChar
*s
)
943 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
950 #if defined(__WXMSW__) || defined(__OS2__)
951 wxUnix2DosFilename (wxChar
*s
)
953 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
956 // Yes, I really mean this to happen under DOS only! JACS
957 #if defined(__WXMSW__) || defined(__OS2__)
968 // Concatenate two files to form third
970 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
974 wxFile
in1(file1
), in2(file2
);
975 wxTempFile
out(file3
);
977 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
981 unsigned char buf
[1024];
983 for( int i
=0; i
<2; i
++)
985 wxFile
*in
= i
==0 ? &in1
: &in2
;
987 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
989 if ( !out
.Write(buf
,ofs
) )
991 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1008 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1010 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1011 // CopyFile() copies file attributes and modification time too, so use it
1012 // instead of our code if available
1014 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1015 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1017 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1018 file1
.c_str(), file2
.c_str());
1022 #elif defined(__OS2__)
1023 if ( ::DosCopy((PSZ
)file1
.c_str(), (PSZ
)file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1025 #elif defined(__PALMOS__)
1026 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1028 #elif wxUSE_FILE // !Win32
1031 // get permissions of file1
1032 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1034 // the file probably doesn't exist or we haven't the rights to read
1036 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1041 // open file1 for reading
1042 wxFile
fileIn(file1
, wxFile::read
);
1043 if ( !fileIn
.IsOpened() )
1046 // remove file2, if it exists. This is needed for creating
1047 // file2 with the correct permissions in the next step
1048 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1050 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1055 // reset the umask as we want to create the file with exactly the same
1056 // permissions as the original one
1059 // create file2 with the same permissions than file1 and open it for
1063 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1066 // copy contents of file1 to file2
1071 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1072 if ( fileIn
.Error() )
1079 if ( fileOut
.Write(buf
, count
) < count
)
1083 // we can expect fileIn to be closed successfully, but we should ensure
1084 // that fileOut was closed as some write errors (disk full) might not be
1085 // detected before doing this
1086 if ( !fileIn
.Close() || !fileOut
.Close() )
1089 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1090 // no chmod in VA. Should be some permission API for HPFS386 partitions
1092 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1094 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1098 #endif // OS/2 || Mac
1100 #else // !Win32 && ! wxUSE_FILE
1102 // impossible to simulate with wxWidgets API
1105 wxUnusedVar(overwrite
);
1108 #endif // __WXMSW__ && __WIN32__
1114 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1116 if ( !overwrite
&& wxFileExists(file2
) )
1120 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1121 file1
.c_str(), file2
.c_str()
1127 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1128 // Normal system call
1129 if ( wxRename (file1
, file2
) == 0 )
1134 if (wxCopyFile(file1
, file2
, overwrite
)) {
1135 wxRemoveFile(file1
);
1142 bool wxRemoveFile(const wxString
& file
)
1144 #if defined(__VISUALC__) \
1145 || defined(__BORLANDC__) \
1146 || defined(__WATCOMC__) \
1147 || defined(__DMC__) \
1148 || defined(__GNUWIN32__) \
1149 || (defined(__MWERKS__) && defined(__MSL__))
1150 int res
= wxRemove(file
);
1151 #elif defined(__WXMAC__)
1152 int res
= unlink(wxFNCONV(file
));
1153 #elif defined(__WXPALMOS__)
1155 // TODO with VFSFileDelete()
1157 int res
= unlink(OS_FILENAME(file
));
1163 bool wxMkdir(const wxString
& dir
, int perm
)
1165 #if defined(__WXPALMOS__)
1167 #elif defined(__WXMAC__) && !defined(__UNIX__)
1168 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1170 const wxChar
*dirname
= dir
.c_str();
1172 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1173 // for the GNU compiler
1174 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1177 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1179 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1181 #elif defined(__OS2__)
1183 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1184 #elif defined(__DOS__)
1185 #if defined(__WATCOMC__)
1187 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1188 #elif defined(__DJGPP__)
1189 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1191 #error "Unsupported DOS compiler!"
1193 #else // !MSW, !DOS and !OS/2 VAC++
1196 if ( !CreateDirectory(dirname
, NULL
) )
1198 if ( wxMkDir(dir
.fn_str()) != 0 )
1202 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1211 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1213 #if defined(__VMS__)
1214 return false; //to be changed since rmdir exists in VMS7.x
1215 #elif defined(__OS2__)
1216 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1217 #elif defined(__WXWINCE__)
1218 return (CreateDirectory(dir
, NULL
) != 0);
1219 #elif defined(__WXPALMOS__)
1220 // TODO with VFSFileRename()
1223 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1227 // does the path exists? (may have or not '/' or '\\' at the end)
1228 bool wxDirExists(const wxChar
*pszPathName
)
1230 wxString
strPath(pszPathName
);
1232 #if defined(__WINDOWS__) || defined(__OS2__)
1233 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1234 // so remove all trailing backslashes from the path - but don't do this for
1235 // the pathes "d:\" (which are different from "d:") nor for just "\"
1236 while ( wxEndsWithPathSeparator(strPath
) )
1238 size_t len
= strPath
.length();
1239 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1242 strPath
.Truncate(len
- 1);
1244 #endif // __WINDOWS__
1247 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1248 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1252 #if defined(__WXPALMOS__)
1254 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1255 // stat() can't cope with network paths
1256 DWORD ret
= ::GetFileAttributes(strPath
);
1258 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1259 #elif defined(__OS2__)
1260 FILESTATUS3 Info
= {{0}};
1261 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1262 (void*) &Info
, sizeof(FILESTATUS3
));
1264 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1265 (rc
== ERROR_SHARING_VIOLATION
);
1266 // If we got a sharing violation, there must be something with this name.
1270 #ifndef __VISAGECPP__
1271 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1273 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1274 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1277 #endif // __WIN32__/!__WIN32__
1280 // Get a temporary filename, opening and closing the file.
1281 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1284 if ( !wxGetTempFileName(prefix
, filename
) )
1288 wxStrcpy(buf
, filename
);
1290 buf
= MYcopystring(filename
);
1295 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1298 buf
= wxFileName::CreateTempFileName(prefix
);
1300 return !buf
.empty();
1301 #else // !wxUSE_FILE
1302 wxUnusedVar(prefix
);
1306 #endif // wxUSE_FILE/!wxUSE_FILE
1309 // Get first file name matching given wild card.
1311 static wxDir
*gs_dir
= NULL
;
1312 static wxString gs_dirPath
;
1314 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1316 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1317 if ( gs_dirPath
.empty() )
1318 gs_dirPath
= wxT(".");
1319 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1320 gs_dirPath
<< wxFILE_SEP_PATH
;
1324 gs_dir
= new wxDir(gs_dirPath
);
1326 if ( !gs_dir
->IsOpened() )
1328 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1329 return wxEmptyString
;
1335 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1336 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1337 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1341 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1342 if ( result
.empty() )
1348 return gs_dirPath
+ result
;
1351 wxString
wxFindNextFile()
1353 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1356 gs_dir
->GetNext(&result
);
1358 if ( result
.empty() )
1364 return gs_dirPath
+ result
;
1368 // Get current working directory.
1369 // If buf is NULL, allocates space using new, else copies into buf.
1370 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1371 // wxDoGetCwd() is their common core to be moved
1372 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1373 // Do not expose wxDoGetCwd in headers!
1375 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1377 #if defined(__WXPALMOS__)
1379 if(buf
&& sz
>0) buf
[0] = _T('\0');
1381 #elif defined(__WXWINCE__)
1383 if(buf
&& sz
>0) buf
[0] = _T('\0');
1388 buf
= new wxChar
[sz
+ 1];
1391 bool ok
wxDUMMY_INITIALIZE(false);
1393 // for the compilers which have Unicode version of _getcwd(), call it
1394 // directly, for the others call the ANSI version and do the translation
1397 #else // wxUSE_UNICODE
1398 bool needsANSI
= true;
1400 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1401 char cbuf
[_MAXPATHLEN
];
1405 #if wxUSE_UNICODE_MSLU
1406 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1408 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1411 ok
= _wgetcwd(buf
, sz
) != NULL
;
1417 #endif // wxUSE_UNICODE
1419 #if defined(_MSC_VER) || defined(__MINGW32__)
1420 ok
= _getcwd(cbuf
, sz
) != NULL
;
1421 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1423 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1425 wxString
res( lbuf
, *wxConvCurrent
) ;
1426 wxStrcpy( buf
, res
) ;
1431 #elif defined(__OS2__)
1433 ULONG ulDriveNum
= 0;
1434 ULONG ulDriveMap
= 0;
1435 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1440 rc
= ::DosQueryCurrentDir( 0 // current drive
1444 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1449 #else // !Win32/VC++ !Mac !OS2
1450 ok
= getcwd(cbuf
, sz
) != NULL
;
1453 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1454 // finally convert the result to Unicode if needed
1455 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1456 #endif // wxUSE_UNICODE
1461 wxLogSysError(_("Failed to get the working directory"));
1463 // VZ: the old code used to return "." on error which didn't make any
1464 // sense at all to me - empty string is a better error indicator
1465 // (NULL might be even better but I'm afraid this could lead to
1466 // problems with the old code assuming the return is never NULL)
1469 else // ok, but we might need to massage the path into the right format
1472 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1473 // with / deliminers. We don't like that.
1474 for (wxChar
*ch
= buf
; *ch
; ch
++)
1476 if (*ch
== wxT('/'))
1481 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1482 // he needs Unix as opposed to Win32 pathnames
1483 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1484 // another example of DOS/Unix mix (Cygwin)
1485 wxString pathUnix
= buf
;
1487 char bufA
[_MAXPATHLEN
];
1488 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1489 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1491 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1492 #endif // wxUSE_UNICODE
1493 #endif // __CYGWIN__
1506 #if WXWIN_COMPATIBILITY_2_6
1507 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1509 return wxDoGetCwd(buf
,sz
);
1511 #endif // WXWIN_COMPATIBILITY_2_6
1516 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1520 bool wxSetWorkingDirectory(const wxString
& d
)
1522 #if defined(__OS2__)
1523 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1524 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1525 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1526 #elif defined(__WINDOWS__)
1530 // No equivalent in WinCE
1534 return (bool)(SetCurrentDirectory(d
) != 0);
1537 // Must change drive, too.
1538 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1541 wxChar firstChar
= d
[0];
1545 firstChar
= firstChar
- 32;
1547 // To a drive number
1548 unsigned int driveNo
= firstChar
- 64;
1551 unsigned int noDrives
;
1552 _dos_setdrive(driveNo
, &noDrives
);
1555 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1563 // Get the OS directory if appropriate (such as the Windows directory).
1564 // On non-Windows platform, probably just return the empty string.
1565 wxString
wxGetOSDirectory()
1568 return wxString(wxT("\\Windows"));
1569 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1571 GetWindowsDirectory(buf
, 256);
1572 return wxString(buf
);
1573 #elif defined(__WXMAC__)
1574 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1576 return wxEmptyString
;
1580 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1582 size_t len
= wxStrlen(pszFileName
);
1584 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1587 // find a file in a list of directories, returns false if not found
1588 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1590 // we assume that it's not empty
1591 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1592 _T("empty file name in wxFindFileInPath"));
1594 // skip path separator in the beginning of the file name if present
1595 if ( wxIsPathSeparator(*pszFile
) )
1598 // copy the path (strtok will modify it)
1599 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1600 wxStrcpy(szPath
, pszPath
);
1603 wxChar
*pc
, *save_ptr
;
1604 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1606 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1608 // search for the file in this directory
1610 if ( !wxEndsWithPathSeparator(pc
) )
1611 strFile
+= wxFILE_SEP_PATH
;
1614 if ( wxFileExists(strFile
) ) {
1620 // suppress warning about unused variable save_ptr when wxStrtok() is a
1621 // macro which throws away its third argument
1626 return pc
!= NULL
; // if true => we breaked from the loop
1629 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1634 // it can be empty, but it shouldn't be NULL
1635 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1637 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1642 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1645 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1648 return mtime
.GetTicks();
1651 #endif // wxUSE_DATETIME
1654 // Parses the filterStr, returning the number of filters.
1655 // Returns 0 if none or if there's a problem.
1656 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1658 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1659 wxArrayString
& descriptions
,
1660 wxArrayString
& filters
)
1662 descriptions
.Clear();
1665 wxString
str(filterStr
);
1667 wxString description
, filter
;
1669 while( pos
!= wxNOT_FOUND
)
1671 pos
= str
.Find(wxT('|'));
1672 if ( pos
== wxNOT_FOUND
)
1674 // if there are no '|'s at all in the string just take the entire
1675 // string as filter and make description empty for later autocompletion
1676 if ( filters
.IsEmpty() )
1678 descriptions
.Add(wxEmptyString
);
1679 filters
.Add(filterStr
);
1683 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1689 description
= str
.Left(pos
);
1690 str
= str
.Mid(pos
+ 1);
1691 pos
= str
.Find(wxT('|'));
1692 if ( pos
== wxNOT_FOUND
)
1698 filter
= str
.Left(pos
);
1699 str
= str
.Mid(pos
+ 1);
1702 descriptions
.Add(description
);
1703 filters
.Add(filter
);
1706 #if defined(__WXMOTIF__)
1707 // split it so there is one wildcard per entry
1708 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1710 pos
= filters
[i
].Find(wxT(';'));
1711 if (pos
!= wxNOT_FOUND
)
1713 // first split only filters
1714 descriptions
.Insert(descriptions
[i
],i
+1);
1715 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1716 filters
[i
]=filters
[i
].Left(pos
);
1718 // autoreplace new filter in description with pattern:
1719 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1720 // cause split into:
1721 // C/C++ Files(*.cpp)|*.cpp
1722 // C/C++ Files(*.c;*.h)|*.c;*.h
1723 // and next iteration cause another split into:
1724 // C/C++ Files(*.cpp)|*.cpp
1725 // C/C++ Files(*.c)|*.c
1726 // C/C++ Files(*.h)|*.h
1727 for ( size_t k
=i
;k
<i
+2;k
++ )
1729 pos
= descriptions
[k
].Find(filters
[k
]);
1730 if (pos
!= wxNOT_FOUND
)
1732 wxString before
= descriptions
[k
].Left(pos
);
1733 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1734 pos
= before
.Find(_T('('),true);
1735 if (pos
>before
.Find(_T(')'),true))
1737 before
= before
.Left(pos
+1);
1738 before
<< filters
[k
];
1739 pos
= after
.Find(_T(')'));
1740 int pos1
= after
.Find(_T('('));
1741 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1743 before
<< after
.Mid(pos
);
1744 descriptions
[k
] = before
;
1754 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1756 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1758 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1762 return filters
.GetCount();
1765 #if defined( __WINDOWS__ )
1766 bool wxCheckGenericPermission(const wxString
&path
, DWORD access
)
1768 // quoting the MSDN: "To obtain a handle to a directory, call the
1769 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag"
1770 wxWinVersion ver
= wxGetWinVersion();
1771 bool isdir
= wxDirExists(path
);
1772 if (isdir
&& (ver
== wxWinVersion_95
|| ver
== wxWinVersion_98
|| ver
== wxWinVersion_ME
))
1774 // however Win95/98/ME do not support FILE_FLAG_BACKUP_SEMANTICS...
1775 if (access
== GENERIC_READ
)
1777 WIN32_FILE_ATTRIBUTE_DATA data
;
1778 if (GetFileAttributesEx(path
.c_str(), GetFileExInfoStandard
, &data
) == 0)
1779 return false; // cannot query attributes
1780 return (data
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
) == 0;
1783 // FIXME: is it true that directories are always writable & executable on Win9X family ?
1788 HANDLE h
= CreateFile(path
.c_str(), access
,
1789 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1790 OPEN_EXISTING
, isdir
? FILE_FLAG_BACKUP_SEMANTICS
: 0, NULL
);
1791 if (h
!= INVALID_HANDLE_VALUE
)
1794 return h
!= INVALID_HANDLE_VALUE
;
1799 bool wxIsWritable(const wxString
&path
)
1801 #if defined( __UNIX__ )
1802 // access() will take in count also symbolic links
1803 return access(wxConvFile
.cWX2MB(path
), W_OK
) == 0;
1804 #elif defined( __WINDOWS__ )
1805 return wxCheckGenericPermission(path
, GENERIC_WRITE
);
1813 bool wxIsReadable(const wxString
&path
)
1815 #if defined( __UNIX__ )
1816 // access() will take in count also symbolic links
1817 return access(wxConvFile
.cWX2MB(path
), R_OK
) == 0;
1818 #elif defined( __WINDOWS__ )
1819 return wxCheckGenericPermission(path
, GENERIC_READ
);
1827 bool wxIsExecutable(const wxString
&path
)
1829 #if defined( __UNIX__ )
1830 // access() will take in count also symbolic links
1831 return access(wxConvFile
.cWX2MB(path
), X_OK
) == 0;
1832 #elif defined( __WINDOWS__ )
1833 return wxCheckGenericPermission(path
, GENERIC_EXECUTE
);
1842 //------------------------------------------------------------------------
1843 // wild character routines
1844 //------------------------------------------------------------------------
1846 bool wxIsWild( const wxString
& pattern
)
1848 wxString tmp
= pattern
;
1849 wxChar
*pat
= WXSTRINGCAST(tmp
);
1854 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1865 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1867 * The match procedure is public domain code (from ircII's reg.c)
1868 * but modified to suit our tastes (RN: No "%" syntax I guess)
1871 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1875 /* Match if both are empty. */
1879 const wxChar
*m
= pat
.c_str(),
1887 if (dot_special
&& (*n
== wxT('.')))
1889 /* Never match so that hidden Unix files
1890 * are never found. */
1903 else if (*m
== wxT('?'))
1911 if (*m
== wxT('\\'))
1914 /* Quoting "nothing" is a bad thing */
1921 * If we are out of both strings or we just
1922 * saw a wildcard, then we can say we have a
1933 * We could check for *n == NULL at this point, but
1934 * since it's more common to have a character there,
1935 * check to see if they match first (m and n) and
1936 * then if they don't match, THEN we can check for
1952 * If there are no more characters in the
1953 * string, but we still need to find another
1954 * character (*m != NULL), then it will be
1955 * impossible to match it
1973 // Return the type of an open file
1975 // Some file types on some platforms seem seekable but in fact are not.
1976 // The main use of this function is to allow such cases to be detected
1977 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1979 // This is important for the archive streams, which benefit greatly from
1980 // being able to seek on a stream, but which will produce corrupt archives
1981 // if they unknowingly seek on a non-seekable stream.
1983 // wxFILE_KIND_DISK is a good catch all return value, since other values
1984 // disable features of the archive streams. Some other value must be returned
1985 // for a file type that appears seekable but isn't.
1988 // * Pipes on Windows
1989 // * Files on VMS with a record format other than StreamLF
1991 wxFileKind
wxGetFileKind(int fd
)
1993 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1994 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1996 case FILE_TYPE_CHAR
:
1997 return wxFILE_KIND_TERMINAL
;
1998 case FILE_TYPE_DISK
:
1999 return wxFILE_KIND_DISK
;
2000 case FILE_TYPE_PIPE
:
2001 return wxFILE_KIND_PIPE
;
2004 return wxFILE_KIND_UNKNOWN
;
2006 #elif defined(__UNIX__)
2008 return wxFILE_KIND_TERMINAL
;
2013 if (S_ISFIFO(st
.st_mode
))
2014 return wxFILE_KIND_PIPE
;
2015 if (!S_ISREG(st
.st_mode
))
2016 return wxFILE_KIND_UNKNOWN
;
2018 #if defined(__VMS__)
2019 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
2020 return wxFILE_KIND_UNKNOWN
;
2023 return wxFILE_KIND_DISK
;
2026 #define wxFILEKIND_STUB
2028 return wxFILE_KIND_DISK
;
2032 wxFileKind
wxGetFileKind(FILE *fp
)
2034 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
2035 // Should be fixed in version 1.4.
2036 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
2038 return wxFILE_KIND_DISK
;
2040 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2045 #pragma warning(default:4706) // assignment within conditional expression