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__
83 extern "C" { long _get_osfhandle(int); }
91 // TODO: Borland probably has _wgetcwd as well?
96 // ----------------------------------------------------------------------------
98 // ----------------------------------------------------------------------------
101 #define _MAXPATHLEN 1024
105 # include "MoreFilesX.h"
108 // ----------------------------------------------------------------------------
110 // ----------------------------------------------------------------------------
112 // MT-FIXME: get rid of this horror and all code using it
113 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
115 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
117 // VisualAge C++ V4.0 cannot have any external linkage const decs
118 // in headers included by more than one primary source
120 const int wxInvalidOffset
= -1;
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 // we need to translate Mac filenames before passing them to OS functions
128 #define OS_FILENAME(s) (s.fn_str())
130 // ============================================================================
132 // ============================================================================
134 #ifdef wxNEED_WX_UNISTD_H
136 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
138 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
141 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
143 return access( wxConvFile
.cWX2MB( pathname
), mode
);
146 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
148 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
152 // wxNEED_WX_UNISTD_H
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
158 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
160 static inline wxChar
* MYcopystring(const wxString
& s
)
162 wxChar
* copy
= new wxChar
[s
.length() + 1];
163 return wxStrcpy(copy
, s
.c_str());
166 static inline wxChar
* MYcopystring(const wxChar
* s
)
168 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
169 return wxStrcpy(copy
, s
);
172 void wxPathList::Add (const wxString
& path
)
174 wxStringList::Add (WXSTRINGCAST path
);
177 // Add paths e.g. from the PATH environment variable
178 void wxPathList::AddEnvList (const wxString
& envVariable
)
180 // No environment variables on WinCE
182 static const wxChar PATH_TOKS
[] =
183 #if defined(__WINDOWS__) || defined(__OS2__)
185 The space has been removed from the tokenizers, otherwise a
186 path such as "C:\Program Files" would be split into 2 paths:
187 "C:\Program" and "Files"
189 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
190 wxT(";"); // Don't seperate with colon in DOS (used for drive)
196 if (wxGetEnv (WXSTRINGCAST envVariable
, &val
))
198 wxChar
*s
= MYcopystring (val
);
199 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
206 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
214 // suppress warning about unused variable save_ptr when wxStrtok() is a
215 // macro which throws away its third argument
221 wxUnusedVar(envVariable
);
222 #endif // !__WXWINCE__/__WXWINCE__
225 // Given a full filename (with path), ensure that that file can
226 // be accessed again USING FILENAME ONLY by adding the path
227 // to the list if not already there.
228 void wxPathList::EnsureFileAccessible (const wxString
& path
)
230 wxString
path_only(wxPathOnly(path
));
231 if ( !path_only
.empty() )
233 if ( !Member(path_only
) )
238 bool wxPathList::Member (const wxString
& path
)
240 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
242 wxString
path2( node
->GetData() );
244 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined(__WXMAC__)
246 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
248 // Case sensitive File System
249 path
.CompareTo (path2
) == 0
257 wxString
wxPathList::FindValidPath (const wxString
& file
)
259 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
260 return wxString(wxFileFunctionsBuffer
);
262 wxChar buf
[_MAXPATHLEN
];
263 wxStrcpy(buf
, wxFileFunctionsBuffer
);
265 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
267 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
269 const wxChar
*path
= node
->GetData();
270 wxStrcpy (wxFileFunctionsBuffer
, path
);
271 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
272 if (ch
!= wxT('\\') && ch
!= wxT('/'))
273 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
274 wxStrcat (wxFileFunctionsBuffer
, filename
);
276 wxUnix2DosFilename (wxFileFunctionsBuffer
);
278 if (wxFileExists (wxFileFunctionsBuffer
))
280 return wxString(wxFileFunctionsBuffer
); // Found!
284 return wxEmptyString
; // Not found
287 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
289 wxString f
= FindValidPath(file
);
290 if ( f
.empty() || wxIsAbsolutePath(f
) )
294 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
296 if ( !wxEndsWithPathSeparator(buf
) )
298 buf
+= wxFILE_SEP_PATH
;
306 wxFileExists (const wxString
& filename
)
308 #if defined(__WXPALMOS__)
310 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
311 // we must use GetFileAttributes() instead of the ANSI C functions because
312 // it can cope with network (UNC) paths unlike them
313 DWORD ret
= ::GetFileAttributes(filename
);
315 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
318 #ifndef wxNEED_WX_UNISTD_H
319 return wxStat( filename
.fn_str() , &st
) == 0 && (st
.st_mode
& S_IFREG
);
321 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
323 #endif // __WIN32__/!__WIN32__
327 wxIsAbsolutePath (const wxString
& filename
)
329 if (!filename
.empty())
331 #if defined(__WXMAC__) && !defined(__DARWIN__)
332 // Classic or Carbon CodeWarrior like
333 // Carbon with Apple DevTools is Unix like
335 // This seems wrong to me, but there is no fix. since
336 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
337 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
338 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
341 // Unix like or Windows
342 if (filename
[0] == wxT('/'))
346 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
349 #if defined(__WINDOWS__) || defined(__OS2__)
351 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
359 * Strip off any extension (dot something) from end of file,
360 * IF one exists. Inserts zero into buffer.
364 void wxStripExtension(wxChar
*buffer
)
366 int len
= wxStrlen(buffer
);
370 if (buffer
[i
] == wxT('.'))
379 void wxStripExtension(wxString
& buffer
)
381 //RN: Be careful about the handling the case where
382 //buffer.Length() == 0
383 for(size_t i
= buffer
.Length() - 1; i
!= wxString::npos
; --i
)
385 if (buffer
.GetChar(i
) == wxT('.'))
387 buffer
= buffer
.Left(i
);
393 // Destructive removal of /./ and /../ stuff
394 wxChar
*wxRealPath (wxChar
*path
)
397 static const wxChar SEP
= wxT('\\');
398 wxUnix2DosFilename(path
);
400 static const wxChar SEP
= wxT('/');
402 if (path
[0] && path
[1]) {
403 /* MATTHEW: special case "/./x" */
405 if (path
[2] == SEP
&& path
[1] == wxT('.'))
413 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
416 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
421 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
422 && (q
- 1 <= path
|| q
[-1] != SEP
))
425 if (path
[0] == wxT('\0'))
430 #if defined(__WXMSW__) || defined(__OS2__)
431 /* Check that path[2] is NULL! */
432 else if (path
[1] == wxT(':') && !path
[2])
441 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
450 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
452 if (filename
.empty())
453 return (wxChar
*) NULL
;
455 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
456 wxChar buf
[_MAXPATHLEN
];
458 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
459 wxChar ch
= buf
[wxStrlen(buf
) - 1];
461 if (ch
!= wxT('\\') && ch
!= wxT('/'))
462 wxStrcat(buf
, wxT("\\"));
465 wxStrcat(buf
, wxT("/"));
467 wxStrcat(buf
, wxFileFunctionsBuffer
);
468 return MYcopystring( wxRealPath(buf
) );
470 return MYcopystring( wxFileFunctionsBuffer
);
476 ~user/ => user's home dir
477 If the environment variable a = "foo" and b = "bar" then:
494 /* input name in name, pathname output to buf. */
496 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
498 register wxChar
*d
, *s
, *nm
;
499 wxChar lnm
[_MAXPATHLEN
];
502 // Some compilers don't like this line.
503 // const wxChar trimchars[] = wxT("\n \t");
506 trimchars
[0] = wxT('\n');
507 trimchars
[1] = wxT(' ');
508 trimchars
[2] = wxT('\t');
512 const wxChar SEP
= wxT('\\');
514 const wxChar SEP
= wxT('/');
517 if (name
== NULL
|| *name
== wxT('\0'))
519 nm
= MYcopystring(name
); // Make a scratch copy
522 /* Skip leading whitespace and cr */
523 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
525 /* And strip off trailing whitespace and cr */
526 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
527 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
535 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
538 /* Expand inline environment variables */
556 while ((*d
++ = *s
) != 0) {
558 if (*s
== wxT('\\')) {
559 if ((*(d
- 1) = *++s
)) {
567 // No env variables on WinCE
570 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
572 if (*s
++ == wxT('$'))
575 register wxChar
*start
= d
;
576 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
577 register wxChar
*value
;
578 while ((*d
++ = *s
) != 0)
579 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
584 value
= wxGetenv(braces
? start
+ 1 : start
);
586 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
600 /* Expand ~ and ~user */
602 if (nm
[0] == wxT('~') && !q
)
605 if (nm
[1] == SEP
|| nm
[1] == 0)
607 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
608 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
613 { /* ~user/filename */
614 register wxChar
*nnm
;
615 register wxChar
*home
;
616 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
620 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
621 was_sep
= (*s
== SEP
);
622 nnm
= *s
? s
+ 1 : s
;
624 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
625 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
626 if (was_sep
) /* replace only if it was there: */
637 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
639 while (wxT('\0') != (*d
++ = *s
++))
642 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
646 while ((*d
++ = *s
++) != 0)
650 delete[] nm_tmp
; // clean up alloc
651 /* Now clean up the buffer */
652 return wxRealPath(buf
);
655 /* Contract Paths to be build upon an environment variable
658 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
660 The call wxExpandPath can convert these back!
663 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
665 static wxChar dest
[_MAXPATHLEN
];
667 if (filename
.empty())
668 return (wxChar
*) NULL
;
670 wxStrcpy (dest
, WXSTRINGCAST filename
);
672 wxUnix2DosFilename(dest
);
675 // Handle environment
679 if (!envname
.empty() && (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
680 (tcp
= wxStrstr (dest
, val
)) != NULL
)
682 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
685 wxStrcpy (tcp
, WXSTRINGCAST envname
);
686 wxStrcat (tcp
, wxT("}"));
687 wxStrcat (tcp
, wxFileFunctionsBuffer
);
690 wxUnusedVar(envname
);
693 // Handle User's home (ignore root homes!)
694 val
= wxGetUserHome (user
);
698 const size_t len
= wxStrlen(val
);
702 if (wxStrncmp(dest
, val
, len
) == 0)
704 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
706 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
707 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
708 wxStrcpy (dest
, wxFileFunctionsBuffer
);
714 // Return just the filename, not the path (basename)
715 wxChar
*wxFileNameFromPath (wxChar
*path
)
718 wxString n
= wxFileNameFromPath(p
);
720 return path
+ p
.length() - n
.length();
723 wxString
wxFileNameFromPath (const wxString
& path
)
726 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
728 wxString fullname
= name
;
731 fullname
<< wxFILE_SEP_EXT
<< ext
;
737 // Return just the directory, or NULL if no directory
739 wxPathOnly (wxChar
*path
)
743 static wxChar buf
[_MAXPATHLEN
];
746 wxStrcpy (buf
, path
);
748 int l
= wxStrlen(path
);
751 // Search backward for a backward or forward slash
754 #if defined(__WXMAC__) && !defined(__DARWIN__)
755 // Classic or Carbon CodeWarrior like
756 // Carbon with Apple DevTools is Unix like
757 if (path
[i
] == wxT(':') )
763 // Unix like or Windows
764 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
771 if (path
[i
] == wxT(']'))
780 #if defined(__WXMSW__) || defined(__OS2__)
781 // Try Drive specifier
782 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
784 // A:junk --> A:. (since A:.\junk Not A:\junk)
791 return (wxChar
*) NULL
;
794 // Return just the directory, or NULL if no directory
795 wxString
wxPathOnly (const wxString
& path
)
799 wxChar buf
[_MAXPATHLEN
];
802 wxStrcpy (buf
, WXSTRINGCAST path
);
804 int l
= path
.Length();
807 // Search backward for a backward or forward slash
810 #if defined(__WXMAC__) && !defined(__DARWIN__)
811 // Classic or Carbon CodeWarrior like
812 // Carbon with Apple DevTools is Unix like
813 if (path
[i
] == wxT(':') )
816 return wxString(buf
);
819 // Unix like or Windows
820 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
822 // Don't return an empty string
826 return wxString(buf
);
830 if (path
[i
] == wxT(']'))
833 return wxString(buf
);
839 #if defined(__WXMSW__) || defined(__OS2__)
840 // Try Drive specifier
841 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
843 // A:junk --> A:. (since A:.\junk Not A:\junk)
846 return wxString(buf
);
850 return wxEmptyString
;
853 // Utility for converting delimiters in DOS filenames to UNIX style
854 // and back again - or we get nasty problems with delimiters.
855 // Also, convert to lower case, since case is significant in UNIX.
857 #if defined(__WXMAC__)
859 #if TARGET_API_MAC_OSX
860 #define kDefaultPathStyle kCFURLPOSIXPathStyle
862 #define kDefaultPathStyle kCFURLHFSPathStyle
865 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
868 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
869 if ( additionalPathComponent
)
871 CFURLRef parentURLRef
= fullURLRef
;
872 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
873 additionalPathComponent
,false);
874 CFRelease( parentURLRef
) ;
876 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
877 CFRelease( fullURLRef
) ;
878 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
881 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
883 OSStatus err
= noErr
;
884 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
887 if ( CFURLGetFSRef(url
, fsRef
) == false )
898 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
900 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
903 return wxMacCFStringHolder(cfname
).AsString() ;
906 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
909 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
911 return wxMacFSRefToPath( &fsRef
) ;
913 return wxEmptyString
;
916 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
918 OSStatus err
= noErr
;
920 wxMacPathToFSRef( path
, &fsRef
) ;
921 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
927 wxDos2UnixFilename (wxChar
*s
)
936 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
943 #if defined(__WXMSW__) || defined(__OS2__)
944 wxUnix2DosFilename (wxChar
*s
)
946 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
949 // Yes, I really mean this to happen under DOS only! JACS
950 #if defined(__WXMSW__) || defined(__OS2__)
961 // Concatenate two files to form third
963 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
966 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
969 FILE *fp1
wxDUMMY_INITIALIZE(NULL
);
972 // Open the inputs and outputs
973 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
974 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
975 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
987 while ((ch
= getc (fp1
)) != EOF
)
988 (void) putc (ch
, fp3
);
991 while ((ch
= getc (fp2
)) != EOF
)
992 (void) putc (ch
, fp3
);
996 bool result
= wxRenameFile(outfile
, file3
);
1002 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1004 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1005 // CopyFile() copies file attributes and modification time too, so use it
1006 // instead of our code if available
1008 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1009 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1011 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1012 file1
.c_str(), file2
.c_str());
1016 #elif defined(__OS2__)
1017 if ( ::DosCopy((PSZ
)file1
.c_str(), (PSZ
)file2
.c_str(), overwrite
? DCPY_EXISTING
: 0) != 0 )
1019 #elif defined(__PALMOS__)
1020 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1022 #elif wxUSE_FILE // !Win32
1025 // get permissions of file1
1026 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1028 // the file probably doesn't exist or we haven't the rights to read
1030 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1035 // open file1 for reading
1036 wxFile
fileIn(file1
, wxFile::read
);
1037 if ( !fileIn
.IsOpened() )
1040 // remove file2, if it exists. This is needed for creating
1041 // file2 with the correct permissions in the next step
1042 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1044 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1049 // reset the umask as we want to create the file with exactly the same
1050 // permissions as the original one
1053 // create file2 with the same permissions than file1 and open it for
1057 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1060 // copy contents of file1 to file2
1065 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1066 if ( fileIn
.Error() )
1073 if ( fileOut
.Write(buf
, count
) < count
)
1077 // we can expect fileIn to be closed successfully, but we should ensure
1078 // that fileOut was closed as some write errors (disk full) might not be
1079 // detected before doing this
1080 if ( !fileIn
.Close() || !fileOut
.Close() )
1083 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1084 // no chmod in VA. Should be some permission API for HPFS386 partitions
1086 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1088 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1092 #endif // OS/2 || Mac
1094 #else // !Win32 && ! wxUSE_FILE
1096 // impossible to simulate with wxWidgets API
1099 wxUnusedVar(overwrite
);
1102 #endif // __WXMSW__ && __WIN32__
1108 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1110 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1111 // Normal system call
1112 if ( wxRename (file1
, file2
) == 0 )
1117 if (wxCopyFile(file1
, file2
)) {
1118 wxRemoveFile(file1
);
1125 bool wxRemoveFile(const wxString
& file
)
1127 #if defined(__VISUALC__) \
1128 || defined(__BORLANDC__) \
1129 || defined(__WATCOMC__) \
1130 || defined(__DMC__) \
1131 || defined(__GNUWIN32__) \
1132 || (defined(__MWERKS__) && defined(__MSL__))
1133 int res
= wxRemove(file
);
1134 #elif defined(__WXMAC__)
1135 int res
= unlink(wxFNCONV(file
));
1136 #elif defined(__WXPALMOS__)
1138 // TODO with VFSFileDelete()
1140 int res
= unlink(OS_FILENAME(file
));
1146 bool wxMkdir(const wxString
& dir
, int perm
)
1148 #if defined(__WXPALMOS__)
1150 #elif defined(__WXMAC__) && !defined(__UNIX__)
1151 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1153 const wxChar
*dirname
= dir
.c_str();
1155 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1156 // for the GNU compiler
1157 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1160 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1162 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1164 #elif defined(__OS2__)
1165 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1166 #elif defined(__DOS__)
1167 #if defined(__WATCOMC__)
1169 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1170 #elif defined(__DJGPP__)
1171 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1173 #error "Unsupported DOS compiler!"
1175 #else // !MSW, !DOS and !OS/2 VAC++
1178 if ( !CreateDirectory(dirname
, NULL
) )
1180 if ( wxMkDir(dir
.fn_str()) != 0 )
1184 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1193 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1195 #if defined(__VMS__)
1196 return false; //to be changed since rmdir exists in VMS7.x
1197 #elif defined(__OS2__)
1198 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1199 #elif defined(__WXWINCE__)
1200 return (CreateDirectory(dir
, NULL
) != 0);
1201 #elif defined(__WXPALMOS__)
1202 // TODO with VFSFileRename()
1205 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1209 // does the path exists? (may have or not '/' or '\\' at the end)
1210 bool wxDirExists(const wxChar
*pszPathName
)
1212 wxString
strPath(pszPathName
);
1214 #if defined(__WINDOWS__) || defined(__OS2__)
1215 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1216 // so remove all trailing backslashes from the path - but don't do this for
1217 // the pathes "d:\" (which are different from "d:") nor for just "\"
1218 while ( wxEndsWithPathSeparator(strPath
) )
1220 size_t len
= strPath
.length();
1221 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1224 strPath
.Truncate(len
- 1);
1226 #endif // __WINDOWS__
1229 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1230 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1234 #if defined(__WXPALMOS__)
1236 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1237 // stat() can't cope with network paths
1238 DWORD ret
= ::GetFileAttributes(strPath
);
1240 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1241 #elif defined(__OS2__)
1242 return (::DosSetCurrentDir((PSZ
)(WXSTRINGCAST strPath
)));
1246 #ifndef __VISAGECPP__
1247 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1249 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1250 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1253 #endif // __WIN32__/!__WIN32__
1256 // Get a temporary filename, opening and closing the file.
1257 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1260 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1261 if ( filename
.empty() )
1265 wxStrcpy(buf
, filename
);
1267 buf
= MYcopystring(filename
);
1271 wxUnusedVar(prefix
);
1273 // wxFileName::CreateTempFileName needs wxFile class enabled
1278 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1280 buf
= wxGetTempFileName(prefix
);
1282 return !buf
.empty();
1285 // Get first file name matching given wild card.
1287 static wxDir
*gs_dir
= NULL
;
1288 static wxString gs_dirPath
;
1290 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1292 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1293 if ( gs_dirPath
.empty() )
1294 gs_dirPath
= wxT(".");
1295 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1296 gs_dirPath
<< wxFILE_SEP_PATH
;
1300 gs_dir
= new wxDir(gs_dirPath
);
1302 if ( !gs_dir
->IsOpened() )
1304 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1305 return wxEmptyString
;
1311 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1312 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1313 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1317 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1318 if ( result
.empty() )
1324 return gs_dirPath
+ result
;
1327 wxString
wxFindNextFile()
1329 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1332 gs_dir
->GetNext(&result
);
1334 if ( result
.empty() )
1340 return gs_dirPath
+ result
;
1344 // Get current working directory.
1345 // If buf is NULL, allocates space using new, else
1347 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1349 #if defined(__WXPALMOS__)
1352 #elif defined(__WXWINCE__)
1360 buf
= new wxChar
[sz
+ 1];
1363 bool ok
wxDUMMY_INITIALIZE(false);
1365 // for the compilers which have Unicode version of _getcwd(), call it
1366 // directly, for the others call the ANSI version and do the translation
1369 #else // wxUSE_UNICODE
1370 bool needsANSI
= true;
1372 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1373 // This is not legal code as the compiler
1374 // is allowed destroy the wxCharBuffer.
1375 // wxCharBuffer c_buffer(sz);
1376 // char *cbuf = (char*)(const char*)c_buffer;
1377 char cbuf
[_MAXPATHLEN
];
1381 #if wxUSE_UNICODE_MSLU
1382 if ( wxGetOsVersion() != wxWIN95
)
1384 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1387 ok
= _wgetcwd(buf
, sz
) != NULL
;
1393 #endif // wxUSE_UNICODE
1395 #if defined(_MSC_VER) || defined(__MINGW32__)
1396 ok
= _getcwd(cbuf
, sz
) != NULL
;
1397 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1399 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1401 wxString
res( lbuf
, *wxConvCurrent
) ;
1402 wxStrcpy( buf
, res
) ;
1407 #elif defined(__OS2__)
1409 ULONG ulDriveNum
= 0;
1410 ULONG ulDriveMap
= 0;
1411 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1416 rc
= ::DosQueryCurrentDir( 0 // current drive
1420 cbuf
[0] = 'A' + (ulDriveNum
- 1);
1425 #else // !Win32/VC++ !Mac !OS2
1426 ok
= getcwd(cbuf
, sz
) != NULL
;
1429 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1430 // finally convert the result to Unicode if needed
1431 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1432 #endif // wxUSE_UNICODE
1437 wxLogSysError(_("Failed to get the working directory"));
1439 // VZ: the old code used to return "." on error which didn't make any
1440 // sense at all to me - empty string is a better error indicator
1441 // (NULL might be even better but I'm afraid this could lead to
1442 // problems with the old code assuming the return is never NULL)
1445 else // ok, but we might need to massage the path into the right format
1448 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1449 // with / deliminers. We don't like that.
1450 for (wxChar
*ch
= buf
; *ch
; ch
++)
1452 if (*ch
== wxT('/'))
1457 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1458 // he needs Unix as opposed to Win32 pathnames
1459 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1460 // another example of DOS/Unix mix (Cygwin)
1461 wxString pathUnix
= buf
;
1462 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1463 #endif // __CYGWIN__
1478 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1479 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1480 wxString
str( buffer
);
1486 bool wxSetWorkingDirectory(const wxString
& d
)
1488 #if defined(__OS2__)
1489 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1490 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1491 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1492 #elif defined(__WINDOWS__)
1496 // No equivalent in WinCE
1500 return (bool)(SetCurrentDirectory(d
) != 0);
1503 // Must change drive, too.
1504 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1507 wxChar firstChar
= d
[0];
1511 firstChar
= firstChar
- 32;
1513 // To a drive number
1514 unsigned int driveNo
= firstChar
- 64;
1517 unsigned int noDrives
;
1518 _dos_setdrive(driveNo
, &noDrives
);
1521 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1529 // Get the OS directory if appropriate (such as the Windows directory).
1530 // On non-Windows platform, probably just return the empty string.
1531 wxString
wxGetOSDirectory()
1534 return wxString(wxT("\\Windows"));
1535 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1537 GetWindowsDirectory(buf
, 256);
1538 return wxString(buf
);
1539 #elif defined(__WXMAC__)
1540 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1542 return wxEmptyString
;
1546 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1548 size_t len
= wxStrlen(pszFileName
);
1550 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1553 // find a file in a list of directories, returns false if not found
1554 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1556 // we assume that it's not empty
1557 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1558 _T("empty file name in wxFindFileInPath"));
1560 // skip path separator in the beginning of the file name if present
1561 if ( wxIsPathSeparator(*pszFile
) )
1564 // copy the path (strtok will modify it)
1565 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1566 wxStrcpy(szPath
, pszPath
);
1569 wxChar
*pc
, *save_ptr
;
1570 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1572 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1574 // search for the file in this directory
1576 if ( !wxEndsWithPathSeparator(pc
) )
1577 strFile
+= wxFILE_SEP_PATH
;
1580 if ( wxFileExists(strFile
) ) {
1586 // suppress warning about unused variable save_ptr when wxStrtok() is a
1587 // macro which throws away its third argument
1592 return pc
!= NULL
; // if true => we breaked from the loop
1595 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1600 // it can be empty, but it shouldn't be NULL
1601 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1603 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1606 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1608 #if defined(__WXPALMOS__)
1610 #elif defined(__WXWINCE__)
1611 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1612 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1613 0, FILE_ATTRIBUTE_NORMAL
, 0);
1614 if (fileHandle
== INVALID_HANDLE_VALUE
)
1618 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1620 CloseHandle(fileHandle
);
1622 wxDateTime dateTime
;
1624 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1626 wxLogLastError(_T("FileTimeToLocalFileTime"));
1630 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1632 wxLogLastError(_T("FileTimeToSystemTime"));
1635 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1636 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1637 return dateTime
.GetTicks();
1644 wxStat( filename
, &buf
);
1646 return buf
.st_mtime
;
1651 // Parses the filterStr, returning the number of filters.
1652 // Returns 0 if none or if there's a problem.
1653 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1655 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
, wxArrayString
& descriptions
, 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)
1789 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1793 /* Match if both are empty. */
1797 const wxChar
*m
= pat
.c_str(),
1808 if (dot_special
&& (*n
== wxT('.')))
1810 /* Never match so that hidden Unix files
1811 * are never found. */
1825 else if (*m
== wxT('?'))
1833 if (*m
== wxT('\\'))
1836 /* Quoting "nothing" is a bad thing */
1843 * If we are out of both strings or we just
1844 * saw a wildcard, then we can say we have a
1855 * We could check for *n == NULL at this point, but
1856 * since it's more common to have a character there,
1857 * check to see if they match first (m and n) and
1858 * then if they don't match, THEN we can check for
1876 * If there are no more characters in the
1877 * string, but we still need to find another
1878 * character (*m != NULL), then it will be
1879 * impossible to match it
1886 if (*np
== wxT(' '))
1910 // Return the type of an open file
1912 // Some file types on some platforms seem seekable but in fact are not.
1913 // The main use of this function is to allow such cases to be detected
1914 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1916 // This is important for the archive streams, which benefit greatly from
1917 // being able to seek on a stream, but which will produce corrupt archives
1918 // if they unknowingly seek on a non-seekable stream.
1920 // wxFILE_KIND_DISK is a good catch all return value, since other values
1921 // disable features of the archive streams. Some other value must be returned
1922 // for a file type that appears seekable but isn't.
1925 // * Pipes on Windows
1926 // * Files on VMS with a record format other than StreamLF
1928 wxFileKind
wxGetFileKind(int fd
)
1930 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1931 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1933 case FILE_TYPE_CHAR
:
1934 return wxFILE_KIND_TERMINAL
;
1935 case FILE_TYPE_DISK
:
1936 return wxFILE_KIND_DISK
;
1937 case FILE_TYPE_PIPE
:
1938 return wxFILE_KIND_PIPE
;
1941 return wxFILE_KIND_UNKNOWN
;
1943 #elif defined(__UNIX__)
1945 return wxFILE_KIND_TERMINAL
;
1950 if (S_ISFIFO(st
.st_mode
))
1951 return wxFILE_KIND_PIPE
;
1952 if (!S_ISREG(st
.st_mode
))
1953 return wxFILE_KIND_UNKNOWN
;
1955 #if defined(__VMS__)
1956 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1957 return wxFILE_KIND_UNKNOWN
;
1960 return wxFILE_KIND_DISK
;
1963 #define wxFILEKIND_STUB
1965 return wxFILE_KIND_DISK
;
1969 wxFileKind
wxGetFileKind(FILE *fp
)
1971 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1972 // Should be fixed in version 1.4.
1973 #if defined(wxFILEKIND_STUB) || \
1974 (defined(__WATCOMC__) && __WATCOMC__ <= 1230 && defined(__SW_BR))
1976 return wxFILE_KIND_DISK
;
1978 return wxGetFileKind(fileno(fp
));
1983 #pragma warning(default:4706) // assignment within conditional expression