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() ;
910 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
913 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
915 return wxMacFSRefToPath( &fsRef
) ;
917 return wxEmptyString
;
920 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
922 OSStatus err
= noErr
;
924 wxMacPathToFSRef( path
, &fsRef
) ;
925 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
931 wxDos2UnixFilename (wxChar
*s
)
940 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
947 #if defined(__WXMSW__) || defined(__OS2__)
948 wxUnix2DosFilename (wxChar
*s
)
950 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
953 // Yes, I really mean this to happen under DOS only! JACS
954 #if defined(__WXMSW__) || defined(__OS2__)
965 // Concatenate two files to form third
967 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
971 wxFile
in1(file1
), in2(file2
);
972 wxTempFile
out(file3
);
974 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
978 unsigned char buf
[1024];
980 for( int i
=0; i
<2; i
++)
982 wxFile
*in
= i
==0 ? &in1
: &in2
;
984 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
986 if ( !out
.Write(buf
,ofs
) )
988 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1005 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1007 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1008 // CopyFile() copies file attributes and modification time too, so use it
1009 // instead of our code if available
1011 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1012 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1014 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1015 file1
.c_str(), file2
.c_str());
1019 #elif defined(__OS2__)
1020 if ( ::DosCopy((PSZ
)file1
.c_str(), (PSZ
)file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1022 #elif defined(__PALMOS__)
1023 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1025 #elif wxUSE_FILE // !Win32
1028 // get permissions of file1
1029 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1031 // the file probably doesn't exist or we haven't the rights to read
1033 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1038 // open file1 for reading
1039 wxFile
fileIn(file1
, wxFile::read
);
1040 if ( !fileIn
.IsOpened() )
1043 // remove file2, if it exists. This is needed for creating
1044 // file2 with the correct permissions in the next step
1045 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1047 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1052 // reset the umask as we want to create the file with exactly the same
1053 // permissions as the original one
1056 // create file2 with the same permissions than file1 and open it for
1060 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1063 // copy contents of file1 to file2
1068 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1069 if ( fileIn
.Error() )
1076 if ( fileOut
.Write(buf
, count
) < count
)
1080 // we can expect fileIn to be closed successfully, but we should ensure
1081 // that fileOut was closed as some write errors (disk full) might not be
1082 // detected before doing this
1083 if ( !fileIn
.Close() || !fileOut
.Close() )
1086 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1087 // no chmod in VA. Should be some permission API for HPFS386 partitions
1089 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1091 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1095 #endif // OS/2 || Mac
1097 #else // !Win32 && ! wxUSE_FILE
1099 // impossible to simulate with wxWidgets API
1102 wxUnusedVar(overwrite
);
1105 #endif // __WXMSW__ && __WIN32__
1111 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1113 if ( !overwrite
&& wxFileExists(file2
) )
1117 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1118 file1
.c_str(), file2
.c_str()
1124 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1125 // Normal system call
1126 if ( wxRename (file1
, file2
) == 0 )
1131 if (wxCopyFile(file1
, file2
, overwrite
)) {
1132 wxRemoveFile(file1
);
1139 bool wxRemoveFile(const wxString
& file
)
1141 #if defined(__VISUALC__) \
1142 || defined(__BORLANDC__) \
1143 || defined(__WATCOMC__) \
1144 || defined(__DMC__) \
1145 || defined(__GNUWIN32__) \
1146 || (defined(__MWERKS__) && defined(__MSL__))
1147 int res
= wxRemove(file
);
1148 #elif defined(__WXMAC__)
1149 int res
= unlink(wxFNCONV(file
));
1150 #elif defined(__WXPALMOS__)
1152 // TODO with VFSFileDelete()
1154 int res
= unlink(OS_FILENAME(file
));
1160 bool wxMkdir(const wxString
& dir
, int perm
)
1162 #if defined(__WXPALMOS__)
1164 #elif defined(__WXMAC__) && !defined(__UNIX__)
1165 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1167 const wxChar
*dirname
= dir
.c_str();
1169 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1170 // for the GNU compiler
1171 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1174 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1176 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1178 #elif defined(__OS2__)
1180 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1181 #elif defined(__DOS__)
1182 #if defined(__WATCOMC__)
1184 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1185 #elif defined(__DJGPP__)
1186 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1188 #error "Unsupported DOS compiler!"
1190 #else // !MSW, !DOS and !OS/2 VAC++
1193 if ( !CreateDirectory(dirname
, NULL
) )
1195 if ( wxMkDir(dir
.fn_str()) != 0 )
1199 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1208 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1210 #if defined(__VMS__)
1211 return false; //to be changed since rmdir exists in VMS7.x
1212 #elif defined(__OS2__)
1213 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1214 #elif defined(__WXWINCE__)
1215 return (CreateDirectory(dir
, NULL
) != 0);
1216 #elif defined(__WXPALMOS__)
1217 // TODO with VFSFileRename()
1220 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1224 // does the path exists? (may have or not '/' or '\\' at the end)
1225 bool wxDirExists(const wxChar
*pszPathName
)
1227 wxString
strPath(pszPathName
);
1229 #if defined(__WINDOWS__) || defined(__OS2__)
1230 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1231 // so remove all trailing backslashes from the path - but don't do this for
1232 // the pathes "d:\" (which are different from "d:") nor for just "\"
1233 while ( wxEndsWithPathSeparator(strPath
) )
1235 size_t len
= strPath
.length();
1236 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1239 strPath
.Truncate(len
- 1);
1241 #endif // __WINDOWS__
1244 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1245 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1249 #if defined(__WXPALMOS__)
1251 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1252 // stat() can't cope with network paths
1253 DWORD ret
= ::GetFileAttributes(strPath
);
1255 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1256 #elif defined(__OS2__)
1257 FILESTATUS3 Info
= {{0}};
1258 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1259 (void*) &Info
, sizeof(FILESTATUS3
));
1261 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1262 (rc
== ERROR_SHARING_VIOLATION
);
1263 // If we got a sharing violation, there must be something with this name.
1267 #ifndef __VISAGECPP__
1268 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1270 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1271 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1274 #endif // __WIN32__/!__WIN32__
1277 // Get a temporary filename, opening and closing the file.
1278 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1281 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1282 if ( filename
.empty() )
1286 wxStrcpy(buf
, filename
);
1288 buf
= MYcopystring(filename
);
1292 wxUnusedVar(prefix
);
1294 // wxFileName::CreateTempFileName needs wxFile class enabled
1299 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1301 buf
= wxGetTempFileName(prefix
);
1303 return !buf
.empty();
1306 // Get first file name matching given wild card.
1308 static wxDir
*gs_dir
= NULL
;
1309 static wxString gs_dirPath
;
1311 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1313 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1314 if ( gs_dirPath
.empty() )
1315 gs_dirPath
= wxT(".");
1316 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1317 gs_dirPath
<< wxFILE_SEP_PATH
;
1321 gs_dir
= new wxDir(gs_dirPath
);
1323 if ( !gs_dir
->IsOpened() )
1325 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1326 return wxEmptyString
;
1332 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1333 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1334 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1338 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1339 if ( result
.empty() )
1345 return gs_dirPath
+ result
;
1348 wxString
wxFindNextFile()
1350 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1353 gs_dir
->GetNext(&result
);
1355 if ( result
.empty() )
1361 return gs_dirPath
+ result
;
1365 // Get current working directory.
1366 // If buf is NULL, allocates space using new, else copies into buf.
1367 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1368 // wxDoGetCwd() is their common core to be moved
1369 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1370 // Do not expose wxDoGetCwd in headers!
1372 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1374 #if defined(__WXPALMOS__)
1376 if(buf
&& sz
>0) buf
[0] = _T('\0');
1378 #elif defined(__WXWINCE__)
1380 if(buf
&& sz
>0) buf
[0] = _T('\0');
1385 buf
= new wxChar
[sz
+ 1];
1388 bool ok
wxDUMMY_INITIALIZE(false);
1390 // for the compilers which have Unicode version of _getcwd(), call it
1391 // directly, for the others call the ANSI version and do the translation
1394 #else // wxUSE_UNICODE
1395 bool needsANSI
= true;
1397 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1398 char cbuf
[_MAXPATHLEN
];
1402 #if wxUSE_UNICODE_MSLU
1403 if ( wxGetOsVersion() != wxOS_WINDOWS_9X
)
1405 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1408 ok
= _wgetcwd(buf
, sz
) != NULL
;
1414 #endif // wxUSE_UNICODE
1416 #if defined(_MSC_VER) || defined(__MINGW32__)
1417 ok
= _getcwd(cbuf
, sz
) != NULL
;
1418 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1420 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1422 wxString
res( lbuf
, *wxConvCurrent
) ;
1423 wxStrcpy( buf
, res
) ;
1428 #elif defined(__OS2__)
1430 ULONG ulDriveNum
= 0;
1431 ULONG ulDriveMap
= 0;
1432 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1437 rc
= ::DosQueryCurrentDir( 0 // current drive
1441 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1446 #else // !Win32/VC++ !Mac !OS2
1447 ok
= getcwd(cbuf
, sz
) != NULL
;
1450 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1451 // finally convert the result to Unicode if needed
1452 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1453 #endif // wxUSE_UNICODE
1458 wxLogSysError(_("Failed to get the working directory"));
1460 // VZ: the old code used to return "." on error which didn't make any
1461 // sense at all to me - empty string is a better error indicator
1462 // (NULL might be even better but I'm afraid this could lead to
1463 // problems with the old code assuming the return is never NULL)
1466 else // ok, but we might need to massage the path into the right format
1469 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1470 // with / deliminers. We don't like that.
1471 for (wxChar
*ch
= buf
; *ch
; ch
++)
1473 if (*ch
== wxT('/'))
1478 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1479 // he needs Unix as opposed to Win32 pathnames
1480 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1481 // another example of DOS/Unix mix (Cygwin)
1482 wxString pathUnix
= buf
;
1484 char bufA
[_MAXPATHLEN
];
1485 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1486 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1488 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1489 #endif // wxUSE_UNICODE
1490 #endif // __CYGWIN__
1503 #if WXWIN_COMPATIBILITY_2_6
1504 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1506 return wxDoGetCwd(buf
,sz
);
1508 #endif // WXWIN_COMPATIBILITY_2_6
1513 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1517 bool wxSetWorkingDirectory(const wxString
& d
)
1519 #if defined(__OS2__)
1520 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1521 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1522 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1523 #elif defined(__WINDOWS__)
1527 // No equivalent in WinCE
1531 return (bool)(SetCurrentDirectory(d
) != 0);
1534 // Must change drive, too.
1535 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1538 wxChar firstChar
= d
[0];
1542 firstChar
= firstChar
- 32;
1544 // To a drive number
1545 unsigned int driveNo
= firstChar
- 64;
1548 unsigned int noDrives
;
1549 _dos_setdrive(driveNo
, &noDrives
);
1552 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1560 // Get the OS directory if appropriate (such as the Windows directory).
1561 // On non-Windows platform, probably just return the empty string.
1562 wxString
wxGetOSDirectory()
1565 return wxString(wxT("\\Windows"));
1566 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1568 GetWindowsDirectory(buf
, 256);
1569 return wxString(buf
);
1570 #elif defined(__WXMAC__)
1571 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1573 return wxEmptyString
;
1577 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1579 size_t len
= wxStrlen(pszFileName
);
1581 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1584 // find a file in a list of directories, returns false if not found
1585 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1587 // we assume that it's not empty
1588 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1589 _T("empty file name in wxFindFileInPath"));
1591 // skip path separator in the beginning of the file name if present
1592 if ( wxIsPathSeparator(*pszFile
) )
1595 // copy the path (strtok will modify it)
1596 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1597 wxStrcpy(szPath
, pszPath
);
1600 wxChar
*pc
, *save_ptr
;
1601 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1603 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1605 // search for the file in this directory
1607 if ( !wxEndsWithPathSeparator(pc
) )
1608 strFile
+= wxFILE_SEP_PATH
;
1611 if ( wxFileExists(strFile
) ) {
1617 // suppress warning about unused variable save_ptr when wxStrtok() is a
1618 // macro which throws away its third argument
1623 return pc
!= NULL
; // if true => we breaked from the loop
1626 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1631 // it can be empty, but it shouldn't be NULL
1632 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1634 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1639 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1642 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1645 return mtime
.GetTicks();
1648 #endif // wxUSE_DATETIME
1651 // Parses the filterStr, returning the number of filters.
1652 // Returns 0 if none or if there's a problem.
1653 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1655 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1656 wxArrayString
& descriptions
,
1657 wxArrayString
& filters
)
1659 descriptions
.Clear();
1662 wxString
str(filterStr
);
1664 wxString description
, filter
;
1666 while( pos
!= wxNOT_FOUND
)
1668 pos
= str
.Find(wxT('|'));
1669 if ( pos
== wxNOT_FOUND
)
1671 // if there are no '|'s at all in the string just take the entire
1672 // string as filter and make description empty for later autocompletion
1673 if ( filters
.IsEmpty() )
1675 descriptions
.Add(wxEmptyString
);
1676 filters
.Add(filterStr
);
1680 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1686 description
= str
.Left(pos
);
1687 str
= str
.Mid(pos
+ 1);
1688 pos
= str
.Find(wxT('|'));
1689 if ( pos
== wxNOT_FOUND
)
1695 filter
= str
.Left(pos
);
1696 str
= str
.Mid(pos
+ 1);
1699 descriptions
.Add(description
);
1700 filters
.Add(filter
);
1703 #if defined(__WXMOTIF__)
1704 // split it so there is one wildcard per entry
1705 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1707 pos
= filters
[i
].Find(wxT(';'));
1708 if (pos
!= wxNOT_FOUND
)
1710 // first split only filters
1711 descriptions
.Insert(descriptions
[i
],i
+1);
1712 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1713 filters
[i
]=filters
[i
].Left(pos
);
1715 // autoreplace new filter in description with pattern:
1716 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1717 // cause split into:
1718 // C/C++ Files(*.cpp)|*.cpp
1719 // C/C++ Files(*.c;*.h)|*.c;*.h
1720 // and next iteration cause another split into:
1721 // C/C++ Files(*.cpp)|*.cpp
1722 // C/C++ Files(*.c)|*.c
1723 // C/C++ Files(*.h)|*.h
1724 for ( size_t k
=i
;k
<i
+2;k
++ )
1726 pos
= descriptions
[k
].Find(filters
[k
]);
1727 if (pos
!= wxNOT_FOUND
)
1729 wxString before
= descriptions
[k
].Left(pos
);
1730 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1731 pos
= before
.Find(_T('('),true);
1732 if (pos
>before
.Find(_T(')'),true))
1734 before
= before
.Left(pos
+1);
1735 before
<< filters
[k
];
1736 pos
= after
.Find(_T(')'));
1737 int pos1
= after
.Find(_T('('));
1738 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1740 before
<< after
.Mid(pos
);
1741 descriptions
[k
] = before
;
1751 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1753 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1755 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1759 return filters
.GetCount();
1762 #if defined( __WINDOWS__ )
1763 bool wxCheckGenericPermission(const wxString
&path
, DWORD access
)
1765 // quoting the MSDN: "To obtain a handle to a directory, call the
1766 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag"
1767 wxWinVersion ver
= wxGetWinVersion();
1768 bool isdir
= wxDirExists(path
);
1769 if (isdir
&& (ver
== wxWinVersion_95
|| ver
== wxWinVersion_98
|| ver
== wxWinVersion_ME
))
1771 // however Win95/98/ME do not support FILE_FLAG_BACKUP_SEMANTICS...
1772 if (access
== GENERIC_READ
)
1774 WIN32_FILE_ATTRIBUTE_DATA data
;
1775 if (GetFileAttributesEx(path
.c_str(), GetFileExInfoStandard
, &data
) == 0)
1776 return false; // cannot query attributes
1777 return (data
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
) == 0;
1780 // FIXME: is it true that directories are always writable & executable on Win9X family ?
1785 HANDLE h
= CreateFile(path
.c_str(), access
,
1786 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
1787 OPEN_EXISTING
, isdir
? FILE_FLAG_BACKUP_SEMANTICS
: 0, NULL
);
1788 if (h
!= INVALID_HANDLE_VALUE
)
1791 return h
!= INVALID_HANDLE_VALUE
;
1796 bool wxIsWritable(const wxString
&path
)
1798 #if defined( __UNIX__ )
1799 // access() will take in count also symbolic links
1800 return access(wxConvFile
.cWX2MB(path
), W_OK
) == 0;
1801 #elif defined( __WINDOWS__ )
1802 return wxCheckGenericPermission(path
, GENERIC_WRITE
);
1809 bool wxIsReadable(const wxString
&path
)
1811 #if defined( __UNIX__ )
1812 // access() will take in count also symbolic links
1813 return access(wxConvFile
.cWX2MB(path
), R_OK
) == 0;
1814 #elif defined( __WINDOWS__ )
1815 return wxCheckGenericPermission(path
, GENERIC_READ
);
1822 bool wxIsExecutable(const wxString
&path
)
1824 #if defined( __UNIX__ )
1825 // access() will take in count also symbolic links
1826 return access(wxConvFile
.cWX2MB(path
), X_OK
) == 0;
1827 #elif defined( __WINDOWS__ )
1828 return wxCheckGenericPermission(path
, GENERIC_EXECUTE
);
1836 //------------------------------------------------------------------------
1837 // wild character routines
1838 //------------------------------------------------------------------------
1840 bool wxIsWild( const wxString
& pattern
)
1842 wxString tmp
= pattern
;
1843 wxChar
*pat
= WXSTRINGCAST(tmp
);
1848 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1859 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1861 * The match procedure is public domain code (from ircII's reg.c)
1862 * but modified to suit our tastes (RN: No "%" syntax I guess)
1865 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1869 /* Match if both are empty. */
1873 const wxChar
*m
= pat
.c_str(),
1881 if (dot_special
&& (*n
== wxT('.')))
1883 /* Never match so that hidden Unix files
1884 * are never found. */
1897 else if (*m
== wxT('?'))
1905 if (*m
== wxT('\\'))
1908 /* Quoting "nothing" is a bad thing */
1915 * If we are out of both strings or we just
1916 * saw a wildcard, then we can say we have a
1927 * We could check for *n == NULL at this point, but
1928 * since it's more common to have a character there,
1929 * check to see if they match first (m and n) and
1930 * then if they don't match, THEN we can check for
1946 * If there are no more characters in the
1947 * string, but we still need to find another
1948 * character (*m != NULL), then it will be
1949 * impossible to match it
1967 // Return the type of an open file
1969 // Some file types on some platforms seem seekable but in fact are not.
1970 // The main use of this function is to allow such cases to be detected
1971 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1973 // This is important for the archive streams, which benefit greatly from
1974 // being able to seek on a stream, but which will produce corrupt archives
1975 // if they unknowingly seek on a non-seekable stream.
1977 // wxFILE_KIND_DISK is a good catch all return value, since other values
1978 // disable features of the archive streams. Some other value must be returned
1979 // for a file type that appears seekable but isn't.
1982 // * Pipes on Windows
1983 // * Files on VMS with a record format other than StreamLF
1985 wxFileKind
wxGetFileKind(int fd
)
1987 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1988 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1990 case FILE_TYPE_CHAR
:
1991 return wxFILE_KIND_TERMINAL
;
1992 case FILE_TYPE_DISK
:
1993 return wxFILE_KIND_DISK
;
1994 case FILE_TYPE_PIPE
:
1995 return wxFILE_KIND_PIPE
;
1998 return wxFILE_KIND_UNKNOWN
;
2000 #elif defined(__UNIX__)
2002 return wxFILE_KIND_TERMINAL
;
2007 if (S_ISFIFO(st
.st_mode
))
2008 return wxFILE_KIND_PIPE
;
2009 if (!S_ISREG(st
.st_mode
))
2010 return wxFILE_KIND_UNKNOWN
;
2012 #if defined(__VMS__)
2013 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
2014 return wxFILE_KIND_UNKNOWN
;
2017 return wxFILE_KIND_DISK
;
2020 #define wxFILEKIND_STUB
2022 return wxFILE_KIND_DISK
;
2026 wxFileKind
wxGetFileKind(FILE *fp
)
2028 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
2029 // Should be fixed in version 1.4.
2030 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
2032 return wxFILE_KIND_DISK
;
2034 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
2039 #pragma warning(default:4706) // assignment within conditional expression