1 /////////////////////////////////////////////////////////////////////////////
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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "filefn.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
34 #include "wx/file.h" // This does include filefn.h
35 #include "wx/filename.h"
38 // there are just too many of those...
40 #pragma warning(disable:4706) // assignment within conditional expression
47 #if !defined(__WATCOMC__)
48 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
53 #if defined(__WXMAC__)
54 #include "wx/mac/private.h" // includes mac headers
60 #include "wx/msw/private.h"
61 #include "wx/msw/mslu.h"
63 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
65 // note that it must be included after <windows.h>
68 #include <sys/cygwin.h>
70 #endif // __GNUWIN32__
72 // io.h is needed for _get_osfhandle()
73 // Already included by filefn.h for many Windows compilers
74 #if defined __MWERKS__ || defined __CYGWIN__
83 // TODO: Borland probably has _wgetcwd as well?
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
93 #define _MAXPATHLEN 1024
97 # include "MoreFilesX.h"
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
104 // MT-FIXME: get rid of this horror and all code using it
105 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
107 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
109 // VisualAge C++ V4.0 cannot have any external linkage const decs
110 // in headers included by more than one primary source
112 const int wxInvalidOffset
= -1;
115 // ----------------------------------------------------------------------------
117 // ----------------------------------------------------------------------------
119 // we need to translate Mac filenames before passing them to OS functions
120 #define OS_FILENAME(s) (s.fn_str())
122 // ============================================================================
124 // ============================================================================
126 #ifdef wxNEED_WX_UNISTD_H
128 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
130 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
133 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
135 return access( wxConvFile
.cWX2MB( pathname
), mode
);
138 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
140 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
144 // wxNEED_WX_UNISTD_H
146 // ----------------------------------------------------------------------------
148 // ----------------------------------------------------------------------------
150 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
152 static inline wxChar
* MYcopystring(const wxString
& s
)
154 wxChar
* copy
= new wxChar
[s
.length() + 1];
155 return wxStrcpy(copy
, s
.c_str());
158 static inline wxChar
* MYcopystring(const wxChar
* s
)
160 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
161 return wxStrcpy(copy
, s
);
164 void wxPathList::Add (const wxString
& path
)
166 wxStringList::Add (WXSTRINGCAST path
);
169 // Add paths e.g. from the PATH environment variable
170 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
172 // No environment variables on WinCE
174 static const wxChar PATH_TOKS
[] =
175 #if defined(__WINDOWS__) || defined(__OS2__)
177 The space has been removed from the tokenizers, otherwise a
178 path such as "C:\Program Files" would be split into 2 paths:
179 "C:\Program" and "Files"
181 // wxT(" ;"); // Don't separate with colon in DOS (used for drive)
182 wxT(";"); // Don't separate with colon in DOS (used for drive)
188 if (wxGetEnv (WXSTRINGCAST envVariable
, &val
))
190 wxChar
*s
= MYcopystring (val
);
191 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
198 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
206 // suppress warning about unused variable save_ptr when wxStrtok() is a
207 // macro which throws away its third argument
212 #endif // !__WXWINCE__
215 // Given a full filename (with path), ensure that that file can
216 // be accessed again USING FILENAME ONLY by adding the path
217 // to the list if not already there.
218 void wxPathList::EnsureFileAccessible (const wxString
& path
)
220 wxString
path_only(wxPathOnly(path
));
221 if ( !path_only
.empty() )
223 if ( !Member(path_only
) )
228 bool wxPathList::Member (const wxString
& path
)
230 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
232 wxString
path2( node
->GetData() );
234 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined(__WXMAC__)
236 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
238 // Case sensitive File System
239 path
.CompareTo (path2
) == 0
247 wxString
wxPathList::FindValidPath (const wxString
& file
)
249 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
250 return wxString(wxFileFunctionsBuffer
);
252 wxChar buf
[_MAXPATHLEN
];
253 wxStrcpy(buf
, wxFileFunctionsBuffer
);
255 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
257 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
259 const wxChar
*path
= node
->GetData();
260 wxStrcpy (wxFileFunctionsBuffer
, path
);
261 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
262 if (ch
!= wxT('\\') && ch
!= wxT('/'))
263 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
264 wxStrcat (wxFileFunctionsBuffer
, filename
);
266 wxUnix2DosFilename (wxFileFunctionsBuffer
);
268 if (wxFileExists (wxFileFunctionsBuffer
))
270 return wxString(wxFileFunctionsBuffer
); // Found!
274 return wxEmptyString
; // Not found
277 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
279 wxString f
= FindValidPath(file
);
280 if ( f
.empty() || wxIsAbsolutePath(f
) )
284 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
286 if ( !wxEndsWithPathSeparator(buf
) )
288 buf
+= wxFILE_SEP_PATH
;
296 wxFileExists (const wxString
& filename
)
298 #if defined(__WXPALMOS__)
300 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
301 // we must use GetFileAttributes() instead of the ANSI C functions because
302 // it can cope with network (UNC) paths unlike them
303 DWORD ret
= ::GetFileAttributes(filename
);
305 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
308 #ifndef wxNEED_WX_UNISTD_H
309 return wxStat( filename
.fn_str() , &st
) == 0 && (st
.st_mode
& S_IFREG
);
311 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
313 #endif // __WIN32__/!__WIN32__
317 wxIsAbsolutePath (const wxString
& filename
)
319 if (!filename
.empty())
321 #if defined(__WXMAC__) && !defined(__DARWIN__)
322 // Classic or Carbon CodeWarrior like
323 // Carbon with Apple DevTools is Unix like
325 // This seems wrong to me, but there is no fix. since
326 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
327 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
328 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
331 // Unix like or Windows
332 if (filename
[0] == wxT('/'))
336 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
339 #if defined(__WINDOWS__) || defined(__OS2__)
341 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
349 * Strip off any extension (dot something) from end of file,
350 * IF one exists. Inserts zero into buffer.
354 void wxStripExtension(wxChar
*buffer
)
356 int len
= wxStrlen(buffer
);
360 if (buffer
[i
] == wxT('.'))
369 void wxStripExtension(wxString
& buffer
)
371 //RN: Be careful about the handling the case where
372 //buffer.Length() == 0
373 for(size_t i
= buffer
.Length() - 1; i
!= wxString::npos
; --i
)
375 if (buffer
.GetChar(i
) == wxT('.'))
377 buffer
= buffer
.Left(i
);
383 // Destructive removal of /./ and /../ stuff
384 wxChar
*wxRealPath (wxChar
*path
)
387 static const wxChar SEP
= wxT('\\');
388 wxUnix2DosFilename(path
);
390 static const wxChar SEP
= wxT('/');
392 if (path
[0] && path
[1]) {
393 /* MATTHEW: special case "/./x" */
395 if (path
[2] == SEP
&& path
[1] == wxT('.'))
403 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
406 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
411 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
412 && (q
- 1 <= path
|| q
[-1] != SEP
))
415 if (path
[0] == wxT('\0'))
420 #if defined(__WXMSW__) || defined(__OS2__)
421 /* Check that path[2] is NULL! */
422 else if (path
[1] == wxT(':') && !path
[2])
431 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
440 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
442 if (filename
.empty())
443 return (wxChar
*) NULL
;
445 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
446 wxChar buf
[_MAXPATHLEN
];
448 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
449 wxChar ch
= buf
[wxStrlen(buf
) - 1];
451 if (ch
!= wxT('\\') && ch
!= wxT('/'))
452 wxStrcat(buf
, wxT("\\"));
455 wxStrcat(buf
, wxT("/"));
457 wxStrcat(buf
, wxFileFunctionsBuffer
);
458 return MYcopystring( wxRealPath(buf
) );
460 return MYcopystring( wxFileFunctionsBuffer
);
466 ~user/ => user's home dir
467 If the environment variable a = "foo" and b = "bar" then:
484 /* input name in name, pathname output to buf. */
486 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
488 register wxChar
*d
, *s
, *nm
;
489 wxChar lnm
[_MAXPATHLEN
];
492 // Some compilers don't like this line.
493 // const wxChar trimchars[] = wxT("\n \t");
496 trimchars
[0] = wxT('\n');
497 trimchars
[1] = wxT(' ');
498 trimchars
[2] = wxT('\t');
502 const wxChar SEP
= wxT('\\');
504 const wxChar SEP
= wxT('/');
507 if (name
== NULL
|| *name
== wxT('\0'))
509 nm
= MYcopystring(name
); // Make a scratch copy
512 /* Skip leading whitespace and cr */
513 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
515 /* And strip off trailing whitespace and cr */
516 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
517 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
525 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
528 /* Expand inline environment variables */
546 while ((*d
++ = *s
) != 0) {
548 if (*s
== wxT('\\')) {
549 if ((*(d
- 1) = *++s
)!=0) {
557 // No env variables on WinCE
560 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
562 if (*s
++ == wxT('$'))
565 register wxChar
*start
= d
;
566 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
567 register wxChar
*value
;
568 while ((*d
++ = *s
) != 0)
569 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
574 value
= wxGetenv(braces
? start
+ 1 : start
);
576 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
590 /* Expand ~ and ~user */
592 if (nm
[0] == wxT('~') && !q
)
595 if (nm
[1] == SEP
|| nm
[1] == 0)
597 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
598 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
603 { /* ~user/filename */
604 register wxChar
*nnm
;
605 register wxChar
*home
;
606 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
610 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
611 was_sep
= (*s
== SEP
);
612 nnm
= *s
? s
+ 1 : s
;
614 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
615 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
)
617 if (was_sep
) /* replace only if it was there: */
630 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
632 while (wxT('\0') != (*d
++ = *s
++))
635 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
639 while ((*d
++ = *s
++) != 0)
643 delete[] nm_tmp
; // clean up alloc
644 /* Now clean up the buffer */
645 return wxRealPath(buf
);
648 /* Contract Paths to be build upon an environment variable
651 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
653 The call wxExpandPath can convert these back!
656 wxContractPath (const wxString
& filename
,
657 const wxString
& WXUNUSED_IN_WINCE(envname
),
658 const wxString
& user
)
660 static wxChar dest
[_MAXPATHLEN
];
662 if (filename
.empty())
663 return (wxChar
*) NULL
;
665 wxStrcpy (dest
, WXSTRINGCAST filename
);
667 wxUnix2DosFilename(dest
);
670 // Handle environment
674 if (!envname
.empty() && (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
675 (tcp
= wxStrstr (dest
, val
)) != NULL
)
677 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
680 wxStrcpy (tcp
, WXSTRINGCAST envname
);
681 wxStrcat (tcp
, wxT("}"));
682 wxStrcat (tcp
, wxFileFunctionsBuffer
);
686 // Handle User's home (ignore root homes!)
687 val
= wxGetUserHome (user
);
691 const size_t len
= wxStrlen(val
);
695 if (wxStrncmp(dest
, val
, len
) == 0)
697 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
699 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
700 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
701 wxStrcpy (dest
, wxFileFunctionsBuffer
);
707 // Return just the filename, not the path (basename)
708 wxChar
*wxFileNameFromPath (wxChar
*path
)
711 wxString n
= wxFileNameFromPath(p
);
713 return path
+ p
.length() - n
.length();
716 wxString
wxFileNameFromPath (const wxString
& path
)
719 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
721 wxString fullname
= name
;
724 fullname
<< wxFILE_SEP_EXT
<< ext
;
730 // Return just the directory, or NULL if no directory
732 wxPathOnly (wxChar
*path
)
736 static wxChar buf
[_MAXPATHLEN
];
739 wxStrcpy (buf
, path
);
741 int l
= wxStrlen(path
);
744 // Search backward for a backward or forward slash
747 #if defined(__WXMAC__) && !defined(__DARWIN__)
748 // Classic or Carbon CodeWarrior like
749 // Carbon with Apple DevTools is Unix like
750 if (path
[i
] == wxT(':') )
756 // Unix like or Windows
757 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
764 if (path
[i
] == wxT(']'))
773 #if defined(__WXMSW__) || defined(__OS2__)
774 // Try Drive specifier
775 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
777 // A:junk --> A:. (since A:.\junk Not A:\junk)
784 return (wxChar
*) NULL
;
787 // Return just the directory, or NULL if no directory
788 wxString
wxPathOnly (const wxString
& path
)
792 wxChar buf
[_MAXPATHLEN
];
795 wxStrcpy (buf
, WXSTRINGCAST path
);
797 int l
= path
.Length();
800 // Search backward for a backward or forward slash
803 #if defined(__WXMAC__) && !defined(__DARWIN__)
804 // Classic or Carbon CodeWarrior like
805 // Carbon with Apple DevTools is Unix like
806 if (path
[i
] == wxT(':') )
809 return wxString(buf
);
812 // Unix like or Windows
813 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
815 // Don't return an empty string
819 return wxString(buf
);
823 if (path
[i
] == wxT(']'))
826 return wxString(buf
);
832 #if defined(__WXMSW__) || defined(__OS2__)
833 // Try Drive specifier
834 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
836 // A:junk --> A:. (since A:.\junk Not A:\junk)
839 return wxString(buf
);
843 return wxEmptyString
;
846 // Utility for converting delimiters in DOS filenames to UNIX style
847 // and back again - or we get nasty problems with delimiters.
848 // Also, convert to lower case, since case is significant in UNIX.
850 #if defined(__WXMAC__)
852 #if TARGET_API_MAC_OSX
853 #define kDefaultPathStyle kCFURLPOSIXPathStyle
855 #define kDefaultPathStyle kCFURLHFSPathStyle
858 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
861 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
862 if ( additionalPathComponent
)
864 CFURLRef parentURLRef
= fullURLRef
;
865 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
866 additionalPathComponent
,false);
867 CFRelease( parentURLRef
) ;
869 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
870 CFRelease( fullURLRef
) ;
871 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
874 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
876 OSStatus err
= noErr
;
877 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
880 if ( CFURLGetFSRef(url
, fsRef
) == false )
891 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
893 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
896 return wxMacCFStringHolder(cfname
).AsString() ;
899 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
902 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
904 return wxMacFSRefToPath( &fsRef
) ;
906 return wxEmptyString
;
909 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
911 OSStatus err
= noErr
;
913 wxMacPathToFSRef( path
, &fsRef
) ;
914 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
920 wxDos2UnixFilename (wxChar
*s
)
929 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
936 #if defined(__WXMSW__) || defined(__OS2__)
937 wxUnix2DosFilename (wxChar
*s
)
939 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
942 // Yes, I really mean this to happen under DOS only! JACS
943 #if defined(__WXMSW__) || defined(__OS2__)
954 // Concatenate two files to form third
956 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
960 wxFile
in1(file1
), in2(file2
);
961 wxTempFile
out(file3
);
963 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
967 unsigned char buf
[1024];
969 for( int i
=0; i
<2; i
++)
971 wxFile
*in
= i
==0 ? &in1
: &in2
;
973 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
975 if ( !out
.Write(buf
,ofs
) )
977 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
994 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
996 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
997 // CopyFile() copies file attributes and modification time too, so use it
998 // instead of our code if available
1000 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1001 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1003 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1004 file1
.c_str(), file2
.c_str());
1008 #elif defined(__OS2__)
1009 if ( ::DosCopy((PSZ
)file1
.c_str(), (PSZ
)file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1011 #elif defined(__PALMOS__)
1012 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1014 #elif wxUSE_FILE // !Win32
1017 // get permissions of file1
1018 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1020 // the file probably doesn't exist or we haven't the rights to read
1022 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1027 // open file1 for reading
1028 wxFile
fileIn(file1
, wxFile::read
);
1029 if ( !fileIn
.IsOpened() )
1032 // remove file2, if it exists. This is needed for creating
1033 // file2 with the correct permissions in the next step
1034 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1036 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1041 // reset the umask as we want to create the file with exactly the same
1042 // permissions as the original one
1045 // create file2 with the same permissions than file1 and open it for
1049 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1052 // copy contents of file1 to file2
1057 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1058 if ( fileIn
.Error() )
1065 if ( fileOut
.Write(buf
, count
) < count
)
1069 // we can expect fileIn to be closed successfully, but we should ensure
1070 // that fileOut was closed as some write errors (disk full) might not be
1071 // detected before doing this
1072 if ( !fileIn
.Close() || !fileOut
.Close() )
1075 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1076 // no chmod in VA. Should be some permission API for HPFS386 partitions
1078 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1080 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1084 #endif // OS/2 || Mac
1086 #else // !Win32 && ! wxUSE_FILE
1088 // impossible to simulate with wxWidgets API
1091 wxUnusedVar(overwrite
);
1094 #endif // __WXMSW__ && __WIN32__
1100 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1102 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1103 // Normal system call
1104 if ( wxRename (file1
, file2
) == 0 )
1109 if (wxCopyFile(file1
, file2
)) {
1110 wxRemoveFile(file1
);
1117 bool wxRemoveFile(const wxString
& file
)
1119 #if defined(__VISUALC__) \
1120 || defined(__BORLANDC__) \
1121 || defined(__WATCOMC__) \
1122 || defined(__DMC__) \
1123 || defined(__GNUWIN32__) \
1124 || (defined(__MWERKS__) && defined(__MSL__))
1125 int res
= wxRemove(file
);
1126 #elif defined(__WXMAC__)
1127 int res
= unlink(wxFNCONV(file
));
1128 #elif defined(__WXPALMOS__)
1130 // TODO with VFSFileDelete()
1132 int res
= unlink(OS_FILENAME(file
));
1138 bool wxMkdir(const wxString
& dir
, int perm
)
1140 #if defined(__WXPALMOS__)
1142 #elif defined(__WXMAC__) && !defined(__UNIX__)
1143 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1145 const wxChar
*dirname
= dir
.c_str();
1147 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1148 // for the GNU compiler
1149 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1152 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1154 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1156 #elif defined(__OS2__)
1158 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1159 #elif defined(__DOS__)
1160 #if defined(__WATCOMC__)
1162 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1163 #elif defined(__DJGPP__)
1164 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1166 #error "Unsupported DOS compiler!"
1168 #else // !MSW, !DOS and !OS/2 VAC++
1171 if ( !CreateDirectory(dirname
, NULL
) )
1173 if ( wxMkDir(dir
.fn_str()) != 0 )
1177 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1186 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1188 #if defined(__VMS__)
1189 return false; //to be changed since rmdir exists in VMS7.x
1190 #elif defined(__OS2__)
1191 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1192 #elif defined(__WXWINCE__)
1193 return (CreateDirectory(dir
, NULL
) != 0);
1194 #elif defined(__WXPALMOS__)
1195 // TODO with VFSFileRename()
1198 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1202 // does the path exists? (may have or not '/' or '\\' at the end)
1203 bool wxDirExists(const wxChar
*pszPathName
)
1205 wxString
strPath(pszPathName
);
1207 #if defined(__WINDOWS__) || defined(__OS2__)
1208 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1209 // so remove all trailing backslashes from the path - but don't do this for
1210 // the pathes "d:\" (which are different from "d:") nor for just "\"
1211 while ( wxEndsWithPathSeparator(strPath
) )
1213 size_t len
= strPath
.length();
1214 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1217 strPath
.Truncate(len
- 1);
1219 #endif // __WINDOWS__
1222 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1223 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1227 #if defined(__WXPALMOS__)
1229 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1230 // stat() can't cope with network paths
1231 DWORD ret
= ::GetFileAttributes(strPath
);
1233 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1234 #elif defined(__OS2__)
1235 return (bool)(::DosSetCurrentDir((PSZ
)(WXSTRINGCAST strPath
)));
1239 #ifndef __VISAGECPP__
1240 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1242 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1243 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1246 #endif // __WIN32__/!__WIN32__
1249 // Get a temporary filename, opening and closing the file.
1250 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1253 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1254 if ( filename
.empty() )
1258 wxStrcpy(buf
, filename
);
1260 buf
= MYcopystring(filename
);
1264 wxUnusedVar(prefix
);
1266 // wxFileName::CreateTempFileName needs wxFile class enabled
1271 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1273 buf
= wxGetTempFileName(prefix
);
1275 return !buf
.empty();
1278 // Get first file name matching given wild card.
1280 static wxDir
*gs_dir
= NULL
;
1281 static wxString gs_dirPath
;
1283 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1285 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1286 if ( gs_dirPath
.empty() )
1287 gs_dirPath
= wxT(".");
1288 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1289 gs_dirPath
<< wxFILE_SEP_PATH
;
1293 gs_dir
= new wxDir(gs_dirPath
);
1295 if ( !gs_dir
->IsOpened() )
1297 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1298 return wxEmptyString
;
1304 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1305 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1306 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1310 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1311 if ( result
.empty() )
1317 return gs_dirPath
+ result
;
1320 wxString
wxFindNextFile()
1322 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1325 gs_dir
->GetNext(&result
);
1327 if ( result
.empty() )
1333 return gs_dirPath
+ result
;
1337 // Get current working directory.
1338 // If buf is NULL, allocates space using new, else
1340 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1342 #if defined(__WXPALMOS__)
1345 #elif defined(__WXWINCE__)
1353 buf
= new wxChar
[sz
+ 1];
1356 bool ok
wxDUMMY_INITIALIZE(false);
1358 // for the compilers which have Unicode version of _getcwd(), call it
1359 // directly, for the others call the ANSI version and do the translation
1362 #else // wxUSE_UNICODE
1363 bool needsANSI
= true;
1365 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1366 // This is not legal code as the compiler
1367 // is allowed destroy the wxCharBuffer.
1368 // wxCharBuffer c_buffer(sz);
1369 // char *cbuf = (char*)(const char*)c_buffer;
1370 char cbuf
[_MAXPATHLEN
];
1374 #if wxUSE_UNICODE_MSLU
1375 if ( wxGetOsVersion() != wxWIN95
)
1377 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1380 ok
= _wgetcwd(buf
, sz
) != NULL
;
1386 #endif // wxUSE_UNICODE
1388 #if defined(_MSC_VER) || defined(__MINGW32__)
1389 ok
= _getcwd(cbuf
, sz
) != NULL
;
1390 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1392 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1394 wxString
res( lbuf
, *wxConvCurrent
) ;
1395 wxStrcpy( buf
, res
) ;
1400 #elif defined(__OS2__)
1402 ULONG ulDriveNum
= 0;
1403 ULONG ulDriveMap
= 0;
1404 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1409 rc
= ::DosQueryCurrentDir( 0 // current drive
1413 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1418 #else // !Win32/VC++ !Mac !OS2
1419 ok
= getcwd(cbuf
, sz
) != NULL
;
1422 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1423 // finally convert the result to Unicode if needed
1424 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1425 #endif // wxUSE_UNICODE
1430 wxLogSysError(_("Failed to get the working directory"));
1432 // VZ: the old code used to return "." on error which didn't make any
1433 // sense at all to me - empty string is a better error indicator
1434 // (NULL might be even better but I'm afraid this could lead to
1435 // problems with the old code assuming the return is never NULL)
1438 else // ok, but we might need to massage the path into the right format
1441 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1442 // with / deliminers. We don't like that.
1443 for (wxChar
*ch
= buf
; *ch
; ch
++)
1445 if (*ch
== wxT('/'))
1450 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1451 // he needs Unix as opposed to Win32 pathnames
1452 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1453 // another example of DOS/Unix mix (Cygwin)
1454 wxString pathUnix
= buf
;
1455 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1456 #endif // __CYGWIN__
1471 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1472 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1473 wxString
str( buffer
);
1479 bool wxSetWorkingDirectory(const wxString
& d
)
1481 #if defined(__OS2__)
1482 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1483 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1484 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1485 #elif defined(__WINDOWS__)
1489 // No equivalent in WinCE
1493 return (bool)(SetCurrentDirectory(d
) != 0);
1496 // Must change drive, too.
1497 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1500 wxChar firstChar
= d
[0];
1504 firstChar
= firstChar
- 32;
1506 // To a drive number
1507 unsigned int driveNo
= firstChar
- 64;
1510 unsigned int noDrives
;
1511 _dos_setdrive(driveNo
, &noDrives
);
1514 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1522 // Get the OS directory if appropriate (such as the Windows directory).
1523 // On non-Windows platform, probably just return the empty string.
1524 wxString
wxGetOSDirectory()
1527 return wxString(wxT("\\Windows"));
1528 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1530 GetWindowsDirectory(buf
, 256);
1531 return wxString(buf
);
1532 #elif defined(__WXMAC__)
1533 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1535 return wxEmptyString
;
1539 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1541 size_t len
= wxStrlen(pszFileName
);
1543 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1546 // find a file in a list of directories, returns false if not found
1547 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1549 // we assume that it's not empty
1550 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1551 _T("empty file name in wxFindFileInPath"));
1553 // skip path separator in the beginning of the file name if present
1554 if ( wxIsPathSeparator(*pszFile
) )
1557 // copy the path (strtok will modify it)
1558 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1559 wxStrcpy(szPath
, pszPath
);
1562 wxChar
*pc
, *save_ptr
;
1563 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1565 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1567 // search for the file in this directory
1569 if ( !wxEndsWithPathSeparator(pc
) )
1570 strFile
+= wxFILE_SEP_PATH
;
1573 if ( wxFileExists(strFile
) ) {
1579 // suppress warning about unused variable save_ptr when wxStrtok() is a
1580 // macro which throws away its third argument
1585 return pc
!= NULL
; // if true => we breaked from the loop
1588 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1593 // it can be empty, but it shouldn't be NULL
1594 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1596 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1599 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1601 #if defined(__WXPALMOS__)
1603 #elif defined(__WXWINCE__)
1604 FILETIME ftLastWrite
;
1605 AutoHANDLE
hFile(::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
,
1606 NULL
, 0, FILE_ATTRIBUTE_NORMAL
, 0));
1608 if ( !hFile
.IsOk() )
1611 if ( !::GetFileTime(hFile
, NULL
, NULL
, &ftLastWrite
) )
1614 // sure we want to translate to local time here?
1616 if ( !::FileTimeToLocalFileTime(&ftLastWrite
, &ftLocal
) )
1618 wxLogLastError(_T("FileTimeToLocalFileTime"));
1621 // FILETIME is a counted in 100-ns since 1601-01-01, convert it to
1622 // number of seconds since 1970-01-01
1624 uli
.LowPart
= ftLocal
.dwLowDateTime
;
1625 uli
.HighPart
= ftLocal
.dwHighDateTime
;
1627 ULONGLONG ull
= uli
.QuadPart
;
1628 ull
/= wxULL(10000000); // number of 100ns intervals in 1s
1629 ull
-= wxULL(11644473600); // 1970-01-01 - 1601-01-01 in seconds
1631 return wx_static_cast(time_t, ull
);
1634 if ( wxStat( filename
, &buf
) != 0 )
1637 return buf
.st_mtime
;
1642 // Parses the filterStr, returning the number of filters.
1643 // Returns 0 if none or if there's a problem.
1644 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1646 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1647 wxArrayString
& descriptions
,
1648 wxArrayString
& filters
)
1650 descriptions
.Clear();
1653 wxString
str(filterStr
);
1655 wxString description
, filter
;
1657 while( pos
!= wxNOT_FOUND
)
1659 pos
= str
.Find(wxT('|'));
1660 if ( pos
== wxNOT_FOUND
)
1662 // if there are no '|'s at all in the string just take the entire
1663 // string as filter and make description empty for later autocompletion
1664 if ( filters
.IsEmpty() )
1666 descriptions
.Add(wxEmptyString
);
1667 filters
.Add(filterStr
);
1671 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1677 description
= str
.Left(pos
);
1678 str
= str
.Mid(pos
+ 1);
1679 pos
= str
.Find(wxT('|'));
1680 if ( pos
== wxNOT_FOUND
)
1686 filter
= str
.Left(pos
);
1687 str
= str
.Mid(pos
+ 1);
1690 descriptions
.Add(description
);
1691 filters
.Add(filter
);
1694 #if defined(__WXMOTIF__)
1695 // split it so there is one wildcard per entry
1696 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1698 pos
= filters
[i
].Find(wxT(';'));
1699 if (pos
!= wxNOT_FOUND
)
1701 // first split only filters
1702 descriptions
.Insert(descriptions
[i
],i
+1);
1703 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1704 filters
[i
]=filters
[i
].Left(pos
);
1706 // autoreplace new filter in description with pattern:
1707 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1708 // cause split into:
1709 // C/C++ Files(*.cpp)|*.cpp
1710 // C/C++ Files(*.c;*.h)|*.c;*.h
1711 // and next iteration cause another split into:
1712 // C/C++ Files(*.cpp)|*.cpp
1713 // C/C++ Files(*.c)|*.c
1714 // C/C++ Files(*.h)|*.h
1715 for ( size_t k
=i
;k
<i
+2;k
++ )
1717 pos
= descriptions
[k
].Find(filters
[k
]);
1718 if (pos
!= wxNOT_FOUND
)
1720 wxString before
= descriptions
[k
].Left(pos
);
1721 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1722 pos
= before
.Find(_T('('),true);
1723 if (pos
>before
.Find(_T(')'),true))
1725 before
= before
.Left(pos
+1);
1726 before
<< filters
[k
];
1727 pos
= after
.Find(_T(')'));
1728 int pos1
= after
.Find(_T('('));
1729 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1731 before
<< after
.Mid(pos
);
1732 descriptions
[k
] = before
;
1742 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1744 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1746 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1750 return filters
.GetCount();
1754 //------------------------------------------------------------------------
1755 // wild character routines
1756 //------------------------------------------------------------------------
1758 bool wxIsWild( const wxString
& pattern
)
1760 wxString tmp
= pattern
;
1761 wxChar
*pat
= WXSTRINGCAST(tmp
);
1766 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1777 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1779 * The match procedure is public domain code (from ircII's reg.c)
1782 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1786 /* Match if both are empty. */
1790 const wxChar
*m
= pat
.c_str(),
1801 if (dot_special
&& (*n
== wxT('.')))
1803 /* Never match so that hidden Unix files
1804 * 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
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
1879 if (*np
== wxT(' '))
1903 // Return the type of an open file
1905 // Some file types on some platforms seem seekable but in fact are not.
1906 // The main use of this function is to allow such cases to be detected
1907 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1909 // This is important for the archive streams, which benefit greatly from
1910 // being able to seek on a stream, but which will produce corrupt archives
1911 // if they unknowingly seek on a non-seekable stream.
1913 // wxFILE_KIND_DISK is a good catch all return value, since other values
1914 // disable features of the archive streams. Some other value must be returned
1915 // for a file type that appears seekable but isn't.
1918 // * Pipes on Windows
1919 // * Files on VMS with a record format other than StreamLF
1921 wxFileKind
wxGetFileKind(int fd
)
1923 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1924 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1926 case FILE_TYPE_CHAR
:
1927 return wxFILE_KIND_TERMINAL
;
1928 case FILE_TYPE_DISK
:
1929 return wxFILE_KIND_DISK
;
1930 case FILE_TYPE_PIPE
:
1931 return wxFILE_KIND_PIPE
;
1934 return wxFILE_KIND_UNKNOWN
;
1936 #elif defined(__UNIX__)
1938 return wxFILE_KIND_TERMINAL
;
1943 if (S_ISFIFO(st
.st_mode
))
1944 return wxFILE_KIND_PIPE
;
1945 if (!S_ISREG(st
.st_mode
))
1946 return wxFILE_KIND_UNKNOWN
;
1948 #if defined(__VMS__)
1949 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1950 return wxFILE_KIND_UNKNOWN
;
1953 return wxFILE_KIND_DISK
;
1956 #define wxFILEKIND_STUB
1958 return wxFILE_KIND_DISK
;
1962 wxFileKind
wxGetFileKind(FILE *fp
)
1964 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1965 // Should be fixed in version 1.4.
1966 #if defined(wxFILEKIND_STUB) || \
1967 (defined(__WATCOMC__) && __WATCOMC__ <= 1230 && defined(__SW_BR))
1969 return wxFILE_KIND_DISK
;
1971 return wxGetFileKind(fileno(fp
));
1976 #pragma warning(default:4706) // assignment within conditional expression