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
59 // No, Cygwin doesn't appear to have fnmatch.h after all.
60 #if defined(HAVE_FNMATCH_H)
65 #include "wx/msw/private.h"
66 #include "wx/msw/mslu.h"
68 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
70 // note that it must be included after <windows.h>
73 #include <sys/cygwin.h>
75 #endif // __GNUWIN32__
77 // io.h is needed for _get_osfhandle()
78 // Already included by filefn.h for many Windows compilers
79 #if defined __MWERKS__ || defined __CYGWIN__
88 // TODO: Borland probably has _wgetcwd as well?
93 // ----------------------------------------------------------------------------
95 // ----------------------------------------------------------------------------
98 #define _MAXPATHLEN 1024
102 # include "MoreFilesX.h"
105 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 // MT-FIXME: get rid of this horror and all code using it
110 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
112 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
114 // VisualAge C++ V4.0 cannot have any external linkage const decs
115 // in headers included by more than one primary source
117 const int wxInvalidOffset
= -1;
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
124 // we need to translate Mac filenames before passing them to OS functions
125 #define OS_FILENAME(s) (s.fn_str())
127 // ============================================================================
129 // ============================================================================
131 #ifdef wxNEED_WX_UNISTD_H
133 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
135 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
138 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
140 return access( wxConvFile
.cWX2MB( pathname
), mode
);
143 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
145 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
149 // wxNEED_WX_UNISTD_H
151 // ----------------------------------------------------------------------------
153 // ----------------------------------------------------------------------------
155 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
157 static inline wxChar
* MYcopystring(const wxString
& s
)
159 wxChar
* copy
= new wxChar
[s
.length() + 1];
160 return wxStrcpy(copy
, s
.c_str());
163 static inline wxChar
* MYcopystring(const wxChar
* s
)
165 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
166 return wxStrcpy(copy
, s
);
169 void wxPathList::Add (const wxString
& path
)
171 wxStringList::Add (WXSTRINGCAST path
);
174 // Add paths e.g. from the PATH environment variable
175 void wxPathList::AddEnvList (const wxString
& envVariable
)
177 // No environment variables on WinCE
179 static const wxChar PATH_TOKS
[] =
180 #if defined(__WINDOWS__) || defined(__OS2__)
182 The space has been removed from the tokenizers, otherwise a
183 path such as "C:\Program Files" would be split into 2 paths:
184 "C:\Program" and "Files"
186 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
187 wxT(";"); // Don't seperate with colon in DOS (used for drive)
192 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
195 wxChar
*s
= MYcopystring (val
);
196 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
203 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
211 // suppress warning about unused variable save_ptr when wxStrtok() is a
212 // macro which throws away its third argument
220 // Given a full filename (with path), ensure that that file can
221 // be accessed again USING FILENAME ONLY by adding the path
222 // to the list if not already there.
223 void wxPathList::EnsureFileAccessible (const wxString
& path
)
225 wxString
path_only(wxPathOnly(path
));
226 if ( !path_only
.empty() )
228 if ( !Member(path_only
) )
233 bool wxPathList::Member (const wxString
& path
)
235 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
237 wxString
path2( node
->GetData() );
239 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined(__WXMAC__)
241 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
243 // Case sensitive File System
244 path
.CompareTo (path2
) == 0
252 wxString
wxPathList::FindValidPath (const wxString
& file
)
254 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
255 return wxString(wxFileFunctionsBuffer
);
257 wxChar buf
[_MAXPATHLEN
];
258 wxStrcpy(buf
, wxFileFunctionsBuffer
);
260 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
262 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
264 const wxChar
*path
= node
->GetData();
265 wxStrcpy (wxFileFunctionsBuffer
, path
);
266 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
267 if (ch
!= wxT('\\') && ch
!= wxT('/'))
268 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
269 wxStrcat (wxFileFunctionsBuffer
, filename
);
271 wxUnix2DosFilename (wxFileFunctionsBuffer
);
273 if (wxFileExists (wxFileFunctionsBuffer
))
275 return wxString(wxFileFunctionsBuffer
); // Found!
279 return wxEmptyString
; // Not found
282 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
284 wxString f
= FindValidPath(file
);
285 if ( f
.empty() || wxIsAbsolutePath(f
) )
289 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
291 if ( !wxEndsWithPathSeparator(buf
) )
293 buf
+= wxFILE_SEP_PATH
;
301 wxFileExists (const wxString
& filename
)
303 #if defined(__WXPALMOS__)
305 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
306 // we must use GetFileAttributes() instead of the ANSI C functions because
307 // it can cope with network (UNC) paths unlike them
308 DWORD ret
= ::GetFileAttributes(filename
);
310 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
313 #ifndef wxNEED_WX_UNISTD_H
314 return wxStat( filename
.fn_str() , &st
) == 0 && (st
.st_mode
& S_IFREG
);
316 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
318 #endif // __WIN32__/!__WIN32__
322 wxIsAbsolutePath (const wxString
& filename
)
324 if (!filename
.empty())
326 #if defined(__WXMAC__) && !defined(__DARWIN__)
327 // Classic or Carbon CodeWarrior like
328 // Carbon with Apple DevTools is Unix like
330 // This seems wrong to me, but there is no fix. since
331 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
332 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
333 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
336 // Unix like or Windows
337 if (filename
[0] == wxT('/'))
341 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
344 #if defined(__WINDOWS__) || defined(__OS2__)
346 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
354 * Strip off any extension (dot something) from end of file,
355 * IF one exists. Inserts zero into buffer.
359 void wxStripExtension(wxChar
*buffer
)
361 int len
= wxStrlen(buffer
);
365 if (buffer
[i
] == wxT('.'))
374 void wxStripExtension(wxString
& buffer
)
376 //RN: Be careful about the handling the case where
377 //buffer.Length() == 0
378 for(size_t i
= buffer
.Length() - 1; i
!= wxString::npos
; --i
)
380 if (buffer
.GetChar(i
) == wxT('.'))
382 buffer
= buffer
.Left(i
);
388 // Destructive removal of /./ and /../ stuff
389 wxChar
*wxRealPath (wxChar
*path
)
392 static const wxChar SEP
= wxT('\\');
393 wxUnix2DosFilename(path
);
395 static const wxChar SEP
= wxT('/');
397 if (path
[0] && path
[1]) {
398 /* MATTHEW: special case "/./x" */
400 if (path
[2] == SEP
&& path
[1] == wxT('.'))
408 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
411 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
416 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
417 && (q
- 1 <= path
|| q
[-1] != SEP
))
420 if (path
[0] == wxT('\0'))
425 #if defined(__WXMSW__) || defined(__OS2__)
426 /* Check that path[2] is NULL! */
427 else if (path
[1] == wxT(':') && !path
[2])
436 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
445 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
447 if (filename
.empty())
448 return (wxChar
*) NULL
;
450 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
451 wxChar buf
[_MAXPATHLEN
];
453 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
454 wxChar ch
= buf
[wxStrlen(buf
) - 1];
456 if (ch
!= wxT('\\') && ch
!= wxT('/'))
457 wxStrcat(buf
, wxT("\\"));
460 wxStrcat(buf
, wxT("/"));
462 wxStrcat(buf
, wxFileFunctionsBuffer
);
463 return MYcopystring( wxRealPath(buf
) );
465 return MYcopystring( wxFileFunctionsBuffer
);
471 ~user/ => user's home dir
472 If the environment variable a = "foo" and b = "bar" then:
489 /* input name in name, pathname output to buf. */
491 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
493 register wxChar
*d
, *s
, *nm
;
494 wxChar lnm
[_MAXPATHLEN
];
497 // Some compilers don't like this line.
498 // const wxChar trimchars[] = wxT("\n \t");
501 trimchars
[0] = wxT('\n');
502 trimchars
[1] = wxT(' ');
503 trimchars
[2] = wxT('\t');
507 const wxChar SEP
= wxT('\\');
509 const wxChar SEP
= wxT('/');
512 if (name
== NULL
|| *name
== wxT('\0'))
514 nm
= MYcopystring(name
); // Make a scratch copy
517 /* Skip leading whitespace and cr */
518 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
520 /* And strip off trailing whitespace and cr */
521 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
522 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
530 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
533 /* Expand inline environment variables */
551 while ((*d
++ = *s
) != 0) {
553 if (*s
== wxT('\\')) {
554 if ((*(d
- 1) = *++s
)) {
562 // No env variables on WinCE
565 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
567 if (*s
++ == wxT('$'))
570 register wxChar
*start
= d
;
571 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
572 register wxChar
*value
;
573 while ((*d
++ = *s
) != 0)
574 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
579 value
= wxGetenv(braces
? start
+ 1 : start
);
581 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
595 /* Expand ~ and ~user */
597 if (nm
[0] == wxT('~') && !q
)
600 if (nm
[1] == SEP
|| nm
[1] == 0)
602 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
603 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
608 { /* ~user/filename */
609 register wxChar
*nnm
;
610 register wxChar
*home
;
611 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
615 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
616 was_sep
= (*s
== SEP
);
617 nnm
= *s
? s
+ 1 : s
;
619 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
620 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
621 if (was_sep
) /* replace only if it was there: */
632 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
634 while (wxT('\0') != (*d
++ = *s
++))
637 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
641 while ((*d
++ = *s
++) != 0)
645 delete[] nm_tmp
; // clean up alloc
646 /* Now clean up the buffer */
647 return wxRealPath(buf
);
650 /* Contract Paths to be build upon an environment variable
653 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
655 The call wxExpandPath can convert these back!
658 wxContractPath (const wxString
& filename
, const wxString
& envname
, 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
!= WXSTRINGCAST NULL
&& (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
)
959 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
962 FILE *fp1
wxDUMMY_INITIALIZE(NULL
);
965 // Open the inputs and outputs
966 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
967 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
968 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
980 while ((ch
= getc (fp1
)) != EOF
)
981 (void) putc (ch
, fp3
);
984 while ((ch
= getc (fp2
)) != EOF
)
985 (void) putc (ch
, fp3
);
989 bool result
= wxRenameFile(outfile
, file3
);
995 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
997 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
998 // CopyFile() copies file attributes and modification time too, so use it
999 // instead of our code if available
1001 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1002 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1004 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1005 file1
.c_str(), file2
.c_str());
1009 #elif defined(__OS2__)
1010 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1012 #elif defined(__PALMOS__)
1013 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1018 // get permissions of file1
1019 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1021 // the file probably doesn't exist or we haven't the rights to read
1023 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1028 // open file1 for reading
1029 wxFile
fileIn(file1
, wxFile::read
);
1030 if ( !fileIn
.IsOpened() )
1033 // remove file2, if it exists. This is needed for creating
1034 // file2 with the correct permissions in the next step
1035 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1037 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1042 // reset the umask as we want to create the file with exactly the same
1043 // permissions as the original one
1046 // create file2 with the same permissions than file1 and open it for
1050 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1053 // copy contents of file1 to file2
1058 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1059 if ( fileIn
.Error() )
1066 if ( fileOut
.Write(buf
, count
) < count
)
1070 // we can expect fileIn to be closed successfully, but we should ensure
1071 // that fileOut was closed as some write errors (disk full) might not be
1072 // detected before doing this
1073 if ( !fileIn
.Close() || !fileOut
.Close() )
1076 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1077 // no chmod in VA. Should be some permission API for HPFS386 partitions
1079 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1081 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1085 #endif // OS/2 || Mac
1086 #endif // __WXMSW__ && __WIN32__
1092 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1094 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1095 // Normal system call
1096 if ( wxRename (file1
, file2
) == 0 )
1101 if (wxCopyFile(file1
, file2
)) {
1102 wxRemoveFile(file1
);
1109 bool wxRemoveFile(const wxString
& file
)
1111 #if defined(__VISUALC__) \
1112 || defined(__BORLANDC__) \
1113 || defined(__WATCOMC__) \
1114 || defined(__DMC__) \
1115 || defined(__GNUWIN32__) \
1116 || (defined(__MWERKS__) && defined(__MSL__))
1117 int res
= wxRemove(file
);
1118 #elif defined(__WXMAC__)
1119 int res
= unlink(wxFNCONV(file
));
1120 #elif defined(__WXPALMOS__)
1122 // TODO with VFSFileDelete()
1124 int res
= unlink(OS_FILENAME(file
));
1130 bool wxMkdir(const wxString
& dir
, int perm
)
1132 #if defined(__WXPALMOS__)
1134 #elif defined(__WXMAC__) && !defined(__UNIX__)
1135 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1137 const wxChar
*dirname
= dir
.c_str();
1139 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1140 // for the GNU compiler
1141 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1144 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1146 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1148 #elif defined(__OS2__)
1149 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1150 #elif defined(__DOS__)
1151 #if defined(__WATCOMC__)
1153 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1154 #elif defined(__DJGPP__)
1155 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1157 #error "Unsupported DOS compiler!"
1159 #else // !MSW, !DOS and !OS/2 VAC++
1162 if ( !CreateDirectory(dirname
, NULL
) )
1164 if ( wxMkDir(dir
.fn_str()) != 0 )
1168 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1177 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1179 #if defined(__VMS__)
1180 return false; //to be changed since rmdir exists in VMS7.x
1181 #elif defined(__OS2__)
1182 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1183 #elif defined(__WXWINCE__)
1184 return (CreateDirectory(dir
, NULL
) != 0);
1185 #elif defined(__WXPALMOS__)
1186 // TODO with VFSFileRename()
1189 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1193 // does the path exists? (may have or not '/' or '\\' at the end)
1194 bool wxPathExists(const wxChar
*pszPathName
)
1196 wxString
strPath(pszPathName
);
1198 #if defined(__WINDOWS__) || defined(__OS2__)
1199 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1200 // so remove all trailing backslashes from the path - but don't do this for
1201 // the pathes "d:\" (which are different from "d:") nor for just "\"
1202 while ( wxEndsWithPathSeparator(strPath
) )
1204 size_t len
= strPath
.length();
1205 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1208 strPath
.Truncate(len
- 1);
1210 #endif // __WINDOWS__
1213 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1214 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1218 #if defined(__WXPALMOS__)
1220 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1221 // stat() can't cope with network paths
1222 DWORD ret
= ::GetFileAttributes(strPath
);
1224 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1228 #ifndef __VISAGECPP__
1229 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1231 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1232 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1235 #endif // __WIN32__/!__WIN32__
1238 // Get a temporary filename, opening and closing the file.
1239 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1242 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1243 if ( filename
.empty() )
1247 wxStrcpy(buf
, filename
);
1249 buf
= MYcopystring(filename
);
1253 // wxFileName::CreateTempFileName needs wxFile class enabled
1258 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1260 buf
= wxGetTempFileName(prefix
);
1262 return !buf
.empty();
1265 // Get first file name matching given wild card.
1267 static wxDir
*gs_dir
= NULL
;
1268 static wxString gs_dirPath
;
1270 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1272 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1273 if ( gs_dirPath
.empty() )
1274 gs_dirPath
= wxT(".");
1275 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1276 gs_dirPath
<< wxFILE_SEP_PATH
;
1280 gs_dir
= new wxDir(gs_dirPath
);
1282 if ( !gs_dir
->IsOpened() )
1284 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1285 return wxEmptyString
;
1291 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1292 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1293 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1297 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1298 if ( result
.empty() )
1304 return gs_dirPath
+ result
;
1307 wxString
wxFindNextFile()
1309 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1312 gs_dir
->GetNext(&result
);
1314 if ( result
.empty() )
1320 return gs_dirPath
+ result
;
1324 // Get current working directory.
1325 // If buf is NULL, allocates space using new, else
1327 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1329 #if defined(__WXPALMOS__)
1332 #elif defined(__WXWINCE__)
1337 buf
= new wxChar
[sz
+ 1];
1340 bool ok
wxDUMMY_INITIALIZE(false);
1342 // for the compilers which have Unicode version of _getcwd(), call it
1343 // directly, for the others call the ANSI version and do the translation
1346 #else // wxUSE_UNICODE
1347 bool needsANSI
= true;
1349 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1350 // This is not legal code as the compiler
1351 // is allowed destroy the wxCharBuffer.
1352 // wxCharBuffer c_buffer(sz);
1353 // char *cbuf = (char*)(const char*)c_buffer;
1354 char cbuf
[_MAXPATHLEN
];
1358 #if wxUSE_UNICODE_MSLU
1359 if ( wxGetOsVersion() != wxWIN95
)
1361 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1364 ok
= _wgetcwd(buf
, sz
) != NULL
;
1370 #endif // wxUSE_UNICODE
1372 #if defined(_MSC_VER) || defined(__MINGW32__)
1373 ok
= _getcwd(cbuf
, sz
) != NULL
;
1374 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1376 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1378 wxString
res( lbuf
, *wxConvCurrent
) ;
1379 wxStrcpy( buf
, res
) ;
1384 #elif defined(__OS2__)
1386 ULONG ulDriveNum
= 0;
1387 ULONG ulDriveMap
= 0;
1388 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1393 rc
= ::DosQueryCurrentDir( 0 // current drive
1397 cbuf
[0] = 'A' + (ulDriveNum
- 1);
1402 #else // !Win32/VC++ !Mac !OS2
1403 ok
= getcwd(cbuf
, sz
) != NULL
;
1406 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1407 // finally convert the result to Unicode if needed
1408 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1409 #endif // wxUSE_UNICODE
1414 wxLogSysError(_("Failed to get the working directory"));
1416 // VZ: the old code used to return "." on error which didn't make any
1417 // sense at all to me - empty string is a better error indicator
1418 // (NULL might be even better but I'm afraid this could lead to
1419 // problems with the old code assuming the return is never NULL)
1422 else // ok, but we might need to massage the path into the right format
1425 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1426 // with / deliminers. We don't like that.
1427 for (wxChar
*ch
= buf
; *ch
; ch
++)
1429 if (*ch
== wxT('/'))
1434 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1435 // he needs Unix as opposed to Win32 pathnames
1436 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1437 // another example of DOS/Unix mix (Cygwin)
1438 wxString pathUnix
= buf
;
1439 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1440 #endif // __CYGWIN__
1455 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1456 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1457 wxString
str( buffer
);
1463 bool wxSetWorkingDirectory(const wxString
& d
)
1465 #if defined(__OS2__)
1466 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1467 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1468 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1469 #elif defined(__WINDOWS__)
1473 // No equivalent in WinCE
1476 return (bool)(SetCurrentDirectory(d
) != 0);
1479 // Must change drive, too.
1480 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1483 wxChar firstChar
= d
[0];
1487 firstChar
= firstChar
- 32;
1489 // To a drive number
1490 unsigned int driveNo
= firstChar
- 64;
1493 unsigned int noDrives
;
1494 _dos_setdrive(driveNo
, &noDrives
);
1497 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1505 // Get the OS directory if appropriate (such as the Windows directory).
1506 // On non-Windows platform, probably just return the empty string.
1507 wxString
wxGetOSDirectory()
1510 return wxString(wxT("\\Windows"));
1511 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1513 GetWindowsDirectory(buf
, 256);
1514 return wxString(buf
);
1515 #elif defined(__WXMAC__)
1516 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1518 return wxEmptyString
;
1522 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1524 size_t len
= wxStrlen(pszFileName
);
1526 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1529 // find a file in a list of directories, returns false if not found
1530 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1532 // we assume that it's not empty
1533 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1534 _T("empty file name in wxFindFileInPath"));
1536 // skip path separator in the beginning of the file name if present
1537 if ( wxIsPathSeparator(*pszFile
) )
1540 // copy the path (strtok will modify it)
1541 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1542 wxStrcpy(szPath
, pszPath
);
1545 wxChar
*pc
, *save_ptr
;
1546 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1548 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1550 // search for the file in this directory
1552 if ( !wxEndsWithPathSeparator(pc
) )
1553 strFile
+= wxFILE_SEP_PATH
;
1556 if ( wxFileExists(strFile
) ) {
1562 // suppress warning about unused variable save_ptr when wxStrtok() is a
1563 // macro which throws away its third argument
1568 return pc
!= NULL
; // if true => we breaked from the loop
1571 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1576 // it can be empty, but it shouldn't be NULL
1577 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1579 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1582 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1584 #if defined(__WXPALMOS__)
1586 #elif defined(__WXWINCE__)
1587 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1588 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1589 0, FILE_ATTRIBUTE_NORMAL
, 0);
1590 if (fileHandle
== INVALID_HANDLE_VALUE
)
1594 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1596 CloseHandle(fileHandle
);
1598 wxDateTime dateTime
;
1600 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1602 wxLogLastError(_T("FileTimeToLocalFileTime"));
1606 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1608 wxLogLastError(_T("FileTimeToSystemTime"));
1611 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1612 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1613 return dateTime
.GetTicks();
1620 wxStat( filename
, &buf
);
1622 return buf
.st_mtime
;
1627 // Parses the filterStr, returning the number of filters.
1628 // Returns 0 if none or if there's a problem.
1629 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1631 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
, wxArrayString
& descriptions
, wxArrayString
& filters
)
1633 descriptions
.Clear();
1636 wxString
str(filterStr
);
1638 wxString description
, filter
;
1640 while( pos
!= wxNOT_FOUND
)
1642 pos
= str
.Find(wxT('|'));
1643 if ( pos
== wxNOT_FOUND
)
1645 // if there are no '|'s at all in the string just take the entire
1646 // string as filter and make description empty for later autocompletion
1647 if ( filters
.IsEmpty() )
1649 descriptions
.Add(wxEmptyString
);
1650 filters
.Add(filterStr
);
1654 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1660 description
= str
.Left(pos
);
1661 str
= str
.Mid(pos
+ 1);
1662 pos
= str
.Find(wxT('|'));
1663 if ( pos
== wxNOT_FOUND
)
1669 filter
= str
.Left(pos
);
1670 str
= str
.Mid(pos
+ 1);
1673 descriptions
.Add(description
);
1674 filters
.Add(filter
);
1677 #if defined(__WXMOTIF__)
1678 // split it so there is one wildcard per entry
1679 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1681 pos
= filters
[i
].Find(wxT(';'));
1682 if (pos
!= wxNOT_FOUND
)
1684 // first split only filters
1685 descriptions
.Insert(descriptions
[i
],i
+1);
1686 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1687 filters
[i
]=filters
[i
].Left(pos
);
1689 // autoreplace new filter in description with pattern:
1690 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1691 // cause split into:
1692 // C/C++ Files(*.cpp)|*.cpp
1693 // C/C++ Files(*.c;*.h)|*.c;*.h
1694 // and next iteration cause another split into:
1695 // C/C++ Files(*.cpp)|*.cpp
1696 // C/C++ Files(*.c)|*.c
1697 // C/C++ Files(*.h)|*.h
1698 for ( size_t k
=i
;k
<i
+2;k
++ )
1700 pos
= descriptions
[k
].Find(filters
[k
]);
1701 if (pos
!= wxNOT_FOUND
)
1703 wxString before
= descriptions
[k
].Left(pos
);
1704 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1705 pos
= before
.Find(_T('('),true);
1706 if (pos
>before
.Find(_T(')'),true))
1708 before
= before
.Left(pos
+1);
1709 before
<< filters
[k
];
1710 pos
= after
.Find(_T(')'));
1711 int pos1
= after
.Find(_T('('));
1712 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1714 before
<< after
.Mid(pos
);
1715 descriptions
[k
] = before
;
1725 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1727 if ( descriptions
[j
] == wxEmptyString
&& filters
[j
] != wxEmptyString
)
1729 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1733 return filters
.GetCount();
1737 //------------------------------------------------------------------------
1738 // wild character routines
1739 //------------------------------------------------------------------------
1741 bool wxIsWild( const wxString
& pattern
)
1743 wxString tmp
= pattern
;
1744 wxChar
*pat
= WXSTRINGCAST(tmp
);
1749 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1760 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1762 * The match procedure is public domain code (from ircII's reg.c)
1765 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1769 /* Match if both are empty. */
1773 const wxChar
*m
= pat
.c_str(),
1784 if (dot_special
&& (*n
== wxT('.')))
1786 /* Never match so that hidden Unix files
1787 * are never found. */
1801 else if (*m
== wxT('?'))
1809 if (*m
== wxT('\\'))
1812 /* Quoting "nothing" is a bad thing */
1819 * If we are out of both strings or we just
1820 * saw a wildcard, then we can say we have a
1831 * We could check for *n == NULL at this point, but
1832 * since it's more common to have a character there,
1833 * check to see if they match first (m and n) and
1834 * then if they don't match, THEN we can check for
1852 * If there are no more characters in the
1853 * string, but we still need to find another
1854 * character (*m != NULL), then it will be
1855 * impossible to match it
1862 if (*np
== wxT(' '))
1886 // Return the type of an open file
1888 // Some file types on some platforms seem seekable but in fact are not.
1889 // The main use of this function is to allow such cases to be detected
1890 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1892 // This is important for the archive streams, which benefit greatly from
1893 // being able to seek on a stream, but which will produce corrupt archives
1894 // if they unknowingly seek on a non-seekable stream.
1896 // wxFILE_KIND_DISK is a good catch all return value, since other values
1897 // disable features of the archive streams. Some other value must be returned
1898 // for a file type that appears seekable but isn't.
1901 // * Pipes on Windows
1902 // * Files on VMS with a record format other than StreamLF
1904 wxFileKind
wxGetFileKind(int fd
)
1906 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1907 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1909 case FILE_TYPE_CHAR
:
1910 return wxFILE_KIND_TERMINAL
;
1911 case FILE_TYPE_DISK
:
1912 return wxFILE_KIND_DISK
;
1913 case FILE_TYPE_PIPE
:
1914 return wxFILE_KIND_PIPE
;
1917 return wxFILE_KIND_UNKNOWN
;
1919 #elif defined(__UNIX__)
1921 return wxFILE_KIND_TERMINAL
;
1926 if (S_ISFIFO(st
.st_mode
))
1927 return wxFILE_KIND_PIPE
;
1928 if (!S_ISREG(st
.st_mode
))
1929 return wxFILE_KIND_UNKNOWN
;
1931 #if defined(__VMS__)
1932 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1933 return wxFILE_KIND_UNKNOWN
;
1936 return wxFILE_KIND_DISK
;
1940 return wxFILE_KIND_DISK
;
1945 #pragma warning(default:4706) // assignment within conditional expression