1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filefn.cpp
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
33 #include "wx/file.h" // This does include filefn.h
34 #include "wx/filename.h"
37 // there are just too many of those...
39 #pragma warning(disable:4706) // assignment within conditional expression
46 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
47 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
52 #if defined(__WXMAC__)
53 #include "wx/mac/private.h" // includes mac headers
57 #include "wx/msw/private.h"
58 #include "wx/msw/mslu.h"
60 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
62 // note that it must be included after <windows.h>
65 #include <sys/cygwin.h>
67 #endif // __GNUWIN32__
69 // io.h is needed for _get_osfhandle()
70 // Already included by filefn.h for many Windows compilers
71 #if defined __MWERKS__ || defined __CYGWIN__
80 // TODO: Borland probably has _wgetcwd as well?
85 // ----------------------------------------------------------------------------
87 // ----------------------------------------------------------------------------
90 #define _MAXPATHLEN 1024
94 # include "MoreFilesX.h"
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 // MT-FIXME: get rid of this horror and all code using it
102 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
104 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
106 // VisualAge C++ V4.0 cannot have any external linkage const decs
107 // in headers included by more than one primary source
109 const int wxInvalidOffset
= -1;
112 // ----------------------------------------------------------------------------
114 // ----------------------------------------------------------------------------
116 // we need to translate Mac filenames before passing them to OS functions
117 #define OS_FILENAME(s) (s.fn_str())
119 // ============================================================================
121 // ============================================================================
123 #ifdef wxNEED_WX_UNISTD_H
125 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
127 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
130 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
132 return access( wxConvFile
.cWX2MB( pathname
), mode
);
135 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
137 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
141 // wxNEED_WX_UNISTD_H
143 // ----------------------------------------------------------------------------
145 // ----------------------------------------------------------------------------
147 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
149 static inline wxChar
* MYcopystring(const wxString
& s
)
151 wxChar
* copy
= new wxChar
[s
.length() + 1];
152 return wxStrcpy(copy
, s
.c_str());
155 static inline wxChar
* MYcopystring(const wxChar
* s
)
157 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
158 return wxStrcpy(copy
, s
);
161 void wxPathList::Add (const wxString
& path
)
163 wxStringList::Add (WXSTRINGCAST path
);
166 // Add paths e.g. from the PATH environment variable
167 void wxPathList::AddEnvList (const wxString
& WXUNUSED_IN_WINCE(envVariable
))
169 // No environment variables on WinCE
171 static const wxChar PATH_TOKS
[] =
172 #if defined(__WINDOWS__) || defined(__OS2__)
174 The space has been removed from the tokenizers, otherwise a
175 path such as "C:\Program Files" would be split into 2 paths:
176 "C:\Program" and "Files"
178 // wxT(" ;"); // Don't separate with colon in DOS (used for drive)
179 wxT(";"); // Don't separate with colon in DOS (used for drive)
185 if (wxGetEnv (WXSTRINGCAST envVariable
, &val
))
187 wxChar
*s
= MYcopystring (val
);
188 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
195 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
203 // suppress warning about unused variable save_ptr when wxStrtok() is a
204 // macro which throws away its third argument
209 #endif // !__WXWINCE__
212 // Given a full filename (with path), ensure that that file can
213 // be accessed again USING FILENAME ONLY by adding the path
214 // to the list if not already there.
215 void wxPathList::EnsureFileAccessible (const wxString
& path
)
217 wxString
path_only(wxPathOnly(path
));
218 if ( !path_only
.empty() )
220 if ( !Member(path_only
) )
225 bool wxPathList::Member (const wxString
& path
)
227 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
229 wxString
path2( node
->GetData() );
231 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined(__WXMAC__)
233 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
235 // Case sensitive File System
236 path
.CompareTo (path2
) == 0
244 wxString
wxPathList::FindValidPath (const wxString
& file
)
246 wxExpandPath(wxFileFunctionsBuffer
, file
);
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 wxString
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
) )
279 wxString buf
= ::wxGetCwd();
281 if ( !wxEndsWithPathSeparator(buf
) )
283 buf
+= wxFILE_SEP_PATH
;
291 wxFileExists (const wxString
& filename
)
293 #if defined(__WXPALMOS__)
295 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
296 // we must use GetFileAttributes() instead of the ANSI C functions because
297 // it can cope with network (UNC) paths unlike them
298 DWORD ret
= ::GetFileAttributes(filename
);
300 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
303 #define S_ISREG(mode) ((mode) & S_IFREG)
306 #ifndef wxNEED_WX_UNISTD_H
307 return (wxStat( filename
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
309 || (errno
== EACCES
) // if access is denied something with that name
310 // exists and is opened in exclusive mode.
314 return wxStat( filename
, &st
) == 0 && S_ISREG(st
.st_mode
);
316 #endif // __WIN32__/!__WIN32__
320 wxIsAbsolutePath (const wxString
& filename
)
322 if (!filename
.empty())
324 #if defined(__WXMAC__) && !defined(__DARWIN__)
325 // Classic or Carbon CodeWarrior like
326 // Carbon with Apple DevTools is Unix like
328 // This seems wrong to me, but there is no fix. since
329 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
330 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
331 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
334 // Unix like or Windows
335 if (filename
[0] == wxT('/'))
339 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
342 #if defined(__WINDOWS__) || defined(__OS2__)
344 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
352 * Strip off any extension (dot something) from end of file,
353 * IF one exists. Inserts zero into buffer.
357 void wxStripExtension(wxChar
*buffer
)
359 int len
= wxStrlen(buffer
);
363 if (buffer
[i
] == wxT('.'))
372 void wxStripExtension(wxString
& buffer
)
374 //RN: Be careful about the handling the case where
375 //buffer.length() == 0
376 for(size_t i
= buffer
.length() - 1; i
!= wxString::npos
; --i
)
378 if (buffer
.GetChar(i
) == wxT('.'))
380 buffer
= buffer
.Left(i
);
386 // Destructive removal of /./ and /../ stuff
387 wxChar
*wxRealPath (wxChar
*path
)
390 static const wxChar SEP
= wxT('\\');
391 wxUnix2DosFilename(path
);
393 static const wxChar SEP
= wxT('/');
395 if (path
[0] && path
[1]) {
396 /* MATTHEW: special case "/./x" */
398 if (path
[2] == SEP
&& path
[1] == wxT('.'))
406 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
409 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
414 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
415 && (q
- 1 <= path
|| q
[-1] != SEP
))
418 if (path
[0] == wxT('\0'))
423 #if defined(__WXMSW__) || defined(__OS2__)
424 /* Check that path[2] is NULL! */
425 else if (path
[1] == wxT(':') && !path
[2])
434 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
442 wxString
wxRealPath(const wxString
& path
)
444 wxChar
*buf1
=MYcopystring(path
);
445 wxChar
*buf2
=wxRealPath(buf1
);
453 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
455 if (filename
.empty())
456 return (wxChar
*) NULL
;
458 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
)))
460 wxString buf
= ::wxGetCwd();
461 wxChar ch
= buf
.Last();
463 if (ch
!= wxT('\\') && ch
!= wxT('/'))
469 buf
<< wxFileFunctionsBuffer
;
470 buf
= wxRealPath( buf
);
471 return MYcopystring( buf
);
473 return MYcopystring( wxFileFunctionsBuffer
);
479 ~user/ => user's home dir
480 If the environment variable a = "foo" and b = "bar" then:
497 /* input name in name, pathname output to buf. */
499 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
501 register wxChar
*d
, *s
, *nm
;
502 wxChar lnm
[_MAXPATHLEN
];
505 // Some compilers don't like this line.
506 // const wxChar trimchars[] = wxT("\n \t");
509 trimchars
[0] = wxT('\n');
510 trimchars
[1] = wxT(' ');
511 trimchars
[2] = wxT('\t');
515 const wxChar SEP
= wxT('\\');
517 const wxChar SEP
= wxT('/');
520 if (name
== NULL
|| *name
== wxT('\0'))
522 nm
= MYcopystring(name
); // Make a scratch copy
525 /* Skip leading whitespace and cr */
526 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
528 /* And strip off trailing whitespace and cr */
529 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
530 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
538 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
541 /* Expand inline environment variables */
559 while ((*d
++ = *s
) != 0) {
561 if (*s
== wxT('\\')) {
562 if ((*(d
- 1) = *++s
)!=0) {
570 // No env variables on WinCE
573 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
575 if (*s
++ == wxT('$'))
578 register wxChar
*start
= d
;
579 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
580 register wxChar
*value
;
581 while ((*d
++ = *s
) != 0)
582 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
587 value
= wxGetenv(braces
? start
+ 1 : start
);
589 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
603 /* Expand ~ and ~user */
605 if (nm
[0] == wxT('~') && !q
)
608 if (nm
[1] == SEP
|| nm
[1] == 0)
610 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
611 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
616 { /* ~user/filename */
617 register wxChar
*nnm
;
618 register wxChar
*home
;
619 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
623 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
624 was_sep
= (*s
== SEP
);
625 nnm
= *s
? s
+ 1 : s
;
627 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
628 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
)
630 if (was_sep
) /* replace only if it was there: */
643 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
645 while (wxT('\0') != (*d
++ = *s
++))
648 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
652 while ((*d
++ = *s
++) != 0)
656 delete[] nm_tmp
; // clean up alloc
657 /* Now clean up the buffer */
658 return wxRealPath(buf
);
661 /* Contract Paths to be build upon an environment variable
664 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
666 The call wxExpandPath can convert these back!
669 wxContractPath (const wxString
& filename
,
670 const wxString
& WXUNUSED_IN_WINCE(envname
),
671 const wxString
& user
)
673 static wxChar dest
[_MAXPATHLEN
];
675 if (filename
.empty())
676 return (wxChar
*) NULL
;
678 wxStrcpy (dest
, WXSTRINGCAST filename
);
680 wxUnix2DosFilename(dest
);
683 // Handle environment
687 if (!envname
.empty() && (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
688 (tcp
= wxStrstr (dest
, val
)) != NULL
)
690 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
693 wxStrcpy (tcp
, WXSTRINGCAST envname
);
694 wxStrcat (tcp
, wxT("}"));
695 wxStrcat (tcp
, wxFileFunctionsBuffer
);
699 // Handle User's home (ignore root homes!)
700 val
= wxGetUserHome (user
);
704 const size_t len
= wxStrlen(val
);
708 if (wxStrncmp(dest
, val
, len
) == 0)
710 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
712 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
713 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
714 wxStrcpy (dest
, wxFileFunctionsBuffer
);
720 // Return just the filename, not the path (basename)
721 wxChar
*wxFileNameFromPath (wxChar
*path
)
724 wxString n
= wxFileNameFromPath(p
);
726 return path
+ p
.length() - n
.length();
729 wxString
wxFileNameFromPath (const wxString
& path
)
732 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
734 wxString fullname
= name
;
737 fullname
<< wxFILE_SEP_EXT
<< ext
;
743 // Return just the directory, or NULL if no directory
745 wxPathOnly (wxChar
*path
)
749 static wxChar buf
[_MAXPATHLEN
];
752 wxStrcpy (buf
, path
);
754 int l
= wxStrlen(path
);
757 // Search backward for a backward or forward slash
760 #if defined(__WXMAC__) && !defined(__DARWIN__)
761 // Classic or Carbon CodeWarrior like
762 // Carbon with Apple DevTools is Unix like
763 if (path
[i
] == wxT(':') )
769 // Unix like or Windows
770 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
777 if (path
[i
] == wxT(']'))
786 #if defined(__WXMSW__) || defined(__OS2__)
787 // Try Drive specifier
788 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
790 // A:junk --> A:. (since A:.\junk Not A:\junk)
797 return (wxChar
*) NULL
;
800 // Return just the directory, or NULL if no directory
801 wxString
wxPathOnly (const wxString
& path
)
805 wxChar buf
[_MAXPATHLEN
];
808 wxStrcpy (buf
, WXSTRINGCAST path
);
810 int l
= path
.length();
813 // Search backward for a backward or forward slash
816 #if defined(__WXMAC__) && !defined(__DARWIN__)
817 // Classic or Carbon CodeWarrior like
818 // Carbon with Apple DevTools is Unix like
819 if (path
[i
] == wxT(':') )
822 return wxString(buf
);
825 // Unix like or Windows
826 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
828 // Don't return an empty string
832 return wxString(buf
);
836 if (path
[i
] == wxT(']'))
839 return wxString(buf
);
845 #if defined(__WXMSW__) || defined(__OS2__)
846 // Try Drive specifier
847 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
849 // A:junk --> A:. (since A:.\junk Not A:\junk)
852 return wxString(buf
);
856 return wxEmptyString
;
859 // Utility for converting delimiters in DOS filenames to UNIX style
860 // and back again - or we get nasty problems with delimiters.
861 // Also, convert to lower case, since case is significant in UNIX.
863 #if defined(__WXMAC__)
865 #if TARGET_API_MAC_OSX
866 #define kDefaultPathStyle kCFURLPOSIXPathStyle
868 #define kDefaultPathStyle kCFURLHFSPathStyle
871 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
874 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
875 if ( additionalPathComponent
)
877 CFURLRef parentURLRef
= fullURLRef
;
878 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
879 additionalPathComponent
,false);
880 CFRelease( parentURLRef
) ;
882 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
883 CFRelease( fullURLRef
) ;
884 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
887 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
889 OSStatus err
= noErr
;
890 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
893 if ( CFURLGetFSRef(url
, fsRef
) == false )
904 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
906 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
909 return wxMacCFStringHolder(cfname
).AsString() ;
912 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
915 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
917 return wxMacFSRefToPath( &fsRef
) ;
919 return wxEmptyString
;
922 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
924 OSStatus err
= noErr
;
926 wxMacPathToFSRef( path
, &fsRef
) ;
927 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
933 wxDos2UnixFilename (wxChar
*s
)
942 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
949 #if defined(__WXMSW__) || defined(__OS2__)
950 wxUnix2DosFilename (wxChar
*s
)
952 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
955 // Yes, I really mean this to happen under DOS only! JACS
956 #if defined(__WXMSW__) || defined(__OS2__)
967 // Concatenate two files to form third
969 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
973 wxFile
in1(file1
), in2(file2
);
974 wxTempFile
out(file3
);
976 if ( !in1
.IsOpened() || !in2
.IsOpened() || !out
.IsOpened() )
980 unsigned char buf
[1024];
982 for( int i
=0; i
<2; i
++)
984 wxFile
*in
= i
==0 ? &in1
: &in2
;
986 if ( (ofs
= in
->Read(buf
,WXSIZEOF(buf
))) == wxInvalidOffset
) return false;
988 if ( !out
.Write(buf
,ofs
) )
990 } while ( ofs
== (ssize_t
)WXSIZEOF(buf
) );
1007 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1009 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1010 // CopyFile() copies file attributes and modification time too, so use it
1011 // instead of our code if available
1013 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1014 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1016 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1017 file1
.c_str(), file2
.c_str());
1021 #elif defined(__OS2__)
1022 if ( ::DosCopy((PSZ
)file1
.c_str(), (PSZ
)file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1024 #elif defined(__PALMOS__)
1025 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1027 #elif wxUSE_FILE // !Win32
1030 // get permissions of file1
1031 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1033 // the file probably doesn't exist or we haven't the rights to read
1035 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1040 // open file1 for reading
1041 wxFile
fileIn(file1
, wxFile::read
);
1042 if ( !fileIn
.IsOpened() )
1045 // remove file2, if it exists. This is needed for creating
1046 // file2 with the correct permissions in the next step
1047 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1049 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1054 // reset the umask as we want to create the file with exactly the same
1055 // permissions as the original one
1058 // create file2 with the same permissions than file1 and open it for
1062 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1065 // copy contents of file1 to file2
1070 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1071 if ( fileIn
.Error() )
1078 if ( fileOut
.Write(buf
, count
) < count
)
1082 // we can expect fileIn to be closed successfully, but we should ensure
1083 // that fileOut was closed as some write errors (disk full) might not be
1084 // detected before doing this
1085 if ( !fileIn
.Close() || !fileOut
.Close() )
1088 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1089 // no chmod in VA. Should be some permission API for HPFS386 partitions
1091 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1093 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1097 #endif // OS/2 || Mac
1099 #else // !Win32 && ! wxUSE_FILE
1101 // impossible to simulate with wxWidgets API
1104 wxUnusedVar(overwrite
);
1107 #endif // __WXMSW__ && __WIN32__
1113 wxRenameFile(const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1115 if ( !overwrite
&& wxFileExists(file2
) )
1119 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1120 file1
.c_str(), file2
.c_str()
1126 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1127 // Normal system call
1128 if ( wxRename (file1
, file2
) == 0 )
1133 if (wxCopyFile(file1
, file2
, overwrite
)) {
1134 wxRemoveFile(file1
);
1141 bool wxRemoveFile(const wxString
& file
)
1143 #if defined(__VISUALC__) \
1144 || defined(__BORLANDC__) \
1145 || defined(__WATCOMC__) \
1146 || defined(__DMC__) \
1147 || defined(__GNUWIN32__) \
1148 || (defined(__MWERKS__) && defined(__MSL__))
1149 int res
= wxRemove(file
);
1150 #elif defined(__WXMAC__)
1151 int res
= unlink(wxFNCONV(file
));
1152 #elif defined(__WXPALMOS__)
1154 // TODO with VFSFileDelete()
1156 int res
= unlink(OS_FILENAME(file
));
1162 bool wxMkdir(const wxString
& dir
, int perm
)
1164 #if defined(__WXPALMOS__)
1166 #elif defined(__WXMAC__) && !defined(__UNIX__)
1167 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1169 const wxChar
*dirname
= dir
.c_str();
1171 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1172 // for the GNU compiler
1173 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1176 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1178 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1180 #elif defined(__OS2__)
1182 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1183 #elif defined(__DOS__)
1184 #if defined(__WATCOMC__)
1186 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1187 #elif defined(__DJGPP__)
1188 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1190 #error "Unsupported DOS compiler!"
1192 #else // !MSW, !DOS and !OS/2 VAC++
1195 if ( !CreateDirectory(dirname
, NULL
) )
1197 if ( wxMkDir(dir
.fn_str()) != 0 )
1201 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1210 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1212 #if defined(__VMS__)
1213 return false; //to be changed since rmdir exists in VMS7.x
1214 #elif defined(__OS2__)
1215 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1216 #elif defined(__WXWINCE__)
1217 return (CreateDirectory(dir
, NULL
) != 0);
1218 #elif defined(__WXPALMOS__)
1219 // TODO with VFSFileRename()
1222 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1226 // does the path exists? (may have or not '/' or '\\' at the end)
1227 bool wxDirExists(const wxChar
*pszPathName
)
1229 wxString
strPath(pszPathName
);
1231 #if defined(__WINDOWS__) || defined(__OS2__)
1232 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1233 // so remove all trailing backslashes from the path - but don't do this for
1234 // the pathes "d:\" (which are different from "d:") nor for just "\"
1235 while ( wxEndsWithPathSeparator(strPath
) )
1237 size_t len
= strPath
.length();
1238 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1241 strPath
.Truncate(len
- 1);
1243 #endif // __WINDOWS__
1246 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1247 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1251 #if defined(__WXPALMOS__)
1253 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1254 // stat() can't cope with network paths
1255 DWORD ret
= ::GetFileAttributes(strPath
);
1257 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1258 #elif defined(__OS2__)
1259 FILESTATUS3 Info
= {{0}};
1260 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
1261 (void*) &Info
, sizeof(FILESTATUS3
));
1263 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
1264 (rc
== ERROR_SHARING_VIOLATION
);
1265 // If we got a sharing violation, there must be something with this name.
1269 #ifndef __VISAGECPP__
1270 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1272 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1273 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1276 #endif // __WIN32__/!__WIN32__
1279 // Get a temporary filename, opening and closing the file.
1280 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1283 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1284 if ( filename
.empty() )
1288 wxStrcpy(buf
, filename
);
1290 buf
= MYcopystring(filename
);
1294 wxUnusedVar(prefix
);
1296 // wxFileName::CreateTempFileName needs wxFile class enabled
1301 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1303 buf
= wxGetTempFileName(prefix
);
1305 return !buf
.empty();
1308 // Get first file name matching given wild card.
1310 static wxDir
*gs_dir
= NULL
;
1311 static wxString gs_dirPath
;
1313 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1315 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1316 if ( gs_dirPath
.empty() )
1317 gs_dirPath
= wxT(".");
1318 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1319 gs_dirPath
<< wxFILE_SEP_PATH
;
1323 gs_dir
= new wxDir(gs_dirPath
);
1325 if ( !gs_dir
->IsOpened() )
1327 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1328 return wxEmptyString
;
1334 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1335 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1336 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1340 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1341 if ( result
.empty() )
1347 return gs_dirPath
+ result
;
1350 wxString
wxFindNextFile()
1352 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1355 gs_dir
->GetNext(&result
);
1357 if ( result
.empty() )
1363 return gs_dirPath
+ result
;
1367 // Get current working directory.
1368 // If buf is NULL, allocates space using new, else copies into buf.
1369 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1370 // wxDoGetCwd() is their common core to be moved
1371 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1372 // Do not expose wxDoGetCwd in headers!
1374 wxChar
*wxDoGetCwd(wxChar
*buf
, int sz
)
1376 #if defined(__WXPALMOS__)
1378 if(buf
&& sz
>0) buf
[0] = _T('\0');
1380 #elif defined(__WXWINCE__)
1382 if(buf
&& sz
>0) buf
[0] = _T('\0');
1387 buf
= new wxChar
[sz
+ 1];
1390 bool ok
wxDUMMY_INITIALIZE(false);
1392 // for the compilers which have Unicode version of _getcwd(), call it
1393 // directly, for the others call the ANSI version and do the translation
1396 #else // wxUSE_UNICODE
1397 bool needsANSI
= true;
1399 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1400 char cbuf
[_MAXPATHLEN
];
1404 #if wxUSE_UNICODE_MSLU
1405 if ( wxGetOsVersion() != wxWIN95
)
1407 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1410 ok
= _wgetcwd(buf
, sz
) != NULL
;
1416 #endif // wxUSE_UNICODE
1418 #if defined(_MSC_VER) || defined(__MINGW32__)
1419 ok
= _getcwd(cbuf
, sz
) != NULL
;
1420 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1422 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1424 wxString
res( lbuf
, *wxConvCurrent
) ;
1425 wxStrcpy( buf
, res
) ;
1430 #elif defined(__OS2__)
1432 ULONG ulDriveNum
= 0;
1433 ULONG ulDriveMap
= 0;
1434 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1439 rc
= ::DosQueryCurrentDir( 0 // current drive
1443 cbuf
[0] = char('A' + (ulDriveNum
- 1));
1448 #else // !Win32/VC++ !Mac !OS2
1449 ok
= getcwd(cbuf
, sz
) != NULL
;
1452 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1453 // finally convert the result to Unicode if needed
1454 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1455 #endif // wxUSE_UNICODE
1460 wxLogSysError(_("Failed to get the working directory"));
1462 // VZ: the old code used to return "." on error which didn't make any
1463 // sense at all to me - empty string is a better error indicator
1464 // (NULL might be even better but I'm afraid this could lead to
1465 // problems with the old code assuming the return is never NULL)
1468 else // ok, but we might need to massage the path into the right format
1471 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1472 // with / deliminers. We don't like that.
1473 for (wxChar
*ch
= buf
; *ch
; ch
++)
1475 if (*ch
== wxT('/'))
1480 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1481 // he needs Unix as opposed to Win32 pathnames
1482 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1483 // another example of DOS/Unix mix (Cygwin)
1484 wxString pathUnix
= buf
;
1486 char bufA
[_MAXPATHLEN
];
1487 cygwin_conv_to_full_win32_path(pathUnix
.mb_str(wxConvFile
), bufA
);
1488 wxConvFile
.MB2WC(buf
, bufA
, sz
);
1490 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1491 #endif // wxUSE_UNICODE
1492 #endif // __CYGWIN__
1505 #if WXWIN_COMPATIBILITY_2_6
1506 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1508 return wxDoGetCwd(buf
,sz
);
1510 #endif // WXWIN_COMPATIBILITY_2_6
1515 wxDoGetCwd(wxStringBuffer(str
, _MAXPATHLEN
), _MAXPATHLEN
);
1519 bool wxSetWorkingDirectory(const wxString
& d
)
1521 #if defined(__OS2__)
1522 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1523 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1524 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1525 #elif defined(__WINDOWS__)
1529 // No equivalent in WinCE
1533 return (bool)(SetCurrentDirectory(d
) != 0);
1536 // Must change drive, too.
1537 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1540 wxChar firstChar
= d
[0];
1544 firstChar
= firstChar
- 32;
1546 // To a drive number
1547 unsigned int driveNo
= firstChar
- 64;
1550 unsigned int noDrives
;
1551 _dos_setdrive(driveNo
, &noDrives
);
1554 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1562 // Get the OS directory if appropriate (such as the Windows directory).
1563 // On non-Windows platform, probably just return the empty string.
1564 wxString
wxGetOSDirectory()
1567 return wxString(wxT("\\Windows"));
1568 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1570 GetWindowsDirectory(buf
, 256);
1571 return wxString(buf
);
1572 #elif defined(__WXMAC__)
1573 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1575 return wxEmptyString
;
1579 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1581 size_t len
= wxStrlen(pszFileName
);
1583 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1586 // find a file in a list of directories, returns false if not found
1587 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1589 // we assume that it's not empty
1590 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1591 _T("empty file name in wxFindFileInPath"));
1593 // skip path separator in the beginning of the file name if present
1594 if ( wxIsPathSeparator(*pszFile
) )
1597 // copy the path (strtok will modify it)
1598 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1599 wxStrcpy(szPath
, pszPath
);
1602 wxChar
*pc
, *save_ptr
;
1603 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1605 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1607 // search for the file in this directory
1609 if ( !wxEndsWithPathSeparator(pc
) )
1610 strFile
+= wxFILE_SEP_PATH
;
1613 if ( wxFileExists(strFile
) ) {
1619 // suppress warning about unused variable save_ptr when wxStrtok() is a
1620 // macro which throws away its third argument
1625 return pc
!= NULL
; // if true => we breaked from the loop
1628 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1633 // it can be empty, but it shouldn't be NULL
1634 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1636 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1639 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1642 if ( !wxFileName(filename
).GetTimes(NULL
, &mtime
, NULL
) )
1645 return mtime
.GetTicks();
1649 // Parses the filterStr, returning the number of filters.
1650 // Returns 0 if none or if there's a problem.
1651 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1653 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
,
1654 wxArrayString
& descriptions
,
1655 wxArrayString
& filters
)
1657 descriptions
.Clear();
1660 wxString
str(filterStr
);
1662 wxString description
, filter
;
1664 while( pos
!= wxNOT_FOUND
)
1666 pos
= str
.Find(wxT('|'));
1667 if ( pos
== wxNOT_FOUND
)
1669 // if there are no '|'s at all in the string just take the entire
1670 // string as filter and make description empty for later autocompletion
1671 if ( filters
.IsEmpty() )
1673 descriptions
.Add(wxEmptyString
);
1674 filters
.Add(filterStr
);
1678 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1684 description
= str
.Left(pos
);
1685 str
= str
.Mid(pos
+ 1);
1686 pos
= str
.Find(wxT('|'));
1687 if ( pos
== wxNOT_FOUND
)
1693 filter
= str
.Left(pos
);
1694 str
= str
.Mid(pos
+ 1);
1697 descriptions
.Add(description
);
1698 filters
.Add(filter
);
1701 #if defined(__WXMOTIF__)
1702 // split it so there is one wildcard per entry
1703 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1705 pos
= filters
[i
].Find(wxT(';'));
1706 if (pos
!= wxNOT_FOUND
)
1708 // first split only filters
1709 descriptions
.Insert(descriptions
[i
],i
+1);
1710 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1711 filters
[i
]=filters
[i
].Left(pos
);
1713 // autoreplace new filter in description with pattern:
1714 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1715 // cause split into:
1716 // C/C++ Files(*.cpp)|*.cpp
1717 // C/C++ Files(*.c;*.h)|*.c;*.h
1718 // and next iteration cause another split into:
1719 // C/C++ Files(*.cpp)|*.cpp
1720 // C/C++ Files(*.c)|*.c
1721 // C/C++ Files(*.h)|*.h
1722 for ( size_t k
=i
;k
<i
+2;k
++ )
1724 pos
= descriptions
[k
].Find(filters
[k
]);
1725 if (pos
!= wxNOT_FOUND
)
1727 wxString before
= descriptions
[k
].Left(pos
);
1728 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1729 pos
= before
.Find(_T('('),true);
1730 if (pos
>before
.Find(_T(')'),true))
1732 before
= before
.Left(pos
+1);
1733 before
<< filters
[k
];
1734 pos
= after
.Find(_T(')'));
1735 int pos1
= after
.Find(_T('('));
1736 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1738 before
<< after
.Mid(pos
);
1739 descriptions
[k
] = before
;
1749 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1751 if ( descriptions
[j
].empty() && !filters
[j
].empty() )
1753 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1757 return filters
.GetCount();
1761 //------------------------------------------------------------------------
1762 // wild character routines
1763 //------------------------------------------------------------------------
1765 bool wxIsWild( const wxString
& pattern
)
1767 wxString tmp
= pattern
;
1768 wxChar
*pat
= WXSTRINGCAST(tmp
);
1773 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1784 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1786 * The match procedure is public domain code (from ircII's reg.c)
1787 * but modified to suit our tastes (RN: No "%" syntax I guess)
1790 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1794 /* Match if both are empty. */
1798 const wxChar
*m
= pat
.c_str(),
1806 if (dot_special
&& (*n
== wxT('.')))
1808 /* Never match so that hidden Unix files
1809 * are never found. */
1822 else if (*m
== wxT('?'))
1830 if (*m
== wxT('\\'))
1833 /* Quoting "nothing" is a bad thing */
1840 * If we are out of both strings or we just
1841 * saw a wildcard, then we can say we have a
1852 * We could check for *n == NULL at this point, but
1853 * since it's more common to have a character there,
1854 * check to see if they match first (m and n) and
1855 * then if they don't match, THEN we can check for
1871 * If there are no more characters in the
1872 * string, but we still need to find another
1873 * character (*m != NULL), then it will be
1874 * impossible to match it
1892 // Return the type of an open file
1894 // Some file types on some platforms seem seekable but in fact are not.
1895 // The main use of this function is to allow such cases to be detected
1896 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1898 // This is important for the archive streams, which benefit greatly from
1899 // being able to seek on a stream, but which will produce corrupt archives
1900 // if they unknowingly seek on a non-seekable stream.
1902 // wxFILE_KIND_DISK is a good catch all return value, since other values
1903 // disable features of the archive streams. Some other value must be returned
1904 // for a file type that appears seekable but isn't.
1907 // * Pipes on Windows
1908 // * Files on VMS with a record format other than StreamLF
1910 wxFileKind
wxGetFileKind(int fd
)
1912 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1913 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1915 case FILE_TYPE_CHAR
:
1916 return wxFILE_KIND_TERMINAL
;
1917 case FILE_TYPE_DISK
:
1918 return wxFILE_KIND_DISK
;
1919 case FILE_TYPE_PIPE
:
1920 return wxFILE_KIND_PIPE
;
1923 return wxFILE_KIND_UNKNOWN
;
1925 #elif defined(__UNIX__)
1927 return wxFILE_KIND_TERMINAL
;
1932 if (S_ISFIFO(st
.st_mode
))
1933 return wxFILE_KIND_PIPE
;
1934 if (!S_ISREG(st
.st_mode
))
1935 return wxFILE_KIND_UNKNOWN
;
1937 #if defined(__VMS__)
1938 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1939 return wxFILE_KIND_UNKNOWN
;
1942 return wxFILE_KIND_DISK
;
1945 #define wxFILEKIND_STUB
1947 return wxFILE_KIND_DISK
;
1951 wxFileKind
wxGetFileKind(FILE *fp
)
1953 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1954 // Should be fixed in version 1.4.
1955 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1957 return wxFILE_KIND_DISK
;
1959 return fp
? wxGetFileKind(fileno(fp
)) : wxFILE_KIND_UNKNOWN
;
1964 #pragma warning(default:4706) // assignment within conditional expression