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 // 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 !defined(__WATCOMC__)
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 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
246 return wxString(wxFileFunctionsBuffer
);
248 wxChar buf
[_MAXPATHLEN
];
249 wxStrcpy(buf
, wxFileFunctionsBuffer
);
251 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
253 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
255 const wxChar
*path
= node
->GetData();
256 wxStrcpy (wxFileFunctionsBuffer
, path
);
257 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
258 if (ch
!= wxT('\\') && ch
!= wxT('/'))
259 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
260 wxStrcat (wxFileFunctionsBuffer
, filename
);
262 wxUnix2DosFilename (wxFileFunctionsBuffer
);
264 if (wxFileExists (wxFileFunctionsBuffer
))
266 return wxString(wxFileFunctionsBuffer
); // Found!
270 return wxEmptyString
; // Not found
273 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
275 wxString f
= FindValidPath(file
);
276 if ( f
.empty() || wxIsAbsolutePath(f
) )
280 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
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 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
309 #endif // __WIN32__/!__WIN32__
313 wxIsAbsolutePath (const wxString
& filename
)
315 if (!filename
.empty())
317 #if defined(__WXMAC__) && !defined(__DARWIN__)
318 // Classic or Carbon CodeWarrior like
319 // Carbon with Apple DevTools is Unix like
321 // This seems wrong to me, but there is no fix. since
322 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
323 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
324 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
327 // Unix like or Windows
328 if (filename
[0] == wxT('/'))
332 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
335 #if defined(__WINDOWS__) || defined(__OS2__)
337 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
345 * Strip off any extension (dot something) from end of file,
346 * IF one exists. Inserts zero into buffer.
350 void wxStripExtension(wxChar
*buffer
)
352 int len
= wxStrlen(buffer
);
356 if (buffer
[i
] == wxT('.'))
365 void wxStripExtension(wxString
& buffer
)
367 //RN: Be careful about the handling the case where
368 //buffer.Length() == 0
369 for(size_t i
= buffer
.Length() - 1; i
!= wxString::npos
; --i
)
371 if (buffer
.GetChar(i
) == wxT('.'))
373 buffer
= buffer
.Left(i
);
379 // Destructive removal of /./ and /../ stuff
380 wxChar
*wxRealPath (wxChar
*path
)
383 static const wxChar SEP
= wxT('\\');
384 wxUnix2DosFilename(path
);
386 static const wxChar SEP
= wxT('/');
388 if (path
[0] && path
[1]) {
389 /* MATTHEW: special case "/./x" */
391 if (path
[2] == SEP
&& path
[1] == wxT('.'))
399 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
402 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
407 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
408 && (q
- 1 <= path
|| q
[-1] != SEP
))
411 if (path
[0] == wxT('\0'))
416 #if defined(__WXMSW__) || defined(__OS2__)
417 /* Check that path[2] is NULL! */
418 else if (path
[1] == wxT(':') && !path
[2])
427 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
436 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
438 if (filename
.empty())
439 return (wxChar
*) NULL
;
441 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
442 wxChar buf
[_MAXPATHLEN
];
444 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
445 wxChar ch
= buf
[wxStrlen(buf
) - 1];
447 if (ch
!= wxT('\\') && ch
!= wxT('/'))
448 wxStrcat(buf
, wxT("\\"));
451 wxStrcat(buf
, wxT("/"));
453 wxStrcat(buf
, wxFileFunctionsBuffer
);
454 return MYcopystring( wxRealPath(buf
) );
456 return MYcopystring( wxFileFunctionsBuffer
);
462 ~user/ => user's home dir
463 If the environment variable a = "foo" and b = "bar" then:
480 /* input name in name, pathname output to buf. */
482 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
484 register wxChar
*d
, *s
, *nm
;
485 wxChar lnm
[_MAXPATHLEN
];
488 // Some compilers don't like this line.
489 // const wxChar trimchars[] = wxT("\n \t");
492 trimchars
[0] = wxT('\n');
493 trimchars
[1] = wxT(' ');
494 trimchars
[2] = wxT('\t');
498 const wxChar SEP
= wxT('\\');
500 const wxChar SEP
= wxT('/');
503 if (name
== NULL
|| *name
== wxT('\0'))
505 nm
= MYcopystring(name
); // Make a scratch copy
508 /* Skip leading whitespace and cr */
509 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
511 /* And strip off trailing whitespace and cr */
512 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
513 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
521 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
524 /* Expand inline environment variables */
542 while ((*d
++ = *s
) != 0) {
544 if (*s
== wxT('\\')) {
545 if ((*(d
- 1) = *++s
)!=0) {
553 // No env variables on WinCE
556 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
558 if (*s
++ == wxT('$'))
561 register wxChar
*start
= d
;
562 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
563 register wxChar
*value
;
564 while ((*d
++ = *s
) != 0)
565 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
570 value
= wxGetenv(braces
? start
+ 1 : start
);
572 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
586 /* Expand ~ and ~user */
588 if (nm
[0] == wxT('~') && !q
)
591 if (nm
[1] == SEP
|| nm
[1] == 0)
593 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
594 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
599 { /* ~user/filename */
600 register wxChar
*nnm
;
601 register wxChar
*home
;
602 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
606 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
607 was_sep
= (*s
== SEP
);
608 nnm
= *s
? s
+ 1 : s
;
610 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
611 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
)
613 if (was_sep
) /* replace only if it was there: */
626 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
628 while (wxT('\0') != (*d
++ = *s
++))
631 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
635 while ((*d
++ = *s
++) != 0)
639 delete[] nm_tmp
; // clean up alloc
640 /* Now clean up the buffer */
641 return wxRealPath(buf
);
644 /* Contract Paths to be build upon an environment variable
647 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
649 The call wxExpandPath can convert these back!
652 wxContractPath (const wxString
& filename
,
653 const wxString
& WXUNUSED_IN_WINCE(envname
),
654 const wxString
& user
)
656 static wxChar dest
[_MAXPATHLEN
];
658 if (filename
.empty())
659 return (wxChar
*) NULL
;
661 wxStrcpy (dest
, WXSTRINGCAST filename
);
663 wxUnix2DosFilename(dest
);
666 // Handle environment
670 if (!envname
.empty() && (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
671 (tcp
= wxStrstr (dest
, val
)) != NULL
)
673 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
676 wxStrcpy (tcp
, WXSTRINGCAST envname
);
677 wxStrcat (tcp
, wxT("}"));
678 wxStrcat (tcp
, wxFileFunctionsBuffer
);
682 // Handle User's home (ignore root homes!)
683 val
= wxGetUserHome (user
);
687 const size_t len
= wxStrlen(val
);
691 if (wxStrncmp(dest
, val
, len
) == 0)
693 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
695 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
696 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
697 wxStrcpy (dest
, wxFileFunctionsBuffer
);
703 // Return just the filename, not the path (basename)
704 wxChar
*wxFileNameFromPath (wxChar
*path
)
707 wxString n
= wxFileNameFromPath(p
);
709 return path
+ p
.length() - n
.length();
712 wxString
wxFileNameFromPath (const wxString
& path
)
715 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
717 wxString fullname
= name
;
720 fullname
<< wxFILE_SEP_EXT
<< ext
;
726 // Return just the directory, or NULL if no directory
728 wxPathOnly (wxChar
*path
)
732 static wxChar buf
[_MAXPATHLEN
];
735 wxStrcpy (buf
, path
);
737 int l
= wxStrlen(path
);
740 // Search backward for a backward or forward slash
743 #if defined(__WXMAC__) && !defined(__DARWIN__)
744 // Classic or Carbon CodeWarrior like
745 // Carbon with Apple DevTools is Unix like
746 if (path
[i
] == wxT(':') )
752 // Unix like or Windows
753 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
760 if (path
[i
] == wxT(']'))
769 #if defined(__WXMSW__) || defined(__OS2__)
770 // Try Drive specifier
771 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
773 // A:junk --> A:. (since A:.\junk Not A:\junk)
780 return (wxChar
*) NULL
;
783 // Return just the directory, or NULL if no directory
784 wxString
wxPathOnly (const wxString
& path
)
788 wxChar buf
[_MAXPATHLEN
];
791 wxStrcpy (buf
, WXSTRINGCAST path
);
793 int l
= path
.Length();
796 // Search backward for a backward or forward slash
799 #if defined(__WXMAC__) && !defined(__DARWIN__)
800 // Classic or Carbon CodeWarrior like
801 // Carbon with Apple DevTools is Unix like
802 if (path
[i
] == wxT(':') )
805 return wxString(buf
);
808 // Unix like or Windows
809 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
811 // Don't return an empty string
815 return wxString(buf
);
819 if (path
[i
] == wxT(']'))
822 return wxString(buf
);
828 #if defined(__WXMSW__) || defined(__OS2__)
829 // Try Drive specifier
830 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
832 // A:junk --> A:. (since A:.\junk Not A:\junk)
835 return wxString(buf
);
839 return wxEmptyString
;
842 // Utility for converting delimiters in DOS filenames to UNIX style
843 // and back again - or we get nasty problems with delimiters.
844 // Also, convert to lower case, since case is significant in UNIX.
846 #if defined(__WXMAC__)
848 #if TARGET_API_MAC_OSX
849 #define kDefaultPathStyle kCFURLPOSIXPathStyle
851 #define kDefaultPathStyle kCFURLHFSPathStyle
854 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
857 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
858 if ( additionalPathComponent
)
860 CFURLRef parentURLRef
= fullURLRef
;
861 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
862 additionalPathComponent
,false);
863 CFRelease( parentURLRef
) ;
865 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
866 CFRelease( fullURLRef
) ;
867 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
870 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
872 OSStatus err
= noErr
;
873 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
876 if ( CFURLGetFSRef(url
, fsRef
) == false )
887 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
889 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
892 return wxMacCFStringHolder(cfname
).AsString() ;
895 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
898 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
900 return wxMacFSRefToPath( &fsRef
) ;
902 return wxEmptyString
;
905 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
907 OSStatus err
= noErr
;
909 wxMacPathToFSRef( path
, &fsRef
) ;
910 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
916 wxDos2UnixFilename (wxChar
*s
)
925 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
932 #if defined(__WXMSW__) || defined(__OS2__)
933 wxUnix2DosFilename (wxChar
*s
)
935 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
938 // Yes, I really mean this to happen under DOS only! JACS
939 #if defined(__WXMSW__) || defined(__OS2__)
950 // Concatenate two files to form third
952 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
956 wxFile
in1(file1
), in2(file2
);
957 wxTempFile
out(file3
);
959 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
963 unsigned char buf
[1024];
965 for( int i
=0; i
<2; i
++)
967 wxFile
*in
= i
==0 ? &in1
: &in2
;
969 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
971 if ( !out
.Write(buf
,ofs
) )
973 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
990 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
992 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
993 // CopyFile() copies file attributes and modification time too, so use it
994 // instead of our code if available
996 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
997 if ( !::CopyFile(file1
, file2
, !overwrite
) )
999 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1000 file1
.c_str(), file2
.c_str());
1004 #elif defined(__OS2__)
1005 if ( ::DosCopy((PSZ
)file1
.c_str(), (PSZ
)file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1007 #elif defined(__PALMOS__)
1008 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1010 #elif wxUSE_FILE // !Win32
1013 // get permissions of file1
1014 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1016 // the file probably doesn't exist or we haven't the rights to read
1018 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1023 // open file1 for reading
1024 wxFile
fileIn(file1
, wxFile::read
);
1025 if ( !fileIn
.IsOpened() )
1028 // remove file2, if it exists. This is needed for creating
1029 // file2 with the correct permissions in the next step
1030 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1032 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1037 // reset the umask as we want to create the file with exactly the same
1038 // permissions as the original one
1041 // create file2 with the same permissions than file1 and open it for
1045 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1048 // copy contents of file1 to file2
1053 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1054 if ( fileIn
.Error() )
1061 if ( fileOut
.Write(buf
, count
) < count
)
1065 // we can expect fileIn to be closed successfully, but we should ensure
1066 // that fileOut was closed as some write errors (disk full) might not be
1067 // detected before doing this
1068 if ( !fileIn
.Close() || !fileOut
.Close() )
1071 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1072 // no chmod in VA. Should be some permission API for HPFS386 partitions
1074 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1076 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1080 #endif // OS/2 || Mac
1082 #else // !Win32 && ! wxUSE_FILE
1084 // impossible to simulate with wxWidgets API
1087 wxUnusedVar(overwrite
);
1090 #endif // __WXMSW__ && __WIN32__
1096 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1098 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1099 // Normal system call
1100 if ( wxRename (file1
, file2
) == 0 )
1105 if (wxCopyFile(file1
, file2
)) {
1106 wxRemoveFile(file1
);
1113 bool wxRemoveFile(const wxString
& file
)
1115 #if defined(__VISUALC__) \
1116 || defined(__BORLANDC__) \
1117 || defined(__WATCOMC__) \
1118 || defined(__DMC__) \
1119 || defined(__GNUWIN32__) \
1120 || (defined(__MWERKS__) && defined(__MSL__))
1121 int res
= wxRemove(file
);
1122 #elif defined(__WXMAC__)
1123 int res
= unlink(wxFNCONV(file
));
1124 #elif defined(__WXPALMOS__)
1126 // TODO with VFSFileDelete()
1128 int res
= unlink(OS_FILENAME(file
));
1134 bool wxMkdir(const wxString
& dir
, int perm
)
1136 #if defined(__WXPALMOS__)
1138 #elif defined(__WXMAC__) && !defined(__UNIX__)
1139 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1141 const wxChar
*dirname
= dir
.c_str();
1143 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1144 // for the GNU compiler
1145 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1148 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1150 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1152 #elif defined(__OS2__)
1154 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1155 #elif defined(__DOS__)
1156 #if defined(__WATCOMC__)
1158 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1159 #elif defined(__DJGPP__)
1160 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1162 #error "Unsupported DOS compiler!"
1164 #else // !MSW, !DOS and !OS/2 VAC++
1167 if ( !CreateDirectory(dirname
, NULL
) )
1169 if ( wxMkDir(dir
.fn_str()) != 0 )
1173 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1182 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1184 #if defined(__VMS__)
1185 return false; //to be changed since rmdir exists in VMS7.x
1186 #elif defined(__OS2__)
1187 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1188 #elif defined(__WXWINCE__)
1189 return (CreateDirectory(dir
, NULL
) != 0);
1190 #elif defined(__WXPALMOS__)
1191 // TODO with VFSFileRename()
1194 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1198 // does the path exists? (may have or not '/' or '\\' at the end)
1199 bool wxDirExists(const wxChar
*pszPathName
)
1201 wxString
strPath(pszPathName
);
1203 #if defined(__WINDOWS__) || defined(__OS2__)
1204 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1205 // so remove all trailing backslashes from the path - but don't do this for
1206 // the pathes "d:\" (which are different from "d:") nor for just "\"
1207 while ( wxEndsWithPathSeparator(strPath
) )
1209 size_t len
= strPath
.length();
1210 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1213 strPath
.Truncate(len
- 1);
1215 #endif // __WINDOWS__
1218 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1219 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1223 #if defined(__WXPALMOS__)
1225 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1226 // stat() can't cope with network paths
1227 DWORD ret
= ::GetFileAttributes(strPath
);
1229 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1230 #elif defined(__OS2__)
1231 return (bool)(::DosSetCurrentDir((PSZ
)(WXSTRINGCAST strPath
)));
1235 #ifndef __VISAGECPP__
1236 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1238 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1239 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1242 #endif // __WIN32__/!__WIN32__
1245 // Get a temporary filename, opening and closing the file.
1246 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1249 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1250 if ( filename
.empty() )
1254 wxStrcpy(buf
, filename
);
1256 buf
= MYcopystring(filename
);
1260 wxUnusedVar(prefix
);
1262 // wxFileName::CreateTempFileName needs wxFile class enabled
1267 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1269 buf
= wxGetTempFileName(prefix
);
1271 return !buf
.empty();
1274 // Get first file name matching given wild card.
1276 static wxDir
*gs_dir
= NULL
;
1277 static wxString gs_dirPath
;
1279 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1281 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1282 if ( gs_dirPath
.empty() )
1283 gs_dirPath
= wxT(".");
1284 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1285 gs_dirPath
<< wxFILE_SEP_PATH
;
1289 gs_dir
= new wxDir(gs_dirPath
);
1291 if ( !gs_dir
->IsOpened() )
1293 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1294 return wxEmptyString
;
1300 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1301 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1302 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1306 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1307 if ( result
.empty() )
1313 return gs_dirPath
+ result
;
1316 wxString
wxFindNextFile()
1318 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1321 gs_dir
->GetNext(&result
);
1323 if ( result
.empty() )
1329 return gs_dirPath
+ result
;
1333 // Get current working directory.
1334 // If buf is NULL, allocates space using new, else
1336 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1338 #if defined(__WXPALMOS__)
1341 #elif defined(__WXWINCE__)
1349 buf
= new wxChar
[sz
+ 1];
1352 bool ok
wxDUMMY_INITIALIZE(false);
1354 // for the compilers which have Unicode version of _getcwd(), call it
1355 // directly, for the others call the ANSI version and do the translation
1358 #else // wxUSE_UNICODE
1359 bool needsANSI
= true;
1361 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1362 char cbuf
[_MAXPATHLEN
];
1366 #if wxUSE_UNICODE_MSLU
1367 if ( wxGetOsVersion() != wxWIN95
)
1369 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1372 ok
= _wgetcwd(buf
, sz
) != NULL
;
1378 #endif // wxUSE_UNICODE
1380 #if defined(_MSC_VER) || defined(__MINGW32__)
1381 ok
= _getcwd(cbuf
, sz
) != NULL
;
1382 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1384 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1386 wxString
res( lbuf
, *wxConvCurrent
) ;
1387 wxStrcpy( buf
, res
) ;
1392 #elif defined(__OS2__)
1394 ULONG ulDriveNum
= 0;
1395 ULONG ulDriveMap
= 0;
1396 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1401 rc
= ::DosQueryCurrentDir( 0 // current drive
1405 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1410 #else // !Win32/VC++ !Mac !OS2
1411 ok
= getcwd(cbuf
, sz
) != NULL
;
1414 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1415 // finally convert the result to Unicode if needed
1416 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1417 #endif // wxUSE_UNICODE
1422 wxLogSysError(_("Failed to get the working directory"));
1424 // VZ: the old code used to return "." on error which didn't make any
1425 // sense at all to me - empty string is a better error indicator
1426 // (NULL might be even better but I'm afraid this could lead to
1427 // problems with the old code assuming the return is never NULL)
1430 else // ok, but we might need to massage the path into the right format
1433 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1434 // with / deliminers. We don't like that.
1435 for (wxChar
*ch
= buf
; *ch
; ch
++)
1437 if (*ch
== wxT('/'))
1442 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1443 // he needs Unix as opposed to Win32 pathnames
1444 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1445 // another example of DOS/Unix mix (Cygwin)
1446 wxString pathUnix
= buf
;
1448 char bufA
[_MAXPATHLEN
];
1449 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1450 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1452 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1453 #endif // wxUSE_UNICODE
1454 #endif // __CYGWIN__
1469 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1470 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1471 wxString
str( buffer
);
1477 bool wxSetWorkingDirectory(const wxString
& d
)
1479 #if defined(__OS2__)
1480 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1481 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1482 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1483 #elif defined(__WINDOWS__)
1487 // No equivalent in WinCE
1491 return (bool)(SetCurrentDirectory(d
) != 0);
1494 // Must change drive, too.
1495 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1498 wxChar firstChar
= d
[0];
1502 firstChar
= firstChar
- 32;
1504 // To a drive number
1505 unsigned int driveNo
= firstChar
- 64;
1508 unsigned int noDrives
;
1509 _dos_setdrive(driveNo
, &noDrives
);
1512 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1520 // Get the OS directory if appropriate (such as the Windows directory).
1521 // On non-Windows platform, probably just return the empty string.
1522 wxString
wxGetOSDirectory()
1525 return wxString(wxT("\\Windows"));
1526 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1528 GetWindowsDirectory(buf
, 256);
1529 return wxString(buf
);
1530 #elif defined(__WXMAC__)
1531 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1533 return wxEmptyString
;
1537 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1539 size_t len
= wxStrlen(pszFileName
);
1541 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1544 // find a file in a list of directories, returns false if not found
1545 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1547 // we assume that it's not empty
1548 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1549 _T("empty file name in wxFindFileInPath"));
1551 // skip path separator in the beginning of the file name if present
1552 if ( wxIsPathSeparator(*pszFile
) )
1555 // copy the path (strtok will modify it)
1556 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1557 wxStrcpy(szPath
, pszPath
);
1560 wxChar
*pc
, *save_ptr
;
1561 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1563 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1565 // search for the file in this directory
1567 if ( !wxEndsWithPathSeparator(pc
) )
1568 strFile
+= wxFILE_SEP_PATH
;
1571 if ( wxFileExists(strFile
) ) {
1577 // suppress warning about unused variable save_ptr when wxStrtok() is a
1578 // macro which throws away its third argument
1583 return pc
!= NULL
; // if true => we breaked from the loop
1586 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1591 // it can be empty, but it shouldn't be NULL
1592 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1594 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1597 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1599 #if defined(__WXPALMOS__)
1601 #elif defined(__WXWINCE__)
1602 FILETIME ftLastWrite
;
1603 AutoHANDLE
hFile(::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
,
1604 NULL
, 0, FILE_ATTRIBUTE_NORMAL
, 0));
1606 if ( !hFile
.IsOk() )
1609 if ( !::GetFileTime(hFile
, NULL
, NULL
, &ftLastWrite
) )
1612 // sure we want to translate to local time here?
1614 if ( !::FileTimeToLocalFileTime(&ftLastWrite
, &ftLocal
) )
1616 wxLogLastError(_T("FileTimeToLocalFileTime"));
1619 // FILETIME is a counted in 100-ns since 1601-01-01, convert it to
1620 // number of seconds since 1970-01-01
1622 uli
.LowPart
= ftLocal
.dwLowDateTime
;
1623 uli
.HighPart
= ftLocal
.dwHighDateTime
;
1625 ULONGLONG ull
= uli
.QuadPart
;
1626 ull
/= wxULL(10000000); // number of 100ns intervals in 1s
1627 ull
-= wxULL(11644473600); // 1970-01-01 - 1601-01-01 in seconds
1629 return wx_static_cast(time_t, ull
);
1632 if ( wxStat( filename
, &buf
) != 0 )
1635 return buf
.st_mtime
;
1640 // Parses the filterStr, returning the number of filters.
1641 // Returns 0 if none or if there's a problem.
1642 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1644 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1645 wxArrayString
& descriptions
,
1646 wxArrayString
& filters
)
1648 descriptions
.Clear();
1651 wxString
str(filterStr
);
1653 wxString description
, filter
;
1655 while( pos
!= wxNOT_FOUND
)
1657 pos
= str
.Find(wxT('|'));
1658 if ( pos
== wxNOT_FOUND
)
1660 // if there are no '|'s at all in the string just take the entire
1661 // string as filter and make description empty for later autocompletion
1662 if ( filters
.IsEmpty() )
1664 descriptions
.Add(wxEmptyString
);
1665 filters
.Add(filterStr
);
1669 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1675 description
= str
.Left(pos
);
1676 str
= str
.Mid(pos
+ 1);
1677 pos
= str
.Find(wxT('|'));
1678 if ( pos
== wxNOT_FOUND
)
1684 filter
= str
.Left(pos
);
1685 str
= str
.Mid(pos
+ 1);
1688 descriptions
.Add(description
);
1689 filters
.Add(filter
);
1692 #if defined(__WXMOTIF__)
1693 // split it so there is one wildcard per entry
1694 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1696 pos
= filters
[i
].Find(wxT(';'));
1697 if (pos
!= wxNOT_FOUND
)
1699 // first split only filters
1700 descriptions
.Insert(descriptions
[i
],i
+1);
1701 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1702 filters
[i
]=filters
[i
].Left(pos
);
1704 // autoreplace new filter in description with pattern:
1705 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1706 // cause split into:
1707 // C/C++ Files(*.cpp)|*.cpp
1708 // C/C++ Files(*.c;*.h)|*.c;*.h
1709 // and next iteration cause another split into:
1710 // C/C++ Files(*.cpp)|*.cpp
1711 // C/C++ Files(*.c)|*.c
1712 // C/C++ Files(*.h)|*.h
1713 for ( size_t k
=i
;k
<i
+2;k
++ )
1715 pos
= descriptions
[k
].Find(filters
[k
]);
1716 if (pos
!= wxNOT_FOUND
)
1718 wxString before
= descriptions
[k
].Left(pos
);
1719 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1720 pos
= before
.Find(_T('('),true);
1721 if (pos
>before
.Find(_T(')'),true))
1723 before
= before
.Left(pos
+1);
1724 before
<< filters
[k
];
1725 pos
= after
.Find(_T(')'));
1726 int pos1
= after
.Find(_T('('));
1727 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1729 before
<< after
.Mid(pos
);
1730 descriptions
[k
] = before
;
1740 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1742 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1744 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1748 return filters
.GetCount();
1752 //------------------------------------------------------------------------
1753 // wild character routines
1754 //------------------------------------------------------------------------
1756 bool wxIsWild( const wxString
& pattern
)
1758 wxString tmp
= pattern
;
1759 wxChar
*pat
= WXSTRINGCAST(tmp
);
1764 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1775 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1777 * The match procedure is public domain code (from ircII's reg.c)
1780 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1784 /* Match if both are empty. */
1788 const wxChar
*m
= pat
.c_str(),
1799 if (dot_special
&& (*n
== wxT('.')))
1801 /* Never match so that hidden Unix files
1802 * are never found. */
1816 else if (*m
== wxT('?'))
1824 if (*m
== wxT('\\'))
1827 /* Quoting "nothing" is a bad thing */
1834 * If we are out of both strings or we just
1835 * saw a wildcard, then we can say we have a
1846 * We could check for *n == NULL at this point, but
1847 * since it's more common to have a character there,
1848 * check to see if they match first (m and n) and
1849 * 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
1877 if (*np
== wxT(' '))
1901 // Return the type of an open file
1903 // Some file types on some platforms seem seekable but in fact are not.
1904 // The main use of this function is to allow such cases to be detected
1905 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1907 // This is important for the archive streams, which benefit greatly from
1908 // being able to seek on a stream, but which will produce corrupt archives
1909 // if they unknowingly seek on a non-seekable stream.
1911 // wxFILE_KIND_DISK is a good catch all return value, since other values
1912 // disable features of the archive streams. Some other value must be returned
1913 // for a file type that appears seekable but isn't.
1916 // * Pipes on Windows
1917 // * Files on VMS with a record format other than StreamLF
1919 wxFileKind
wxGetFileKind(int fd
)
1921 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1922 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1924 case FILE_TYPE_CHAR
:
1925 return wxFILE_KIND_TERMINAL
;
1926 case FILE_TYPE_DISK
:
1927 return wxFILE_KIND_DISK
;
1928 case FILE_TYPE_PIPE
:
1929 return wxFILE_KIND_PIPE
;
1932 return wxFILE_KIND_UNKNOWN
;
1934 #elif defined(__UNIX__)
1936 return wxFILE_KIND_TERMINAL
;
1941 if (S_ISFIFO(st
.st_mode
))
1942 return wxFILE_KIND_PIPE
;
1943 if (!S_ISREG(st
.st_mode
))
1944 return wxFILE_KIND_UNKNOWN
;
1946 #if defined(__VMS__)
1947 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1948 return wxFILE_KIND_UNKNOWN
;
1951 return wxFILE_KIND_DISK
;
1954 #define wxFILEKIND_STUB
1956 return wxFILE_KIND_DISK
;
1960 wxFileKind
wxGetFileKind(FILE *fp
)
1962 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1963 // Should be fixed in version 1.4.
1964 #if defined(wxFILEKIND_STUB) || \
1965 (defined(__WATCOMC__) && __WATCOMC__ <= 1230 && defined(__SW_BR))
1967 return wxFILE_KIND_DISK
;
1969 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1974 #pragma warning(default:4706) // assignment within conditional expression