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"
30 #include "wx/file.h" // This does include filefn.h
31 #include "wx/filename.h"
34 // there are just too many of those...
36 #pragma warning(disable:4706) // assignment within conditional expression
43 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
44 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
49 #if defined(__WXMAC__)
50 #include "wx/mac/private.h" // includes mac headers
56 #include "wx/msw/private.h"
57 #include "wx/msw/mslu.h"
59 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
61 // note that it must be included after <windows.h>
64 #include <sys/cygwin.h>
66 #endif // __GNUWIN32__
68 // io.h is needed for _get_osfhandle()
69 // Already included by filefn.h for many Windows compilers
70 #if defined __MWERKS__ || defined __CYGWIN__
79 // TODO: Borland probably has _wgetcwd as well?
84 // ----------------------------------------------------------------------------
86 // ----------------------------------------------------------------------------
89 #define _MAXPATHLEN 1024
93 # include "MoreFilesX.h"
96 // ----------------------------------------------------------------------------
98 // ----------------------------------------------------------------------------
100 // MT-FIXME: get rid of this horror and all code using it
101 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
103 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
105 // VisualAge C++ V4.0 cannot have any external linkage const decs
106 // in headers included by more than one primary source
108 const int wxInvalidOffset
= -1;
111 // ----------------------------------------------------------------------------
113 // ----------------------------------------------------------------------------
115 // we need to translate Mac filenames before passing them to OS functions
116 #define OS_FILENAME(s) (s.fn_str())
118 // ============================================================================
120 // ============================================================================
122 #ifdef wxNEED_WX_UNISTD_H
124 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
126 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
129 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
131 return access( wxConvFile
.cWX2MB( pathname
), mode
);
134 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
136 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
140 // wxNEED_WX_UNISTD_H
142 // ----------------------------------------------------------------------------
144 // ----------------------------------------------------------------------------
146 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
148 static inline wxChar
* MYcopystring(const wxString
& s
)
150 wxChar
* copy
= new wxChar
[s
.length() + 1];
151 return wxStrcpy(copy
, s
.c_str());
154 static inline wxChar
* MYcopystring(const wxChar
* s
)
156 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
157 return wxStrcpy(copy
, s
);
160 void wxPathList::Add (const wxString
& path
)
162 wxStringList::Add (WXSTRINGCAST path
);
165 // Add paths e.g. from the PATH environment variable
166 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
168 // No environment variables on WinCE
170 static const wxChar PATH_TOKS
[] =
171 #if defined(__WINDOWS__) || defined(__OS2__)
173 The space has been removed from the tokenizers, otherwise a
174 path such as "C:\Program Files" would be split into 2 paths:
175 "C:\Program" and "Files"
177 // wxT(" ;"); // Don't separate with colon in DOS (used for drive)
178 wxT(";"); // Don't separate with colon in DOS (used for drive)
184 if (wxGetEnv (WXSTRINGCAST envVariable
, &val
))
186 wxChar
*s
= MYcopystring (val
);
187 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
194 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
202 // suppress warning about unused variable save_ptr when wxStrtok() is a
203 // macro which throws away its third argument
208 #endif // !__WXWINCE__
211 // Given a full filename (with path), ensure that that file can
212 // be accessed again USING FILENAME ONLY by adding the path
213 // to the list if not already there.
214 void wxPathList::EnsureFileAccessible (const wxString
& path
)
216 wxString
path_only(wxPathOnly(path
));
217 if ( !path_only
.empty() )
219 if ( !Member(path_only
) )
224 bool wxPathList::Member (const wxString
& path
)
226 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
228 wxString
path2( node
->GetData() );
230 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined(__WXMAC__)
232 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
234 // Case sensitive File System
235 path
.CompareTo (path2
) == 0
243 wxString
wxPathList::FindValidPath (const wxString
& file
)
245 wxExpandPath(wxFileFunctionsBuffer
, file
);
247 wxChar buf
[_MAXPATHLEN
];
248 wxStrcpy(buf
, wxFileFunctionsBuffer
);
250 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
252 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
254 const wxString
path(node
->GetData());
255 wxStrcpy (wxFileFunctionsBuffer
, path
);
256 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
257 if (ch
!= wxT('\\') && ch
!= wxT('/'))
258 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
259 wxStrcat (wxFileFunctionsBuffer
, filename
);
261 wxUnix2DosFilename (wxFileFunctionsBuffer
);
263 if (wxFileExists (wxFileFunctionsBuffer
))
265 return wxString(wxFileFunctionsBuffer
); // Found!
269 return wxEmptyString
; // Not found
272 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
274 wxString f
= FindValidPath(file
);
275 if ( f
.empty() || wxIsAbsolutePath(f
) )
278 wxString buf
= ::wxGetCwd();
280 if ( !wxEndsWithPathSeparator(buf
) )
282 buf
+= wxFILE_SEP_PATH
;
290 wxFileExists (const wxString
& filename
)
292 #if defined(__WXPALMOS__)
294 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
295 // we must use GetFileAttributes() instead of the ANSI C functions because
296 // it can cope with network (UNC) paths unlike them
297 DWORD ret
= ::GetFileAttributes(filename
);
299 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
302 #ifndef wxNEED_WX_UNISTD_H
303 return (wxStat( filename
.fn_str() , &st
) == 0 && (st
.st_mode
& S_IFREG
))
305 || (errno
== EACCES
) // if access is denied something with that name
306 // exists and is opened in exclusive mode.
310 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
312 #endif // __WIN32__/!__WIN32__
316 wxIsAbsolutePath (const wxString
& filename
)
318 if (!filename
.empty())
320 #if defined(__WXMAC__) && !defined(__DARWIN__)
321 // Classic or Carbon CodeWarrior like
322 // Carbon with Apple DevTools is Unix like
324 // This seems wrong to me, but there is no fix. since
325 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
326 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
327 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
330 // Unix like or Windows
331 if (filename
[0] == wxT('/'))
335 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
338 #if defined(__WINDOWS__) || defined(__OS2__)
340 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
348 * Strip off any extension (dot something) from end of file,
349 * IF one exists. Inserts zero into buffer.
353 void wxStripExtension(wxChar
*buffer
)
355 int len
= wxStrlen(buffer
);
359 if (buffer
[i
] == wxT('.'))
368 void wxStripExtension(wxString
& buffer
)
370 //RN: Be careful about the handling the case where
371 //buffer.length() == 0
372 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
374 if (buffer
.GetChar(i
) == wxT('.'))
376 buffer
= buffer
.Left(i
);
382 // Destructive removal of /./ and /../ stuff
383 wxChar
*wxRealPath (wxChar
*path
)
386 static const wxChar SEP
= wxT('\\');
387 wxUnix2DosFilename(path
);
389 static const wxChar SEP
= wxT('/');
391 if (path
[0] && path
[1]) {
392 /* MATTHEW: special case "/./x" */
394 if (path
[2] == SEP
&& path
[1] == wxT('.'))
402 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
405 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
410 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
411 && (q
- 1 <= path
|| q
[-1] != SEP
))
414 if (path
[0] == wxT('\0'))
419 #if defined(__WXMSW__) || defined(__OS2__)
420 /* Check that path[2] is NULL! */
421 else if (path
[1] == wxT(':') && !path
[2])
430 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
438 wxString
wxRealPath(const wxString
& path
)
440 wxChar
*buf1
=MYcopystring(path
);
441 wxChar
*buf2
=wxRealPath(buf1
);
449 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
451 if (filename
.empty())
452 return (wxChar
*) NULL
;
454 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
456 wxString buf
= ::wxGetCwd();
457 wxChar ch
= buf
.Last();
459 if (ch
!= wxT('\\') && ch
!= wxT('/'))
465 buf
<< wxFileFunctionsBuffer
;
466 buf
= wxRealPath( buf
);
467 return MYcopystring( buf
);
469 return MYcopystring( wxFileFunctionsBuffer
);
475 ~user/ => user's home dir
476 If the environment variable a = "foo" and b = "bar" then:
493 /* input name in name, pathname output to buf. */
495 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
497 register wxChar
*d
, *s
, *nm
;
498 wxChar lnm
[_MAXPATHLEN
];
501 // Some compilers don't like this line.
502 // const wxChar trimchars[] = wxT("\n \t");
505 trimchars
[0] = wxT('\n');
506 trimchars
[1] = wxT(' ');
507 trimchars
[2] = wxT('\t');
511 const wxChar SEP
= wxT('\\');
513 const wxChar SEP
= wxT('/');
516 if (name
== NULL
|| *name
== wxT('\0'))
518 nm
= MYcopystring(name
); // Make a scratch copy
521 /* Skip leading whitespace and cr */
522 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
524 /* And strip off trailing whitespace and cr */
525 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
526 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
534 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
537 /* Expand inline environment variables */
555 while ((*d
++ = *s
) != 0) {
557 if (*s
== wxT('\\')) {
558 if ((*(d
- 1) = *++s
)!=0) {
566 // No env variables on WinCE
569 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
571 if (*s
++ == wxT('$'))
574 register wxChar
*start
= d
;
575 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
576 register wxChar
*value
;
577 while ((*d
++ = *s
) != 0)
578 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
583 value
= wxGetenv(braces
? start
+ 1 : start
);
585 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
599 /* Expand ~ and ~user */
601 if (nm
[0] == wxT('~') && !q
)
604 if (nm
[1] == SEP
|| nm
[1] == 0)
606 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
607 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
612 { /* ~user/filename */
613 register wxChar
*nnm
;
614 register wxChar
*home
;
615 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
619 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
620 was_sep
= (*s
== SEP
);
621 nnm
= *s
? s
+ 1 : s
;
623 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
624 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
)
626 if (was_sep
) /* replace only if it was there: */
639 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
641 while (wxT('\0') != (*d
++ = *s
++))
644 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
648 while ((*d
++ = *s
++) != 0)
652 delete[] nm_tmp
; // clean up alloc
653 /* Now clean up the buffer */
654 return wxRealPath(buf
);
657 /* Contract Paths to be build upon an environment variable
660 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
662 The call wxExpandPath can convert these back!
665 wxContractPath (const wxString
& filename
,
666 const wxString
& WXUNUSED_IN_WINCE(envname
),
667 const wxString
& user
)
669 static wxChar dest
[_MAXPATHLEN
];
671 if (filename
.empty())
672 return (wxChar
*) NULL
;
674 wxStrcpy (dest
, WXSTRINGCAST filename
);
676 wxUnix2DosFilename(dest
);
679 // Handle environment
683 if (!envname
.empty() && (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
684 (tcp
= wxStrstr (dest
, val
)) != NULL
)
686 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
689 wxStrcpy (tcp
, WXSTRINGCAST envname
);
690 wxStrcat (tcp
, wxT("}"));
691 wxStrcat (tcp
, wxFileFunctionsBuffer
);
695 // Handle User's home (ignore root homes!)
696 val
= wxGetUserHome (user
);
700 const size_t len
= wxStrlen(val
);
704 if (wxStrncmp(dest
, val
, len
) == 0)
706 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
708 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
709 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
710 wxStrcpy (dest
, wxFileFunctionsBuffer
);
716 // Return just the filename, not the path (basename)
717 wxChar
*wxFileNameFromPath (wxChar
*path
)
720 wxString n
= wxFileNameFromPath(p
);
722 return path
+ p
.length() - n
.length();
725 wxString
wxFileNameFromPath (const wxString
& path
)
728 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
730 wxString fullname
= name
;
733 fullname
<< wxFILE_SEP_EXT
<< ext
;
739 // Return just the directory, or NULL if no directory
741 wxPathOnly (wxChar
*path
)
745 static wxChar buf
[_MAXPATHLEN
];
748 wxStrcpy (buf
, path
);
750 int l
= wxStrlen(path
);
753 // Search backward for a backward or forward slash
756 #if defined(__WXMAC__) && !defined(__DARWIN__)
757 // Classic or Carbon CodeWarrior like
758 // Carbon with Apple DevTools is Unix like
759 if (path
[i
] == wxT(':') )
765 // Unix like or Windows
766 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
773 if (path
[i
] == wxT(']'))
782 #if defined(__WXMSW__) || defined(__OS2__)
783 // Try Drive specifier
784 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
786 // A:junk --> A:. (since A:.\junk Not A:\junk)
793 return (wxChar
*) NULL
;
796 // Return just the directory, or NULL if no directory
797 wxString
wxPathOnly (const wxString
& path
)
801 wxChar buf
[_MAXPATHLEN
];
804 wxStrcpy (buf
, WXSTRINGCAST path
);
806 int l
= path
.length();
809 // Search backward for a backward or forward slash
812 #if defined(__WXMAC__) && !defined(__DARWIN__)
813 // Classic or Carbon CodeWarrior like
814 // Carbon with Apple DevTools is Unix like
815 if (path
[i
] == wxT(':') )
818 return wxString(buf
);
821 // Unix like or Windows
822 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
824 // Don't return an empty string
828 return wxString(buf
);
832 if (path
[i
] == wxT(']'))
835 return wxString(buf
);
841 #if defined(__WXMSW__) || defined(__OS2__)
842 // Try Drive specifier
843 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
845 // A:junk --> A:. (since A:.\junk Not A:\junk)
848 return wxString(buf
);
852 return wxEmptyString
;
855 // Utility for converting delimiters in DOS filenames to UNIX style
856 // and back again - or we get nasty problems with delimiters.
857 // Also, convert to lower case, since case is significant in UNIX.
859 #if defined(__WXMAC__)
861 #if TARGET_API_MAC_OSX
862 #define kDefaultPathStyle kCFURLPOSIXPathStyle
864 #define kDefaultPathStyle kCFURLHFSPathStyle
867 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
870 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
871 if ( additionalPathComponent
)
873 CFURLRef parentURLRef
= fullURLRef
;
874 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
875 additionalPathComponent
,false);
876 CFRelease( parentURLRef
) ;
878 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
879 CFRelease( fullURLRef
) ;
880 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
883 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
885 OSStatus err
= noErr
;
886 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
889 if ( CFURLGetFSRef(url
, fsRef
) == false )
900 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
902 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
905 return wxMacCFStringHolder(cfname
).AsString() ;
908 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
911 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
913 return wxMacFSRefToPath( &fsRef
) ;
915 return wxEmptyString
;
918 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
920 OSStatus err
= noErr
;
922 wxMacPathToFSRef( path
, &fsRef
) ;
923 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
929 wxDos2UnixFilename (wxChar
*s
)
938 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
945 #if defined(__WXMSW__) || defined(__OS2__)
946 wxUnix2DosFilename (wxChar
*s
)
948 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
951 // Yes, I really mean this to happen under DOS only! JACS
952 #if defined(__WXMSW__) || defined(__OS2__)
963 // Concatenate two files to form third
965 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
969 wxFile
in1(file1
), in2(file2
);
970 wxTempFile
out(file3
);
972 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
976 unsigned char buf
[1024];
978 for( int i
=0; i
<2; i
++)
980 wxFile
*in
= i
==0 ? &in1
: &in2
;
982 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
984 if ( !out
.Write(buf
,ofs
) )
986 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1003 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1005 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1006 // CopyFile() copies file attributes and modification time too, so use it
1007 // instead of our code if available
1009 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1010 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1012 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1013 file1
.c_str(), file2
.c_str());
1017 #elif defined(__OS2__)
1018 if ( ::DosCopy((PSZ
)file1
.c_str(), (PSZ
)file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1020 #elif defined(__PALMOS__)
1021 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1023 #elif wxUSE_FILE // !Win32
1026 // get permissions of file1
1027 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1029 // the file probably doesn't exist or we haven't the rights to read
1031 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1036 // open file1 for reading
1037 wxFile
fileIn(file1
, wxFile::read
);
1038 if ( !fileIn
.IsOpened() )
1041 // remove file2, if it exists. This is needed for creating
1042 // file2 with the correct permissions in the next step
1043 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1045 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1050 // reset the umask as we want to create the file with exactly the same
1051 // permissions as the original one
1054 // create file2 with the same permissions than file1 and open it for
1058 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1061 // copy contents of file1 to file2
1066 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1067 if ( fileIn
.Error() )
1074 if ( fileOut
.Write(buf
, count
) < count
)
1078 // we can expect fileIn to be closed successfully, but we should ensure
1079 // that fileOut was closed as some write errors (disk full) might not be
1080 // detected before doing this
1081 if ( !fileIn
.Close() || !fileOut
.Close() )
1084 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1085 // no chmod in VA. Should be some permission API for HPFS386 partitions
1087 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1089 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1093 #endif // OS/2 || Mac
1095 #else // !Win32 && ! wxUSE_FILE
1097 // impossible to simulate with wxWidgets API
1100 wxUnusedVar(overwrite
);
1103 #endif // __WXMSW__ && __WIN32__
1109 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1111 if ( !overwrite
&& wxFileExists(file2
) )
1115 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1116 file1
.c_str(), file2
.c_str()
1122 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1123 // Normal system call
1124 if ( wxRename (file1
, file2
) == 0 )
1129 if (wxCopyFile(file1
, file2
, overwrite
)) {
1130 wxRemoveFile(file1
);
1137 bool wxRemoveFile(const wxString
& file
)
1139 #if defined(__VISUALC__) \
1140 || defined(__BORLANDC__) \
1141 || defined(__WATCOMC__) \
1142 || defined(__DMC__) \
1143 || defined(__GNUWIN32__) \
1144 || (defined(__MWERKS__) && defined(__MSL__))
1145 int res
= wxRemove(file
);
1146 #elif defined(__WXMAC__)
1147 int res
= unlink(wxFNCONV(file
));
1148 #elif defined(__WXPALMOS__)
1150 // TODO with VFSFileDelete()
1152 int res
= unlink(OS_FILENAME(file
));
1158 bool wxMkdir(const wxString
& dir
, int perm
)
1160 #if defined(__WXPALMOS__)
1162 #elif defined(__WXMAC__) && !defined(__UNIX__)
1163 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1165 const wxChar
*dirname
= dir
.c_str();
1167 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1168 // for the GNU compiler
1169 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1172 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1174 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1176 #elif defined(__OS2__)
1178 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1179 #elif defined(__DOS__)
1180 #if defined(__WATCOMC__)
1182 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1183 #elif defined(__DJGPP__)
1184 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1186 #error "Unsupported DOS compiler!"
1188 #else // !MSW, !DOS and !OS/2 VAC++
1191 if ( !CreateDirectory(dirname
, NULL
) )
1193 if ( wxMkDir(dir
.fn_str()) != 0 )
1197 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1206 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1208 #if defined(__VMS__)
1209 return false; //to be changed since rmdir exists in VMS7.x
1210 #elif defined(__OS2__)
1211 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1212 #elif defined(__WXWINCE__)
1213 return (CreateDirectory(dir
, NULL
) != 0);
1214 #elif defined(__WXPALMOS__)
1215 // TODO with VFSFileRename()
1218 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1222 // does the path exists? (may have or not '/' or '\\' at the end)
1223 bool wxDirExists(const wxChar
*pszPathName
)
1225 wxString
strPath(pszPathName
);
1227 #if defined(__WINDOWS__) || defined(__OS2__)
1228 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1229 // so remove all trailing backslashes from the path - but don't do this for
1230 // the pathes "d:\" (which are different from "d:") nor for just "\"
1231 while ( wxEndsWithPathSeparator(strPath
) )
1233 size_t len
= strPath
.length();
1234 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1237 strPath
.Truncate(len
- 1);
1239 #endif // __WINDOWS__
1242 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1243 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1247 #if defined(__WXPALMOS__)
1249 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1250 // stat() can't cope with network paths
1251 DWORD ret
= ::GetFileAttributes(strPath
);
1253 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1254 #elif defined(__OS2__)
1255 FILESTATUS3 Info
= {{0}};
1256 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1257 (void*) &Info
, sizeof(FILESTATUS3
));
1259 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1260 (rc
== ERROR_SHARING_VIOLATION
);
1261 // If we got a sharing violation, there must be something with this name.
1265 #ifndef __VISAGECPP__
1266 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1268 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1269 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1272 #endif // __WIN32__/!__WIN32__
1275 // Get a temporary filename, opening and closing the file.
1276 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1279 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1280 if ( filename
.empty() )
1284 wxStrcpy(buf
, filename
);
1286 buf
= MYcopystring(filename
);
1290 wxUnusedVar(prefix
);
1292 // wxFileName::CreateTempFileName needs wxFile class enabled
1297 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1299 buf
= wxGetTempFileName(prefix
);
1301 return !buf
.empty();
1304 // Get first file name matching given wild card.
1306 static wxDir
*gs_dir
= NULL
;
1307 static wxString gs_dirPath
;
1309 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1311 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1312 if ( gs_dirPath
.empty() )
1313 gs_dirPath
= wxT(".");
1314 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1315 gs_dirPath
<< wxFILE_SEP_PATH
;
1319 gs_dir
= new wxDir(gs_dirPath
);
1321 if ( !gs_dir
->IsOpened() )
1323 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1324 return wxEmptyString
;
1330 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1331 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1332 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1336 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1337 if ( result
.empty() )
1343 return gs_dirPath
+ result
;
1346 wxString
wxFindNextFile()
1348 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1351 gs_dir
->GetNext(&result
);
1353 if ( result
.empty() )
1359 return gs_dirPath
+ result
;
1363 // Get current working directory.
1364 // If buf is NULL, allocates space using new, else copies into buf.
1365 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1366 // wxDoGetCwd() is their common core to be moved
1367 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1368 // Do not expose wxDoGetCwd in headers!
1370 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1372 #if defined(__WXPALMOS__)
1374 if(buf
&& sz
>0) buf
[0] = _T('\0');
1376 #elif defined(__WXWINCE__)
1378 if(buf
&& sz
>0) buf
[0] = _T('\0');
1383 buf
= new wxChar
[sz
+ 1];
1386 bool ok
wxDUMMY_INITIALIZE(false);
1388 // for the compilers which have Unicode version of _getcwd(), call it
1389 // directly, for the others call the ANSI version and do the translation
1392 #else // wxUSE_UNICODE
1393 bool needsANSI
= true;
1395 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1396 char cbuf
[_MAXPATHLEN
];
1400 #if wxUSE_UNICODE_MSLU
1401 if ( wxGetOsVersion() != wxWIN95
)
1403 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1406 ok
= _wgetcwd(buf
, sz
) != NULL
;
1412 #endif // wxUSE_UNICODE
1414 #if defined(_MSC_VER) || defined(__MINGW32__)
1415 ok
= _getcwd(cbuf
, sz
) != NULL
;
1416 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1418 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1420 wxString
res( lbuf
, *wxConvCurrent
) ;
1421 wxStrcpy( buf
, res
) ;
1426 #elif defined(__OS2__)
1428 ULONG ulDriveNum
= 0;
1429 ULONG ulDriveMap
= 0;
1430 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1435 rc
= ::DosQueryCurrentDir( 0 // current drive
1439 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1444 #else // !Win32/VC++ !Mac !OS2
1445 ok
= getcwd(cbuf
, sz
) != NULL
;
1448 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1449 // finally convert the result to Unicode if needed
1450 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1451 #endif // wxUSE_UNICODE
1456 wxLogSysError(_("Failed to get the working directory"));
1458 // VZ: the old code used to return "." on error which didn't make any
1459 // sense at all to me - empty string is a better error indicator
1460 // (NULL might be even better but I'm afraid this could lead to
1461 // problems with the old code assuming the return is never NULL)
1464 else // ok, but we might need to massage the path into the right format
1467 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1468 // with / deliminers. We don't like that.
1469 for (wxChar
*ch
= buf
; *ch
; ch
++)
1471 if (*ch
== wxT('/'))
1476 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1477 // he needs Unix as opposed to Win32 pathnames
1478 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1479 // another example of DOS/Unix mix (Cygwin)
1480 wxString pathUnix
= buf
;
1482 char bufA
[_MAXPATHLEN
];
1483 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1484 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1486 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1487 #endif // wxUSE_UNICODE
1488 #endif // __CYGWIN__
1501 #if WXWIN_COMPATIBILITY_2_6
1502 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1504 return wxDoGetCwd(buf
,sz
);
1506 #endif // WXWIN_COMPATIBILITY_2_6
1511 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1515 bool wxSetWorkingDirectory(const wxString
& d
)
1517 #if defined(__OS2__)
1518 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1519 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1520 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1521 #elif defined(__WINDOWS__)
1525 // No equivalent in WinCE
1529 return (bool)(SetCurrentDirectory(d
) != 0);
1532 // Must change drive, too.
1533 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1536 wxChar firstChar
= d
[0];
1540 firstChar
= firstChar
- 32;
1542 // To a drive number
1543 unsigned int driveNo
= firstChar
- 64;
1546 unsigned int noDrives
;
1547 _dos_setdrive(driveNo
, &noDrives
);
1550 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1558 // Get the OS directory if appropriate (such as the Windows directory).
1559 // On non-Windows platform, probably just return the empty string.
1560 wxString
wxGetOSDirectory()
1563 return wxString(wxT("\\Windows"));
1564 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1566 GetWindowsDirectory(buf
, 256);
1567 return wxString(buf
);
1568 #elif defined(__WXMAC__)
1569 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1571 return wxEmptyString
;
1575 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1577 size_t len
= wxStrlen(pszFileName
);
1579 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1582 // find a file in a list of directories, returns false if not found
1583 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1585 // we assume that it's not empty
1586 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1587 _T("empty file name in wxFindFileInPath"));
1589 // skip path separator in the beginning of the file name if present
1590 if ( wxIsPathSeparator(*pszFile
) )
1593 // copy the path (strtok will modify it)
1594 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1595 wxStrcpy(szPath
, pszPath
);
1598 wxChar
*pc
, *save_ptr
;
1599 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1601 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1603 // search for the file in this directory
1605 if ( !wxEndsWithPathSeparator(pc
) )
1606 strFile
+= wxFILE_SEP_PATH
;
1609 if ( wxFileExists(strFile
) ) {
1615 // suppress warning about unused variable save_ptr when wxStrtok() is a
1616 // macro which throws away its third argument
1621 return pc
!= NULL
; // if true => we breaked from the loop
1624 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1629 // it can be empty, but it shouldn't be NULL
1630 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1632 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1635 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1638 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1641 return mtime
.GetTicks();
1645 // Parses the filterStr, returning the number of filters.
1646 // Returns 0 if none or if there's a problem.
1647 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1649 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1650 wxArrayString
& descriptions
,
1651 wxArrayString
& filters
)
1653 descriptions
.Clear();
1656 wxString
str(filterStr
);
1658 wxString description
, filter
;
1660 while( pos
!= wxNOT_FOUND
)
1662 pos
= str
.Find(wxT('|'));
1663 if ( pos
== wxNOT_FOUND
)
1665 // if there are no '|'s at all in the string just take the entire
1666 // string as filter and make description empty for later autocompletion
1667 if ( filters
.IsEmpty() )
1669 descriptions
.Add(wxEmptyString
);
1670 filters
.Add(filterStr
);
1674 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1680 description
= str
.Left(pos
);
1681 str
= str
.Mid(pos
+ 1);
1682 pos
= str
.Find(wxT('|'));
1683 if ( pos
== wxNOT_FOUND
)
1689 filter
= str
.Left(pos
);
1690 str
= str
.Mid(pos
+ 1);
1693 descriptions
.Add(description
);
1694 filters
.Add(filter
);
1697 #if defined(__WXMOTIF__)
1698 // split it so there is one wildcard per entry
1699 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1701 pos
= filters
[i
].Find(wxT(';'));
1702 if (pos
!= wxNOT_FOUND
)
1704 // first split only filters
1705 descriptions
.Insert(descriptions
[i
],i
+1);
1706 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1707 filters
[i
]=filters
[i
].Left(pos
);
1709 // autoreplace new filter in description with pattern:
1710 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1711 // cause split into:
1712 // C/C++ Files(*.cpp)|*.cpp
1713 // C/C++ Files(*.c;*.h)|*.c;*.h
1714 // and next iteration cause another split into:
1715 // C/C++ Files(*.cpp)|*.cpp
1716 // C/C++ Files(*.c)|*.c
1717 // C/C++ Files(*.h)|*.h
1718 for ( size_t k
=i
;k
<i
+2;k
++ )
1720 pos
= descriptions
[k
].Find(filters
[k
]);
1721 if (pos
!= wxNOT_FOUND
)
1723 wxString before
= descriptions
[k
].Left(pos
);
1724 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1725 pos
= before
.Find(_T('('),true);
1726 if (pos
>before
.Find(_T(')'),true))
1728 before
= before
.Left(pos
+1);
1729 before
<< filters
[k
];
1730 pos
= after
.Find(_T(')'));
1731 int pos1
= after
.Find(_T('('));
1732 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1734 before
<< after
.Mid(pos
);
1735 descriptions
[k
] = before
;
1745 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1747 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1749 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1753 return filters
.GetCount();
1757 //------------------------------------------------------------------------
1758 // wild character routines
1759 //------------------------------------------------------------------------
1761 bool wxIsWild( const wxString
& pattern
)
1763 wxString tmp
= pattern
;
1764 wxChar
*pat
= WXSTRINGCAST(tmp
);
1769 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1780 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1782 * The match procedure is public domain code (from ircII's reg.c)
1783 * but modified to suit our tastes (RN: No "%" syntax I guess)
1786 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1790 /* Match if both are empty. */
1794 const wxChar
*m
= pat
.c_str(),
1802 if (dot_special
&& (*n
== wxT('.')))
1804 /* Never match so that hidden Unix files
1805 * are never found. */
1818 else if (*m
== wxT('?'))
1826 if (*m
== wxT('\\'))
1829 /* Quoting "nothing" is a bad thing */
1836 * If we are out of both strings or we just
1837 * saw a wildcard, then we can say we have a
1848 * We could check for *n == NULL at this point, but
1849 * since it's more common to have a character there,
1850 * check to see if they match first (m and n) and
1851 * then if they don't match, THEN we can check for
1867 * If there are no more characters in the
1868 * string, but we still need to find another
1869 * character (*m != NULL), then it will be
1870 * impossible to match it
1888 // Return the type of an open file
1890 // Some file types on some platforms seem seekable but in fact are not.
1891 // The main use of this function is to allow such cases to be detected
1892 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1894 // This is important for the archive streams, which benefit greatly from
1895 // being able to seek on a stream, but which will produce corrupt archives
1896 // if they unknowingly seek on a non-seekable stream.
1898 // wxFILE_KIND_DISK is a good catch all return value, since other values
1899 // disable features of the archive streams. Some other value must be returned
1900 // for a file type that appears seekable but isn't.
1903 // * Pipes on Windows
1904 // * Files on VMS with a record format other than StreamLF
1906 wxFileKind
wxGetFileKind(int fd
)
1908 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1909 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1911 case FILE_TYPE_CHAR
:
1912 return wxFILE_KIND_TERMINAL
;
1913 case FILE_TYPE_DISK
:
1914 return wxFILE_KIND_DISK
;
1915 case FILE_TYPE_PIPE
:
1916 return wxFILE_KIND_PIPE
;
1919 return wxFILE_KIND_UNKNOWN
;
1921 #elif defined(__UNIX__)
1923 return wxFILE_KIND_TERMINAL
;
1928 if (S_ISFIFO(st
.st_mode
))
1929 return wxFILE_KIND_PIPE
;
1930 if (!S_ISREG(st
.st_mode
))
1931 return wxFILE_KIND_UNKNOWN
;
1933 #if defined(__VMS__)
1934 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1935 return wxFILE_KIND_UNKNOWN
;
1938 return wxFILE_KIND_DISK
;
1941 #define wxFILEKIND_STUB
1943 return wxFILE_KIND_DISK
;
1947 wxFileKind
wxGetFileKind(FILE *fp
)
1949 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1950 // Should be fixed in version 1.4.
1951 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1953 return wxFILE_KIND_DISK
;
1955 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1960 #pragma warning(default:4706) // assignment within conditional expression