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 only the path part of the given string (not the filename, in case it's present)
152 wxFileName
fn(path
+ wxFileName::GetPathSeparator());
153 fn
.Normalize(); // add only normalized paths
155 wxString toadd
= fn
.GetPath();
156 if (Index(toadd
) == wxNOT_FOUND
)
157 wxArrayString::Add(toadd
); // do not add duplicates
160 void wxPathList::Add(const wxArrayString
&arr
)
162 for (size_t j
=0; j
< arr
.GetCount(); j
++)
166 // Add paths e.g. from the PATH environment variable
167 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
169 // No environment variables on WinCE
172 // The space has been removed from the tokenizers, otherwise a
173 // path such as "C:\Program Files" would be split into 2 paths:
174 // "C:\Program" and "Files"; this is true for both Windows and Unix.
176 static const wxChar PATH_TOKS
[] =
177 #if defined(__WINDOWS__) || defined(__OS2__)
178 wxT(";"); // Don't separate with colon in DOS (used for drive)
184 if ( wxGetEnv(envVariable
, &val
) )
186 // split into an array of string the value of the env var
187 wxArrayString arr
= wxStringTokenize(val
, PATH_TOKS
);
188 WX_APPEND_ARRAY(*this, arr
);
190 #endif // !__WXWINCE__
193 // Given a full filename (with path), ensure that that file can
194 // be accessed again USING FILENAME ONLY by adding the path
195 // to the list if not already there.
196 void wxPathList::EnsureFileAccessible (const wxString
& path
)
198 wxString
path_only(wxPathOnly(path
));
199 if ( !path_only
.empty() )
201 if ( Index(path_only
) == wxNOT_FOUND
)
207 bool wxPathList::Member (const wxString
& path
) const
209 return Index(path
) != wxNOT_FOUND
;
212 wxString
wxPathList::FindValidPath (const wxString
& file
) const
219 strend
= fn
.GetFullName();
221 strend
= fn
.GetFullPath();
223 for (size_t i
=0; i
<GetCount(); i
++)
225 wxString strstart
= Item(i
);
226 if (!strstart
.IsEmpty() && strstart
.Last() != wxFileName::GetPathSeparator())
227 strstart
+= wxFileName::GetPathSeparator();
229 if (wxFileExists(strstart
+ strend
))
230 return strstart
+ strend
; // Found!
233 return wxEmptyString
; // Not found
236 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
) const
238 wxString f
= FindValidPath(file
);
239 if ( f
.empty() || wxIsAbsolutePath(f
) )
242 wxString buf
= ::wxGetCwd();
244 if ( !wxEndsWithPathSeparator(buf
) )
246 buf
+= wxFILE_SEP_PATH
;
253 // ----------------------------------------------------------------------------
254 // miscellaneous global functions (TOFIX!)
255 // ----------------------------------------------------------------------------
257 static inline wxChar
* MYcopystring(const wxString
& s
)
259 wxChar
* copy
= new wxChar
[s
.length() + 1];
260 return wxStrcpy(copy
, s
.c_str());
263 static inline wxChar
* MYcopystring(const wxChar
* s
)
265 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
266 return wxStrcpy(copy
, s
);
271 wxFileExists (const wxString
& filename
)
273 #if defined(__WXPALMOS__)
275 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
276 // we must use GetFileAttributes() instead of the ANSI C functions because
277 // it can cope with network (UNC) paths unlike them
278 DWORD ret
= ::GetFileAttributes(filename
);
280 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
283 #define S_ISREG(mode) ((mode) & S_IFREG)
286 #ifndef wxNEED_WX_UNISTD_H
287 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
289 || (errno
== EACCES
) // if access is denied something with that name
290 // exists and is opened in exclusive mode.
294 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
296 #endif // __WIN32__/!__WIN32__
300 wxIsAbsolutePath (const wxString
& filename
)
302 if (!filename
.empty())
304 #if defined(__WXMAC__) && !defined(__DARWIN__)
305 // Classic or Carbon CodeWarrior like
306 // Carbon with Apple DevTools is Unix like
308 // This seems wrong to me, but there is no fix. since
309 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
310 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
311 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
314 // Unix like or Windows
315 if (filename
[0] == wxT('/'))
319 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
322 #if defined(__WINDOWS__) || defined(__OS2__)
324 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
332 * Strip off any extension (dot something) from end of file,
333 * IF one exists. Inserts zero into buffer.
337 void wxStripExtension(wxChar
*buffer
)
339 int len
= wxStrlen(buffer
);
343 if (buffer
[i
] == wxT('.'))
352 void wxStripExtension(wxString
& buffer
)
354 //RN: Be careful about the handling the case where
355 //buffer.length() == 0
356 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
358 if (buffer
.GetChar(i
) == wxT('.'))
360 buffer
= buffer
.Left(i
);
366 // Destructive removal of /./ and /../ stuff
367 wxChar
*wxRealPath (wxChar
*path
)
370 static const wxChar SEP
= wxT('\\');
371 wxUnix2DosFilename(path
);
373 static const wxChar SEP
= wxT('/');
375 if (path
[0] && path
[1]) {
376 /* MATTHEW: special case "/./x" */
378 if (path
[2] == SEP
&& path
[1] == wxT('.'))
386 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
389 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
394 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
395 && (q
- 1 <= path
|| q
[-1] != SEP
))
398 if (path
[0] == wxT('\0'))
403 #if defined(__WXMSW__) || defined(__OS2__)
404 /* Check that path[2] is NULL! */
405 else if (path
[1] == wxT(':') && !path
[2])
414 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
422 wxString
wxRealPath(const wxString
& path
)
424 wxChar
*buf1
=MYcopystring(path
);
425 wxChar
*buf2
=wxRealPath(buf1
);
433 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
435 if (filename
.empty())
436 return (wxChar
*) NULL
;
438 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
440 wxString buf
= ::wxGetCwd();
441 wxChar ch
= buf
.Last();
443 if (ch
!= wxT('\\') && ch
!= wxT('/'))
449 buf
<< wxFileFunctionsBuffer
;
450 buf
= wxRealPath( buf
);
451 return MYcopystring( buf
);
453 return MYcopystring( wxFileFunctionsBuffer
);
459 ~user/ => user's home dir
460 If the environment variable a = "foo" and b = "bar" then:
477 /* input name in name, pathname output to buf. */
479 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
481 register wxChar
*d
, *s
, *nm
;
482 wxChar lnm
[_MAXPATHLEN
];
485 // Some compilers don't like this line.
486 // const wxChar trimchars[] = wxT("\n \t");
489 trimchars
[0] = wxT('\n');
490 trimchars
[1] = wxT(' ');
491 trimchars
[2] = wxT('\t');
495 const wxChar SEP
= wxT('\\');
497 const wxChar SEP
= wxT('/');
500 if (name
== NULL
|| *name
== wxT('\0'))
502 nm
= MYcopystring(name
); // Make a scratch copy
505 /* Skip leading whitespace and cr */
506 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
508 /* And strip off trailing whitespace and cr */
509 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
510 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
518 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
521 /* Expand inline environment variables */
539 while ((*d
++ = *s
) != 0) {
541 if (*s
== wxT('\\')) {
542 if ((*(d
- 1) = *++s
)!=0) {
550 // No env variables on WinCE
553 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
555 if (*s
++ == wxT('$'))
558 register wxChar
*start
= d
;
559 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
560 register wxChar
*value
;
561 while ((*d
++ = *s
) != 0)
562 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
567 value
= wxGetenv(braces
? start
+ 1 : start
);
569 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
583 /* Expand ~ and ~user */
585 if (nm
[0] == wxT('~') && !q
)
588 if (nm
[1] == SEP
|| nm
[1] == 0)
590 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
591 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
596 { /* ~user/filename */
597 register wxChar
*nnm
;
598 register wxChar
*home
;
599 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
603 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
604 was_sep
= (*s
== SEP
);
605 nnm
= *s
? s
+ 1 : s
;
607 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
608 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
)
610 if (was_sep
) /* replace only if it was there: */
623 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
625 while (wxT('\0') != (*d
++ = *s
++))
628 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
632 while ((*d
++ = *s
++) != 0)
636 delete[] nm_tmp
; // clean up alloc
637 /* Now clean up the buffer */
638 return wxRealPath(buf
);
641 /* Contract Paths to be build upon an environment variable
644 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
646 The call wxExpandPath can convert these back!
649 wxContractPath (const wxString
& filename
,
650 const wxString
& WXUNUSED_IN_WINCE(envname
),
651 const wxString
& user
)
653 static wxChar dest
[_MAXPATHLEN
];
655 if (filename
.empty())
656 return (wxChar
*) NULL
;
658 wxStrcpy (dest
, WXSTRINGCAST filename
);
660 wxUnix2DosFilename(dest
);
663 // Handle environment
667 if (!envname
.empty() && (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
668 (tcp
= wxStrstr (dest
, val
)) != NULL
)
670 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
673 wxStrcpy (tcp
, WXSTRINGCAST envname
);
674 wxStrcat (tcp
, wxT("}"));
675 wxStrcat (tcp
, wxFileFunctionsBuffer
);
679 // Handle User's home (ignore root homes!)
680 val
= wxGetUserHome (user
);
684 const size_t len
= wxStrlen(val
);
688 if (wxStrncmp(dest
, val
, len
) == 0)
690 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
692 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
693 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
694 wxStrcpy (dest
, wxFileFunctionsBuffer
);
700 // Return just the filename, not the path (basename)
701 wxChar
*wxFileNameFromPath (wxChar
*path
)
704 wxString n
= wxFileNameFromPath(p
);
706 return path
+ p
.length() - n
.length();
709 wxString
wxFileNameFromPath (const wxString
& path
)
712 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
714 wxString fullname
= name
;
717 fullname
<< wxFILE_SEP_EXT
<< ext
;
723 // Return just the directory, or NULL if no directory
725 wxPathOnly (wxChar
*path
)
729 static wxChar buf
[_MAXPATHLEN
];
732 wxStrcpy (buf
, path
);
734 int l
= wxStrlen(path
);
737 // Search backward for a backward or forward slash
740 #if defined(__WXMAC__) && !defined(__DARWIN__)
741 // Classic or Carbon CodeWarrior like
742 // Carbon with Apple DevTools is Unix like
743 if (path
[i
] == wxT(':') )
749 // Unix like or Windows
750 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
757 if (path
[i
] == wxT(']'))
766 #if defined(__WXMSW__) || defined(__OS2__)
767 // Try Drive specifier
768 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
770 // A:junk --> A:. (since A:.\junk Not A:\junk)
777 return (wxChar
*) NULL
;
780 // Return just the directory, or NULL if no directory
781 wxString
wxPathOnly (const wxString
& path
)
785 wxChar buf
[_MAXPATHLEN
];
788 wxStrcpy (buf
, WXSTRINGCAST path
);
790 int l
= path
.length();
793 // Search backward for a backward or forward slash
796 #if defined(__WXMAC__) && !defined(__DARWIN__)
797 // Classic or Carbon CodeWarrior like
798 // Carbon with Apple DevTools is Unix like
799 if (path
[i
] == wxT(':') )
802 return wxString(buf
);
805 // Unix like or Windows
806 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
808 // Don't return an empty string
812 return wxString(buf
);
816 if (path
[i
] == wxT(']'))
819 return wxString(buf
);
825 #if defined(__WXMSW__) || defined(__OS2__)
826 // Try Drive specifier
827 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
829 // A:junk --> A:. (since A:.\junk Not A:\junk)
832 return wxString(buf
);
836 return wxEmptyString
;
839 // Utility for converting delimiters in DOS filenames to UNIX style
840 // and back again - or we get nasty problems with delimiters.
841 // Also, convert to lower case, since case is significant in UNIX.
843 #if defined(__WXMAC__)
845 #if TARGET_API_MAC_OSX
846 #define kDefaultPathStyle kCFURLPOSIXPathStyle
848 #define kDefaultPathStyle kCFURLHFSPathStyle
851 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
854 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
855 if ( additionalPathComponent
)
857 CFURLRef parentURLRef
= fullURLRef
;
858 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
859 additionalPathComponent
,false);
860 CFRelease( parentURLRef
) ;
862 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
863 CFRelease( fullURLRef
) ;
864 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfString
);
865 CFRelease( cfString
);
866 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
867 return wxMacCFStringHolder(cfMutableString
).AsString();
870 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
872 OSStatus err
= noErr
;
873 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, wxMacCFStringHolder(path
));
874 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormD
);
875 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, cfMutableString
, kDefaultPathStyle
, false);
876 CFRelease( cfMutableString
);
879 if ( CFURLGetFSRef(url
, fsRef
) == false )
890 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
892 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
895 CFMutableStringRef cfMutableString
= CFStringCreateMutableCopy(NULL
, 0, cfname
);
897 CFStringNormalize(cfMutableString
,kCFStringNormalizationFormC
);
898 return wxMacCFStringHolder(cfMutableString
).AsString() ;
901 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
904 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
906 return wxMacFSRefToPath( &fsRef
) ;
908 return wxEmptyString
;
911 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
913 OSStatus err
= noErr
;
915 wxMacPathToFSRef( path
, &fsRef
) ;
916 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
922 wxDos2UnixFilename (wxChar
*s
)
931 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
938 #if defined(__WXMSW__) || defined(__OS2__)
939 wxUnix2DosFilename (wxChar
*s
)
941 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
944 // Yes, I really mean this to happen under DOS only! JACS
945 #if defined(__WXMSW__) || defined(__OS2__)
956 // Concatenate two files to form third
958 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
962 wxFile
in1(file1
), in2(file2
);
963 wxTempFile
out(file3
);
965 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
969 unsigned char buf
[1024];
971 for( int i
=0; i
<2; i
++)
973 wxFile
*in
= i
==0 ? &in1
: &in2
;
975 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
977 if ( !out
.Write(buf
,ofs
) )
979 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
996 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
998 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
999 // CopyFile() copies file attributes and modification time too, so use it
1000 // instead of our code if available
1002 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1003 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1005 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1006 file1
.c_str(), file2
.c_str());
1010 #elif defined(__OS2__)
1011 if ( ::DosCopy((PSZ
)file1
.c_str(), (PSZ
)file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1013 #elif defined(__PALMOS__)
1014 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1016 #elif wxUSE_FILE // !Win32
1019 // get permissions of file1
1020 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1022 // the file probably doesn't exist or we haven't the rights to read
1024 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1029 // open file1 for reading
1030 wxFile
fileIn(file1
, wxFile::read
);
1031 if ( !fileIn
.IsOpened() )
1034 // remove file2, if it exists. This is needed for creating
1035 // file2 with the correct permissions in the next step
1036 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1038 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1043 // reset the umask as we want to create the file with exactly the same
1044 // permissions as the original one
1047 // create file2 with the same permissions than file1 and open it for
1051 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1054 // copy contents of file1 to file2
1059 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1060 if ( fileIn
.Error() )
1067 if ( fileOut
.Write(buf
, count
) < count
)
1071 // we can expect fileIn to be closed successfully, but we should ensure
1072 // that fileOut was closed as some write errors (disk full) might not be
1073 // detected before doing this
1074 if ( !fileIn
.Close() || !fileOut
.Close() )
1077 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1078 // no chmod in VA. Should be some permission API for HPFS386 partitions
1080 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1082 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1086 #endif // OS/2 || Mac
1088 #else // !Win32 && ! wxUSE_FILE
1090 // impossible to simulate with wxWidgets API
1093 wxUnusedVar(overwrite
);
1096 #endif // __WXMSW__ && __WIN32__
1102 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1104 if ( !overwrite
&& wxFileExists(file2
) )
1108 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1109 file1
.c_str(), file2
.c_str()
1115 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1116 // Normal system call
1117 if ( wxRename (file1
, file2
) == 0 )
1122 if (wxCopyFile(file1
, file2
, overwrite
)) {
1123 wxRemoveFile(file1
);
1130 bool wxRemoveFile(const wxString
& file
)
1132 #if defined(__VISUALC__) \
1133 || defined(__BORLANDC__) \
1134 || defined(__WATCOMC__) \
1135 || defined(__DMC__) \
1136 || defined(__GNUWIN32__) \
1137 || (defined(__MWERKS__) && defined(__MSL__))
1138 int res
= wxRemove(file
);
1139 #elif defined(__WXMAC__)
1140 int res
= unlink(wxFNCONV(file
));
1141 #elif defined(__WXPALMOS__)
1143 // TODO with VFSFileDelete()
1145 int res
= unlink(OS_FILENAME(file
));
1151 bool wxMkdir(const wxString
& dir
, int perm
)
1153 #if defined(__WXPALMOS__)
1155 #elif defined(__WXMAC__) && !defined(__UNIX__)
1156 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1158 const wxChar
*dirname
= dir
.c_str();
1160 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1161 // for the GNU compiler
1162 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1165 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1167 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1169 #elif defined(__OS2__)
1171 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1172 #elif defined(__DOS__)
1173 #if defined(__WATCOMC__)
1175 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1176 #elif defined(__DJGPP__)
1177 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1179 #error "Unsupported DOS compiler!"
1181 #else // !MSW, !DOS and !OS/2 VAC++
1184 if ( !CreateDirectory(dirname
, NULL
) )
1186 if ( wxMkDir(dir
.fn_str()) != 0 )
1190 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1199 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1201 #if defined(__VMS__)
1202 return false; //to be changed since rmdir exists in VMS7.x
1203 #elif defined(__OS2__)
1204 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1205 #elif defined(__WXWINCE__)
1206 return (CreateDirectory(dir
, NULL
) != 0);
1207 #elif defined(__WXPALMOS__)
1208 // TODO with VFSFileRename()
1211 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1215 // does the path exists? (may have or not '/' or '\\' at the end)
1216 bool wxDirExists(const wxChar
*pszPathName
)
1218 wxString
strPath(pszPathName
);
1220 #if defined(__WINDOWS__) || defined(__OS2__)
1221 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1222 // so remove all trailing backslashes from the path - but don't do this for
1223 // the pathes "d:\" (which are different from "d:") nor for just "\"
1224 while ( wxEndsWithPathSeparator(strPath
) )
1226 size_t len
= strPath
.length();
1227 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1230 strPath
.Truncate(len
- 1);
1232 #endif // __WINDOWS__
1235 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1236 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1240 #if defined(__WXPALMOS__)
1242 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1243 // stat() can't cope with network paths
1244 DWORD ret
= ::GetFileAttributes(strPath
);
1246 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1247 #elif defined(__OS2__)
1248 FILESTATUS3 Info
= {{0}};
1249 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1250 (void*) &Info
, sizeof(FILESTATUS3
));
1252 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1253 (rc
== ERROR_SHARING_VIOLATION
);
1254 // If we got a sharing violation, there must be something with this name.
1258 #ifndef __VISAGECPP__
1259 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1261 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1262 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1265 #endif // __WIN32__/!__WIN32__
1268 // Get a temporary filename, opening and closing the file.
1269 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1272 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1273 if ( filename
.empty() )
1277 wxStrcpy(buf
, filename
);
1279 buf
= MYcopystring(filename
);
1283 wxUnusedVar(prefix
);
1285 // wxFileName::CreateTempFileName needs wxFile class enabled
1290 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1292 buf
= wxGetTempFileName(prefix
);
1294 return !buf
.empty();
1297 // Get first file name matching given wild card.
1299 static wxDir
*gs_dir
= NULL
;
1300 static wxString gs_dirPath
;
1302 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1304 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1305 if ( gs_dirPath
.empty() )
1306 gs_dirPath
= wxT(".");
1307 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1308 gs_dirPath
<< wxFILE_SEP_PATH
;
1312 gs_dir
= new wxDir(gs_dirPath
);
1314 if ( !gs_dir
->IsOpened() )
1316 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1317 return wxEmptyString
;
1323 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1324 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1325 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1329 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1330 if ( result
.empty() )
1336 return gs_dirPath
+ result
;
1339 wxString
wxFindNextFile()
1341 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1344 gs_dir
->GetNext(&result
);
1346 if ( result
.empty() )
1352 return gs_dirPath
+ result
;
1356 // Get current working directory.
1357 // If buf is NULL, allocates space using new, else copies into buf.
1358 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1359 // wxDoGetCwd() is their common core to be moved
1360 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1361 // Do not expose wxDoGetCwd in headers!
1363 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1365 #if defined(__WXPALMOS__)
1367 if(buf
&& sz
>0) buf
[0] = _T('\0');
1369 #elif defined(__WXWINCE__)
1371 if(buf
&& sz
>0) buf
[0] = _T('\0');
1376 buf
= new wxChar
[sz
+ 1];
1379 bool ok
wxDUMMY_INITIALIZE(false);
1381 // for the compilers which have Unicode version of _getcwd(), call it
1382 // directly, for the others call the ANSI version and do the translation
1385 #else // wxUSE_UNICODE
1386 bool needsANSI
= true;
1388 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1389 char cbuf
[_MAXPATHLEN
];
1393 #if wxUSE_UNICODE_MSLU
1394 if ( wxGetOsVersion() != wxWIN95
)
1396 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1399 ok
= _wgetcwd(buf
, sz
) != NULL
;
1405 #endif // wxUSE_UNICODE
1407 #if defined(_MSC_VER) || defined(__MINGW32__)
1408 ok
= _getcwd(cbuf
, sz
) != NULL
;
1409 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1411 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1413 wxString
res( lbuf
, *wxConvCurrent
) ;
1414 wxStrcpy( buf
, res
) ;
1419 #elif defined(__OS2__)
1421 ULONG ulDriveNum
= 0;
1422 ULONG ulDriveMap
= 0;
1423 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1428 rc
= ::DosQueryCurrentDir( 0 // current drive
1432 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1437 #else // !Win32/VC++ !Mac !OS2
1438 ok
= getcwd(cbuf
, sz
) != NULL
;
1441 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1442 // finally convert the result to Unicode if needed
1443 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1444 #endif // wxUSE_UNICODE
1449 wxLogSysError(_("Failed to get the working directory"));
1451 // VZ: the old code used to return "." on error which didn't make any
1452 // sense at all to me - empty string is a better error indicator
1453 // (NULL might be even better but I'm afraid this could lead to
1454 // problems with the old code assuming the return is never NULL)
1457 else // ok, but we might need to massage the path into the right format
1460 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1461 // with / deliminers. We don't like that.
1462 for (wxChar
*ch
= buf
; *ch
; ch
++)
1464 if (*ch
== wxT('/'))
1469 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1470 // he needs Unix as opposed to Win32 pathnames
1471 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1472 // another example of DOS/Unix mix (Cygwin)
1473 wxString pathUnix
= buf
;
1475 char bufA
[_MAXPATHLEN
];
1476 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1477 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1479 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1480 #endif // wxUSE_UNICODE
1481 #endif // __CYGWIN__
1494 #if WXWIN_COMPATIBILITY_2_6
1495 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1497 return wxDoGetCwd(buf
,sz
);
1499 #endif // WXWIN_COMPATIBILITY_2_6
1504 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1508 bool wxSetWorkingDirectory(const wxString
& d
)
1510 #if defined(__OS2__)
1511 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1512 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1513 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1514 #elif defined(__WINDOWS__)
1518 // No equivalent in WinCE
1522 return (bool)(SetCurrentDirectory(d
) != 0);
1525 // Must change drive, too.
1526 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1529 wxChar firstChar
= d
[0];
1533 firstChar
= firstChar
- 32;
1535 // To a drive number
1536 unsigned int driveNo
= firstChar
- 64;
1539 unsigned int noDrives
;
1540 _dos_setdrive(driveNo
, &noDrives
);
1543 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1551 // Get the OS directory if appropriate (such as the Windows directory).
1552 // On non-Windows platform, probably just return the empty string.
1553 wxString
wxGetOSDirectory()
1556 return wxString(wxT("\\Windows"));
1557 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1559 GetWindowsDirectory(buf
, 256);
1560 return wxString(buf
);
1561 #elif defined(__WXMAC__)
1562 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1564 return wxEmptyString
;
1568 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1570 size_t len
= wxStrlen(pszFileName
);
1572 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1575 // find a file in a list of directories, returns false if not found
1576 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1578 // we assume that it's not empty
1579 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1580 _T("empty file name in wxFindFileInPath"));
1582 // skip path separator in the beginning of the file name if present
1583 if ( wxIsPathSeparator(*pszFile
) )
1586 // copy the path (strtok will modify it)
1587 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1588 wxStrcpy(szPath
, pszPath
);
1591 wxChar
*pc
, *save_ptr
;
1592 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1594 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1596 // search for the file in this directory
1598 if ( !wxEndsWithPathSeparator(pc
) )
1599 strFile
+= wxFILE_SEP_PATH
;
1602 if ( wxFileExists(strFile
) ) {
1608 // suppress warning about unused variable save_ptr when wxStrtok() is a
1609 // macro which throws away its third argument
1614 return pc
!= NULL
; // if true => we breaked from the loop
1617 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1622 // it can be empty, but it shouldn't be NULL
1623 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1625 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1628 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1631 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1634 return mtime
.GetTicks();
1638 // Parses the filterStr, returning the number of filters.
1639 // Returns 0 if none or if there's a problem.
1640 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1642 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1643 wxArrayString
& descriptions
,
1644 wxArrayString
& filters
)
1646 descriptions
.Clear();
1649 wxString
str(filterStr
);
1651 wxString description
, filter
;
1653 while( pos
!= wxNOT_FOUND
)
1655 pos
= str
.Find(wxT('|'));
1656 if ( pos
== wxNOT_FOUND
)
1658 // if there are no '|'s at all in the string just take the entire
1659 // string as filter and make description empty for later autocompletion
1660 if ( filters
.IsEmpty() )
1662 descriptions
.Add(wxEmptyString
);
1663 filters
.Add(filterStr
);
1667 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1673 description
= str
.Left(pos
);
1674 str
= str
.Mid(pos
+ 1);
1675 pos
= str
.Find(wxT('|'));
1676 if ( pos
== wxNOT_FOUND
)
1682 filter
= str
.Left(pos
);
1683 str
= str
.Mid(pos
+ 1);
1686 descriptions
.Add(description
);
1687 filters
.Add(filter
);
1690 #if defined(__WXMOTIF__)
1691 // split it so there is one wildcard per entry
1692 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1694 pos
= filters
[i
].Find(wxT(';'));
1695 if (pos
!= wxNOT_FOUND
)
1697 // first split only filters
1698 descriptions
.Insert(descriptions
[i
],i
+1);
1699 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1700 filters
[i
]=filters
[i
].Left(pos
);
1702 // autoreplace new filter in description with pattern:
1703 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1704 // cause split into:
1705 // C/C++ Files(*.cpp)|*.cpp
1706 // C/C++ Files(*.c;*.h)|*.c;*.h
1707 // and next iteration cause another split into:
1708 // C/C++ Files(*.cpp)|*.cpp
1709 // C/C++ Files(*.c)|*.c
1710 // C/C++ Files(*.h)|*.h
1711 for ( size_t k
=i
;k
<i
+2;k
++ )
1713 pos
= descriptions
[k
].Find(filters
[k
]);
1714 if (pos
!= wxNOT_FOUND
)
1716 wxString before
= descriptions
[k
].Left(pos
);
1717 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1718 pos
= before
.Find(_T('('),true);
1719 if (pos
>before
.Find(_T(')'),true))
1721 before
= before
.Left(pos
+1);
1722 before
<< filters
[k
];
1723 pos
= after
.Find(_T(')'));
1724 int pos1
= after
.Find(_T('('));
1725 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1727 before
<< after
.Mid(pos
);
1728 descriptions
[k
] = before
;
1738 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1740 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1742 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1746 return filters
.GetCount();
1750 //------------------------------------------------------------------------
1751 // wild character routines
1752 //------------------------------------------------------------------------
1754 bool wxIsWild( const wxString
& pattern
)
1756 wxString tmp
= pattern
;
1757 wxChar
*pat
= WXSTRINGCAST(tmp
);
1762 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1773 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1775 * The match procedure is public domain code (from ircII's reg.c)
1776 * but modified to suit our tastes (RN: No "%" syntax I guess)
1779 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1783 /* Match if both are empty. */
1787 const wxChar
*m
= pat
.c_str(),
1795 if (dot_special
&& (*n
== wxT('.')))
1797 /* Never match so that hidden Unix files
1798 * are never found. */
1811 else if (*m
== wxT('?'))
1819 if (*m
== wxT('\\'))
1822 /* Quoting "nothing" is a bad thing */
1829 * If we are out of both strings or we just
1830 * saw a wildcard, then we can say we have a
1841 * We could check for *n == NULL at this point, but
1842 * since it's more common to have a character there,
1843 * check to see if they match first (m and n) and
1844 * then if they don't match, THEN we can check for
1860 * If there are no more characters in the
1861 * string, but we still need to find another
1862 * character (*m != NULL), then it will be
1863 * impossible to match it
1881 // Return the type of an open file
1883 // Some file types on some platforms seem seekable but in fact are not.
1884 // The main use of this function is to allow such cases to be detected
1885 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1887 // This is important for the archive streams, which benefit greatly from
1888 // being able to seek on a stream, but which will produce corrupt archives
1889 // if they unknowingly seek on a non-seekable stream.
1891 // wxFILE_KIND_DISK is a good catch all return value, since other values
1892 // disable features of the archive streams. Some other value must be returned
1893 // for a file type that appears seekable but isn't.
1896 // * Pipes on Windows
1897 // * Files on VMS with a record format other than StreamLF
1899 wxFileKind
wxGetFileKind(int fd
)
1901 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1902 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1904 case FILE_TYPE_CHAR
:
1905 return wxFILE_KIND_TERMINAL
;
1906 case FILE_TYPE_DISK
:
1907 return wxFILE_KIND_DISK
;
1908 case FILE_TYPE_PIPE
:
1909 return wxFILE_KIND_PIPE
;
1912 return wxFILE_KIND_UNKNOWN
;
1914 #elif defined(__UNIX__)
1916 return wxFILE_KIND_TERMINAL
;
1921 if (S_ISFIFO(st
.st_mode
))
1922 return wxFILE_KIND_PIPE
;
1923 if (!S_ISREG(st
.st_mode
))
1924 return wxFILE_KIND_UNKNOWN
;
1926 #if defined(__VMS__)
1927 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1928 return wxFILE_KIND_UNKNOWN
;
1931 return wxFILE_KIND_DISK
;
1934 #define wxFILEKIND_STUB
1936 return wxFILE_KIND_DISK
;
1940 wxFileKind
wxGetFileKind(FILE *fp
)
1942 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1943 // Should be fixed in version 1.4.
1944 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1946 return wxFILE_KIND_DISK
;
1948 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1953 #pragma warning(default:4706) // assignment within conditional expression