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"
32 #include "wx/file.h" // This does include filefn.h
33 #include "wx/filename.h"
36 // there are just too many of those...
38 #pragma warning(disable:4706) // assignment within conditional expression
45 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
46 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
51 #if defined(__WXMAC__)
52 #include "wx/mac/private.h" // includes mac headers
58 #include "wx/msw/private.h"
59 #include "wx/msw/mslu.h"
61 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
63 // note that it must be included after <windows.h>
66 #include <sys/cygwin.h>
68 #endif // __GNUWIN32__
70 // io.h is needed for _get_osfhandle()
71 // Already included by filefn.h for many Windows compilers
72 #if defined __MWERKS__ || defined __CYGWIN__
81 // TODO: Borland probably has _wgetcwd as well?
86 // ----------------------------------------------------------------------------
88 // ----------------------------------------------------------------------------
91 #define _MAXPATHLEN 1024
95 # include "MoreFilesX.h"
98 // ----------------------------------------------------------------------------
100 // ----------------------------------------------------------------------------
102 // MT-FIXME: get rid of this horror and all code using it
103 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
105 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
107 // VisualAge C++ V4.0 cannot have any external linkage const decs
108 // in headers included by more than one primary source
110 const int wxInvalidOffset
= -1;
113 // ----------------------------------------------------------------------------
115 // ----------------------------------------------------------------------------
117 // we need to translate Mac filenames before passing them to OS functions
118 #define OS_FILENAME(s) (s.fn_str())
120 // ============================================================================
122 // ============================================================================
124 #ifdef wxNEED_WX_UNISTD_H
126 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
128 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
131 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
133 return access( wxConvFile
.cWX2MB( pathname
), mode
);
136 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
138 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
142 // wxNEED_WX_UNISTD_H
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
148 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
150 static inline wxChar
* MYcopystring(const wxString
& s
)
152 wxChar
* copy
= new wxChar
[s
.length() + 1];
153 return wxStrcpy(copy
, s
.c_str());
156 static inline wxChar
* MYcopystring(const wxChar
* s
)
158 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
159 return wxStrcpy(copy
, s
);
162 void wxPathList::Add (const wxString
& path
)
164 wxStringList::Add (WXSTRINGCAST path
);
167 // Add paths e.g. from the PATH environment variable
168 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
170 // No environment variables on WinCE
172 static const wxChar PATH_TOKS
[] =
173 #if defined(__WINDOWS__) || defined(__OS2__)
175 The space has been removed from the tokenizers, otherwise a
176 path such as "C:\Program Files" would be split into 2 paths:
177 "C:\Program" and "Files"
179 // wxT(" ;"); // Don't separate with colon in DOS (used for drive)
180 wxT(";"); // Don't separate with colon in DOS (used for drive)
186 if (wxGetEnv (WXSTRINGCAST envVariable
, &val
))
188 wxChar
*s
= MYcopystring (val
);
189 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
196 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
204 // suppress warning about unused variable save_ptr when wxStrtok() is a
205 // macro which throws away its third argument
210 #endif // !__WXWINCE__
213 // Given a full filename (with path), ensure that that file can
214 // be accessed again USING FILENAME ONLY by adding the path
215 // to the list if not already there.
216 void wxPathList::EnsureFileAccessible (const wxString
& path
)
218 wxString
path_only(wxPathOnly(path
));
219 if ( !path_only
.empty() )
221 if ( !Member(path_only
) )
226 bool wxPathList::Member (const wxString
& path
)
228 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
230 wxString
path2( node
->GetData() );
232 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined(__WXMAC__)
234 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
236 // Case sensitive File System
237 path
.CompareTo (path2
) == 0
245 wxString
wxPathList::FindValidPath (const wxString
& file
)
247 wxExpandPath(wxFileFunctionsBuffer
, file
);
249 wxChar buf
[_MAXPATHLEN
];
250 wxStrcpy(buf
, wxFileFunctionsBuffer
);
252 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
254 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
256 const wxString
path(node
->GetData());
257 wxStrcpy (wxFileFunctionsBuffer
, path
);
258 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
259 if (ch
!= wxT('\\') && ch
!= wxT('/'))
260 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
261 wxStrcat (wxFileFunctionsBuffer
, filename
);
263 wxUnix2DosFilename (wxFileFunctionsBuffer
);
265 if (wxFileExists (wxFileFunctionsBuffer
))
267 return wxString(wxFileFunctionsBuffer
); // Found!
271 return wxEmptyString
; // Not found
274 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
276 wxString f
= FindValidPath(file
);
277 if ( f
.empty() || wxIsAbsolutePath(f
) )
280 wxString buf
= ::wxGetCwd();
282 if ( !wxEndsWithPathSeparator(buf
) )
284 buf
+= wxFILE_SEP_PATH
;
292 wxFileExists (const wxString
& filename
)
294 #if defined(__WXPALMOS__)
296 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
297 // we must use GetFileAttributes() instead of the ANSI C functions because
298 // it can cope with network (UNC) paths unlike them
299 DWORD ret
= ::GetFileAttributes(filename
);
301 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
304 #ifndef wxNEED_WX_UNISTD_H
305 return (wxStat( filename
.fn_str() , &st
) == 0 && (st
.st_mode
& S_IFREG
))
307 || (errno
== EACCES
) // if access is denied something with that name
308 // exists and is opened in exclusive mode.
312 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
314 #endif // __WIN32__/!__WIN32__
318 wxIsAbsolutePath (const wxString
& filename
)
320 if (!filename
.empty())
322 #if defined(__WXMAC__) && !defined(__DARWIN__)
323 // Classic or Carbon CodeWarrior like
324 // Carbon with Apple DevTools is Unix like
326 // This seems wrong to me, but there is no fix. since
327 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
328 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
329 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
332 // Unix like or Windows
333 if (filename
[0] == wxT('/'))
337 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
340 #if defined(__WINDOWS__) || defined(__OS2__)
342 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
350 * Strip off any extension (dot something) from end of file,
351 * IF one exists. Inserts zero into buffer.
355 void wxStripExtension(wxChar
*buffer
)
357 int len
= wxStrlen(buffer
);
361 if (buffer
[i
] == wxT('.'))
370 void wxStripExtension(wxString
& buffer
)
372 //RN: Be careful about the handling the case where
373 //buffer.length() == 0
374 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
376 if (buffer
.GetChar(i
) == wxT('.'))
378 buffer
= buffer
.Left(i
);
384 // Destructive removal of /./ and /../ stuff
385 wxChar
*wxRealPath (wxChar
*path
)
388 static const wxChar SEP
= wxT('\\');
389 wxUnix2DosFilename(path
);
391 static const wxChar SEP
= wxT('/');
393 if (path
[0] && path
[1]) {
394 /* MATTHEW: special case "/./x" */
396 if (path
[2] == SEP
&& path
[1] == wxT('.'))
404 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
407 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
412 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
413 && (q
- 1 <= path
|| q
[-1] != SEP
))
416 if (path
[0] == wxT('\0'))
421 #if defined(__WXMSW__) || defined(__OS2__)
422 /* Check that path[2] is NULL! */
423 else if (path
[1] == wxT(':') && !path
[2])
432 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
440 wxString
wxRealPath(const wxString
& path
)
442 wxChar
*buf1
=MYcopystring(path
);
443 wxChar
*buf2
=wxRealPath(buf1
);
451 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
453 if (filename
.empty())
454 return (wxChar
*) NULL
;
456 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
458 wxString buf
= ::wxGetCwd();
459 wxChar ch
= buf
.Last();
461 if (ch
!= wxT('\\') && ch
!= wxT('/'))
467 buf
<< wxFileFunctionsBuffer
;
468 buf
= wxRealPath( buf
);
469 return MYcopystring( buf
);
471 return MYcopystring( wxFileFunctionsBuffer
);
477 ~user/ => user's home dir
478 If the environment variable a = "foo" and b = "bar" then:
495 /* input name in name, pathname output to buf. */
497 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
499 register wxChar
*d
, *s
, *nm
;
500 wxChar lnm
[_MAXPATHLEN
];
503 // Some compilers don't like this line.
504 // const wxChar trimchars[] = wxT("\n \t");
507 trimchars
[0] = wxT('\n');
508 trimchars
[1] = wxT(' ');
509 trimchars
[2] = wxT('\t');
513 const wxChar SEP
= wxT('\\');
515 const wxChar SEP
= wxT('/');
518 if (name
== NULL
|| *name
== wxT('\0'))
520 nm
= MYcopystring(name
); // Make a scratch copy
523 /* Skip leading whitespace and cr */
524 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
526 /* And strip off trailing whitespace and cr */
527 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
528 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
536 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
539 /* Expand inline environment variables */
557 while ((*d
++ = *s
) != 0) {
559 if (*s
== wxT('\\')) {
560 if ((*(d
- 1) = *++s
)!=0) {
568 // No env variables on WinCE
571 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
573 if (*s
++ == wxT('$'))
576 register wxChar
*start
= d
;
577 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
578 register wxChar
*value
;
579 while ((*d
++ = *s
) != 0)
580 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
585 value
= wxGetenv(braces
? start
+ 1 : start
);
587 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
601 /* Expand ~ and ~user */
603 if (nm
[0] == wxT('~') && !q
)
606 if (nm
[1] == SEP
|| nm
[1] == 0)
608 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
609 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
614 { /* ~user/filename */
615 register wxChar
*nnm
;
616 register wxChar
*home
;
617 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
621 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
622 was_sep
= (*s
== SEP
);
623 nnm
= *s
? s
+ 1 : s
;
625 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
626 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
)
628 if (was_sep
) /* replace only if it was there: */
641 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
643 while (wxT('\0') != (*d
++ = *s
++))
646 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
650 while ((*d
++ = *s
++) != 0)
654 delete[] nm_tmp
; // clean up alloc
655 /* Now clean up the buffer */
656 return wxRealPath(buf
);
659 /* Contract Paths to be build upon an environment variable
662 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
664 The call wxExpandPath can convert these back!
667 wxContractPath (const wxString
& filename
,
668 const wxString
& WXUNUSED_IN_WINCE(envname
),
669 const wxString
& user
)
671 static wxChar dest
[_MAXPATHLEN
];
673 if (filename
.empty())
674 return (wxChar
*) NULL
;
676 wxStrcpy (dest
, WXSTRINGCAST filename
);
678 wxUnix2DosFilename(dest
);
681 // Handle environment
685 if (!envname
.empty() && (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
686 (tcp
= wxStrstr (dest
, val
)) != NULL
)
688 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
691 wxStrcpy (tcp
, WXSTRINGCAST envname
);
692 wxStrcat (tcp
, wxT("}"));
693 wxStrcat (tcp
, wxFileFunctionsBuffer
);
697 // Handle User's home (ignore root homes!)
698 val
= wxGetUserHome (user
);
702 const size_t len
= wxStrlen(val
);
706 if (wxStrncmp(dest
, val
, len
) == 0)
708 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
710 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
711 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
712 wxStrcpy (dest
, wxFileFunctionsBuffer
);
718 // Return just the filename, not the path (basename)
719 wxChar
*wxFileNameFromPath (wxChar
*path
)
722 wxString n
= wxFileNameFromPath(p
);
724 return path
+ p
.length() - n
.length();
727 wxString
wxFileNameFromPath (const wxString
& path
)
730 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
732 wxString fullname
= name
;
735 fullname
<< wxFILE_SEP_EXT
<< ext
;
741 // Return just the directory, or NULL if no directory
743 wxPathOnly (wxChar
*path
)
747 static wxChar buf
[_MAXPATHLEN
];
750 wxStrcpy (buf
, path
);
752 int l
= wxStrlen(path
);
755 // Search backward for a backward or forward slash
758 #if defined(__WXMAC__) && !defined(__DARWIN__)
759 // Classic or Carbon CodeWarrior like
760 // Carbon with Apple DevTools is Unix like
761 if (path
[i
] == wxT(':') )
767 // Unix like or Windows
768 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
775 if (path
[i
] == wxT(']'))
784 #if defined(__WXMSW__) || defined(__OS2__)
785 // Try Drive specifier
786 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
788 // A:junk --> A:. (since A:.\junk Not A:\junk)
795 return (wxChar
*) NULL
;
798 // Return just the directory, or NULL if no directory
799 wxString
wxPathOnly (const wxString
& path
)
803 wxChar buf
[_MAXPATHLEN
];
806 wxStrcpy (buf
, WXSTRINGCAST path
);
808 int l
= path
.length();
811 // Search backward for a backward or forward slash
814 #if defined(__WXMAC__) && !defined(__DARWIN__)
815 // Classic or Carbon CodeWarrior like
816 // Carbon with Apple DevTools is Unix like
817 if (path
[i
] == wxT(':') )
820 return wxString(buf
);
823 // Unix like or Windows
824 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
826 // Don't return an empty string
830 return wxString(buf
);
834 if (path
[i
] == wxT(']'))
837 return wxString(buf
);
843 #if defined(__WXMSW__) || defined(__OS2__)
844 // Try Drive specifier
845 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
847 // A:junk --> A:. (since A:.\junk Not A:\junk)
850 return wxString(buf
);
854 return wxEmptyString
;
857 // Utility for converting delimiters in DOS filenames to UNIX style
858 // and back again - or we get nasty problems with delimiters.
859 // Also, convert to lower case, since case is significant in UNIX.
861 #if defined(__WXMAC__)
863 #if TARGET_API_MAC_OSX
864 #define kDefaultPathStyle kCFURLPOSIXPathStyle
866 #define kDefaultPathStyle kCFURLHFSPathStyle
869 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
872 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
873 if ( additionalPathComponent
)
875 CFURLRef parentURLRef
= fullURLRef
;
876 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
877 additionalPathComponent
,false);
878 CFRelease( parentURLRef
) ;
880 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
881 CFRelease( fullURLRef
) ;
882 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
885 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
887 OSStatus err
= noErr
;
888 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
891 if ( CFURLGetFSRef(url
, fsRef
) == false )
902 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
904 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
907 return wxMacCFStringHolder(cfname
).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() != wxWIN95
)
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
);
1637 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1640 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1643 return mtime
.GetTicks();
1647 // Parses the filterStr, returning the number of filters.
1648 // Returns 0 if none or if there's a problem.
1649 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1651 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1652 wxArrayString
& descriptions
,
1653 wxArrayString
& filters
)
1655 descriptions
.Clear();
1658 wxString
str(filterStr
);
1660 wxString description
, filter
;
1662 while( pos
!= wxNOT_FOUND
)
1664 pos
= str
.Find(wxT('|'));
1665 if ( pos
== wxNOT_FOUND
)
1667 // if there are no '|'s at all in the string just take the entire
1668 // string as filter and make description empty for later autocompletion
1669 if ( filters
.IsEmpty() )
1671 descriptions
.Add(wxEmptyString
);
1672 filters
.Add(filterStr
);
1676 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1682 description
= str
.Left(pos
);
1683 str
= str
.Mid(pos
+ 1);
1684 pos
= str
.Find(wxT('|'));
1685 if ( pos
== wxNOT_FOUND
)
1691 filter
= str
.Left(pos
);
1692 str
= str
.Mid(pos
+ 1);
1695 descriptions
.Add(description
);
1696 filters
.Add(filter
);
1699 #if defined(__WXMOTIF__)
1700 // split it so there is one wildcard per entry
1701 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1703 pos
= filters
[i
].Find(wxT(';'));
1704 if (pos
!= wxNOT_FOUND
)
1706 // first split only filters
1707 descriptions
.Insert(descriptions
[i
],i
+1);
1708 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1709 filters
[i
]=filters
[i
].Left(pos
);
1711 // autoreplace new filter in description with pattern:
1712 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1713 // cause split into:
1714 // C/C++ Files(*.cpp)|*.cpp
1715 // C/C++ Files(*.c;*.h)|*.c;*.h
1716 // and next iteration cause another split into:
1717 // C/C++ Files(*.cpp)|*.cpp
1718 // C/C++ Files(*.c)|*.c
1719 // C/C++ Files(*.h)|*.h
1720 for ( size_t k
=i
;k
<i
+2;k
++ )
1722 pos
= descriptions
[k
].Find(filters
[k
]);
1723 if (pos
!= wxNOT_FOUND
)
1725 wxString before
= descriptions
[k
].Left(pos
);
1726 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1727 pos
= before
.Find(_T('('),true);
1728 if (pos
>before
.Find(_T(')'),true))
1730 before
= before
.Left(pos
+1);
1731 before
<< filters
[k
];
1732 pos
= after
.Find(_T(')'));
1733 int pos1
= after
.Find(_T('('));
1734 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1736 before
<< after
.Mid(pos
);
1737 descriptions
[k
] = before
;
1747 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1749 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1751 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1755 return filters
.GetCount();
1759 //------------------------------------------------------------------------
1760 // wild character routines
1761 //------------------------------------------------------------------------
1763 bool wxIsWild( const wxString
& pattern
)
1765 wxString tmp
= pattern
;
1766 wxChar
*pat
= WXSTRINGCAST(tmp
);
1771 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1782 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1784 * The match procedure is public domain code (from ircII's reg.c)
1785 * but modified to suit our tastes (RN: No "%" syntax I guess)
1788 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1792 /* Match if both are empty. */
1796 const wxChar
*m
= pat
.c_str(),
1804 if (dot_special
&& (*n
== wxT('.')))
1806 /* Never match so that hidden Unix files
1807 * are never found. */
1820 else if (*m
== wxT('?'))
1828 if (*m
== wxT('\\'))
1831 /* Quoting "nothing" is a bad thing */
1838 * If we are out of both strings or we just
1839 * saw a wildcard, then we can say we have a
1850 * We could check for *n == NULL at this point, but
1851 * since it's more common to have a character there,
1852 * check to see if they match first (m and n) and
1853 * then if they don't match, THEN we can check for
1869 * If there are no more characters in the
1870 * string, but we still need to find another
1871 * character (*m != NULL), then it will be
1872 * impossible to match it
1890 // Return the type of an open file
1892 // Some file types on some platforms seem seekable but in fact are not.
1893 // The main use of this function is to allow such cases to be detected
1894 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1896 // This is important for the archive streams, which benefit greatly from
1897 // being able to seek on a stream, but which will produce corrupt archives
1898 // if they unknowingly seek on a non-seekable stream.
1900 // wxFILE_KIND_DISK is a good catch all return value, since other values
1901 // disable features of the archive streams. Some other value must be returned
1902 // for a file type that appears seekable but isn't.
1905 // * Pipes on Windows
1906 // * Files on VMS with a record format other than StreamLF
1908 wxFileKind
wxGetFileKind(int fd
)
1910 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1911 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1913 case FILE_TYPE_CHAR
:
1914 return wxFILE_KIND_TERMINAL
;
1915 case FILE_TYPE_DISK
:
1916 return wxFILE_KIND_DISK
;
1917 case FILE_TYPE_PIPE
:
1918 return wxFILE_KIND_PIPE
;
1921 return wxFILE_KIND_UNKNOWN
;
1923 #elif defined(__UNIX__)
1925 return wxFILE_KIND_TERMINAL
;
1930 if (S_ISFIFO(st
.st_mode
))
1931 return wxFILE_KIND_PIPE
;
1932 if (!S_ISREG(st
.st_mode
))
1933 return wxFILE_KIND_UNKNOWN
;
1935 #if defined(__VMS__)
1936 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1937 return wxFILE_KIND_UNKNOWN
;
1940 return wxFILE_KIND_DISK
;
1943 #define wxFILEKIND_STUB
1945 return wxFILE_KIND_DISK
;
1949 wxFileKind
wxGetFileKind(FILE *fp
)
1951 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1952 // Should be fixed in version 1.4.
1953 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1955 return wxFILE_KIND_DISK
;
1957 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1962 #pragma warning(default:4706) // assignment within conditional expression