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/wrapwin.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__
82 // TODO: Borland probably has _wgetcwd as well?
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
92 #define _MAXPATHLEN 1024
96 # include "MoreFilesX.h"
99 // ----------------------------------------------------------------------------
101 // ----------------------------------------------------------------------------
103 // MT-FIXME: get rid of this horror and all code using it
104 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
106 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
108 // VisualAge C++ V4.0 cannot have any external linkage const decs
109 // in headers included by more than one primary source
111 const int wxInvalidOffset
= -1;
114 // ----------------------------------------------------------------------------
116 // ----------------------------------------------------------------------------
118 // we need to translate Mac filenames before passing them to OS functions
119 #define OS_FILENAME(s) (s.fn_str())
121 // ============================================================================
123 // ============================================================================
125 #ifdef wxNEED_WX_UNISTD_H
127 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
129 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
132 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
134 return access( wxConvFile
.cWX2MB( pathname
), mode
);
137 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
139 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
143 // wxNEED_WX_UNISTD_H
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
149 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
151 static inline wxChar
* MYcopystring(const wxString
& s
)
153 wxChar
* copy
= new wxChar
[s
.length() + 1];
154 return wxStrcpy(copy
, s
.c_str());
157 static inline wxChar
* MYcopystring(const wxChar
* s
)
159 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
160 return wxStrcpy(copy
, s
);
163 void wxPathList::Add (const wxString
& path
)
165 wxStringList::Add (WXSTRINGCAST path
);
168 // Add paths e.g. from the PATH environment variable
169 void wxPathList::AddEnvList (const wxString
& envVariable
)
171 // No environment variables on WinCE
173 static const wxChar PATH_TOKS
[] =
174 #if defined(__WINDOWS__) || defined(__OS2__)
176 The space has been removed from the tokenizers, otherwise a
177 path such as "C:\Program Files" would be split into 2 paths:
178 "C:\Program" and "Files"
180 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
181 wxT(";"); // Don't seperate with colon in DOS (used for drive)
186 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
189 wxChar
*s
= MYcopystring (val
);
190 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
197 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
205 // suppress warning about unused variable save_ptr when wxStrtok() is a
206 // macro which throws away its third argument
214 // Given a full filename (with path), ensure that that file can
215 // be accessed again USING FILENAME ONLY by adding the path
216 // to the list if not already there.
217 void wxPathList::EnsureFileAccessible (const wxString
& path
)
219 wxString
path_only(wxPathOnly(path
));
220 if ( !path_only
.empty() )
222 if ( !Member(path_only
) )
227 bool wxPathList::Member (const wxString
& path
)
229 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
231 wxString
path2( node
->GetData() );
233 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined (__WXMAC__)
235 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
237 // Case sensitive File System
238 path
.CompareTo (path2
) == 0
246 wxString
wxPathList::FindValidPath (const wxString
& file
)
248 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
249 return wxString(wxFileFunctionsBuffer
);
251 wxChar buf
[_MAXPATHLEN
];
252 wxStrcpy(buf
, wxFileFunctionsBuffer
);
254 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
256 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
258 const wxChar
*path
= node
->GetData();
259 wxStrcpy (wxFileFunctionsBuffer
, path
);
260 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
261 if (ch
!= wxT('\\') && ch
!= wxT('/'))
262 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
263 wxStrcat (wxFileFunctionsBuffer
, filename
);
265 wxUnix2DosFilename (wxFileFunctionsBuffer
);
267 if (wxFileExists (wxFileFunctionsBuffer
))
269 return wxString(wxFileFunctionsBuffer
); // Found!
273 return wxEmptyString
; // Not found
276 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
278 wxString f
= FindValidPath(file
);
279 if ( f
.empty() || wxIsAbsolutePath(f
) )
283 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
285 if ( !wxEndsWithPathSeparator(buf
) )
287 buf
+= wxFILE_SEP_PATH
;
295 wxFileExists (const wxString
& filename
)
297 // we must use GetFileAttributes() instead of the ANSI C functions because
298 // it can cope with network (UNC) paths unlike them
299 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
300 DWORD ret
= ::GetFileAttributes(filename
);
302 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
305 #ifndef wxNEED_WX_UNISTD_H
306 return wxStat( filename
.fn_str() , &st
) == 0 && (st
.st_mode
& S_IFREG
);
308 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
310 #endif // __WIN32__/!__WIN32__
314 wxIsAbsolutePath (const wxString
& filename
)
316 if (!filename
.empty())
318 #if defined(__WXMAC__) && !defined(__DARWIN__)
319 // Classic or Carbon CodeWarrior like
320 // Carbon with Apple DevTools is Unix like
322 // This seems wrong to me, but there is no fix. since
323 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
324 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
325 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
328 // Unix like or Windows
329 if (filename
[0] == wxT('/'))
333 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
336 #if defined(__WINDOWS__) || defined(__OS2__)
338 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
346 * Strip off any extension (dot something) from end of file,
347 * IF one exists. Inserts zero into buffer.
351 void wxStripExtension(wxChar
*buffer
)
353 int len
= wxStrlen(buffer
);
357 if (buffer
[i
] == wxT('.'))
366 void wxStripExtension(wxString
& buffer
)
368 //RN: Be careful about the handling the case where
369 //buffer.Length() == 0
370 for(size_t i
= buffer
.Length() - 1; i
!= wxString::npos
; --i
)
372 if (buffer
.GetChar(i
) == wxT('.'))
374 buffer
= buffer
.Left(i
);
380 // Destructive removal of /./ and /../ stuff
381 wxChar
*wxRealPath (wxChar
*path
)
384 static const wxChar SEP
= wxT('\\');
385 wxUnix2DosFilename(path
);
387 static const wxChar SEP
= wxT('/');
389 if (path
[0] && path
[1]) {
390 /* MATTHEW: special case "/./x" */
392 if (path
[2] == SEP
&& path
[1] == wxT('.'))
400 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
403 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
408 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
409 && (q
- 1 <= path
|| q
[-1] != SEP
))
412 if (path
[0] == wxT('\0'))
417 #if defined(__WXMSW__) || defined(__OS2__)
418 /* Check that path[2] is NULL! */
419 else if (path
[1] == wxT(':') && !path
[2])
428 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
437 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
439 if (filename
.empty())
440 return (wxChar
*) NULL
;
442 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
443 wxChar buf
[_MAXPATHLEN
];
445 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
446 wxChar ch
= buf
[wxStrlen(buf
) - 1];
448 if (ch
!= wxT('\\') && ch
!= wxT('/'))
449 wxStrcat(buf
, wxT("\\"));
452 wxStrcat(buf
, wxT("/"));
454 wxStrcat(buf
, wxFileFunctionsBuffer
);
455 return MYcopystring( wxRealPath(buf
) );
457 return MYcopystring( wxFileFunctionsBuffer
);
463 ~user/ => user's home dir
464 If the environment variable a = "foo" and b = "bar" then:
481 /* input name in name, pathname output to buf. */
483 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
485 register wxChar
*d
, *s
, *nm
;
486 wxChar lnm
[_MAXPATHLEN
];
489 // Some compilers don't like this line.
490 // const wxChar trimchars[] = wxT("\n \t");
493 trimchars
[0] = wxT('\n');
494 trimchars
[1] = wxT(' ');
495 trimchars
[2] = wxT('\t');
499 const wxChar SEP
= wxT('\\');
501 const wxChar SEP
= wxT('/');
504 if (name
== NULL
|| *name
== wxT('\0'))
506 nm
= MYcopystring(name
); // Make a scratch copy
509 /* Skip leading whitespace and cr */
510 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
512 /* And strip off trailing whitespace and cr */
513 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
514 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
522 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
525 /* Expand inline environment variables */
543 while ((*d
++ = *s
) != 0) {
545 if (*s
== wxT('\\')) {
546 if ((*(d
- 1) = *++s
)) {
554 // No env variables on WinCE
557 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
559 if (*s
++ == wxT('$'))
562 register wxChar
*start
= d
;
563 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
564 register wxChar
*value
;
565 while ((*d
++ = *s
) != 0)
566 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
571 value
= wxGetenv(braces
? start
+ 1 : start
);
573 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
587 /* Expand ~ and ~user */
589 if (nm
[0] == wxT('~') && !q
)
592 if (nm
[1] == SEP
|| nm
[1] == 0)
594 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
595 if ((s
= WXSTRINGCAST
wxGetUserHome(wxEmptyString
)) != NULL
) {
600 { /* ~user/filename */
601 register wxChar
*nnm
;
602 register wxChar
*home
;
603 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
607 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
608 was_sep
= (*s
== SEP
);
609 nnm
= *s
? s
+ 1 : s
;
611 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
612 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
613 if (was_sep
) /* replace only if it was there: */
624 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
626 while (wxT('\0') != (*d
++ = *s
++))
629 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
633 while ((*d
++ = *s
++) != 0)
637 delete[] nm_tmp
; // clean up alloc
638 /* Now clean up the buffer */
639 return wxRealPath(buf
);
642 /* Contract Paths to be build upon an environment variable
645 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
647 The call wxExpandPath can convert these back!
650 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
652 static wxChar dest
[_MAXPATHLEN
];
654 if (filename
.empty())
655 return (wxChar
*) NULL
;
657 wxStrcpy (dest
, WXSTRINGCAST filename
);
659 wxUnix2DosFilename(dest
);
662 // Handle environment
666 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
667 (tcp
= wxStrstr (dest
, val
)) != NULL
)
669 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
672 wxStrcpy (tcp
, WXSTRINGCAST envname
);
673 wxStrcat (tcp
, wxT("}"));
674 wxStrcat (tcp
, wxFileFunctionsBuffer
);
678 // Handle User's home (ignore root homes!)
679 val
= wxGetUserHome (user
);
683 const size_t len
= wxStrlen(val
);
687 if (wxStrncmp(dest
, val
, len
) == 0)
689 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
691 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
692 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
693 wxStrcpy (dest
, wxFileFunctionsBuffer
);
699 // Return just the filename, not the path (basename)
700 wxChar
*wxFileNameFromPath (wxChar
*path
)
703 wxString n
= wxFileNameFromPath(p
);
705 return path
+ p
.length() - n
.length();
708 wxString
wxFileNameFromPath (const wxString
& path
)
711 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
713 wxString fullname
= name
;
716 fullname
<< wxFILE_SEP_EXT
<< ext
;
722 // Return just the directory, or NULL if no directory
724 wxPathOnly (wxChar
*path
)
728 static wxChar buf
[_MAXPATHLEN
];
731 wxStrcpy (buf
, path
);
733 int l
= wxStrlen(path
);
736 // Search backward for a backward or forward slash
739 #if defined(__WXMAC__) && !defined(__DARWIN__)
740 // Classic or Carbon CodeWarrior like
741 // Carbon with Apple DevTools is Unix like
742 if (path
[i
] == wxT(':') )
748 // Unix like or Windows
749 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
756 if (path
[i
] == wxT(']'))
765 #if defined(__WXMSW__) || defined(__OS2__)
766 // Try Drive specifier
767 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
769 // A:junk --> A:. (since A:.\junk Not A:\junk)
776 return (wxChar
*) NULL
;
779 // Return just the directory, or NULL if no directory
780 wxString
wxPathOnly (const wxString
& path
)
784 wxChar buf
[_MAXPATHLEN
];
787 wxStrcpy (buf
, WXSTRINGCAST path
);
789 int l
= path
.Length();
792 // Search backward for a backward or forward slash
795 #if defined(__WXMAC__) && !defined(__DARWIN__)
796 // Classic or Carbon CodeWarrior like
797 // Carbon with Apple DevTools is Unix like
798 if (path
[i
] == wxT(':') )
801 return wxString(buf
);
804 // Unix like or Windows
805 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
807 // Don't return an empty string
811 return wxString(buf
);
815 if (path
[i
] == wxT(']'))
818 return wxString(buf
);
824 #if defined(__WXMSW__) || defined(__OS2__)
825 // Try Drive specifier
826 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
828 // A:junk --> A:. (since A:.\junk Not A:\junk)
831 return wxString(buf
);
835 return wxEmptyString
;
838 // Utility for converting delimiters in DOS filenames to UNIX style
839 // and back again - or we get nasty problems with delimiters.
840 // Also, convert to lower case, since case is significant in UNIX.
842 #if defined(__WXMAC__)
844 #if TARGET_API_MAC_OSX
845 #define kDefaultPathStyle kCFURLPOSIXPathStyle
847 #define kDefaultPathStyle kCFURLHFSPathStyle
850 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
853 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
854 if ( additionalPathComponent
)
856 CFURLRef parentURLRef
= fullURLRef
;
857 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
858 additionalPathComponent
,false);
859 CFRelease( parentURLRef
) ;
861 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
862 CFRelease( fullURLRef
) ;
863 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
866 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
868 OSStatus err
= noErr
;
869 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
872 if ( CFURLGetFSRef(url
, fsRef
) == false )
883 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
885 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
888 return wxMacCFStringHolder(cfname
).AsString() ;
891 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
894 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
896 return wxMacFSRefToPath( &fsRef
) ;
898 return wxEmptyString
;
901 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
903 OSStatus err
= noErr
;
905 wxMacPathToFSRef( path
, &fsRef
) ;
906 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
912 wxDos2UnixFilename (wxChar
*s
)
921 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
928 #if defined(__WXMSW__) || defined(__OS2__)
929 wxUnix2DosFilename (wxChar
*s
)
931 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
934 // Yes, I really mean this to happen under DOS only! JACS
935 #if defined(__WXMSW__) || defined(__OS2__)
946 // Concatenate two files to form third
948 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
951 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
954 FILE *fp1
wxDUMMY_INITIALIZE(NULL
);
957 // Open the inputs and outputs
958 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
959 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
960 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
972 while ((ch
= getc (fp1
)) != EOF
)
973 (void) putc (ch
, fp3
);
976 while ((ch
= getc (fp2
)) != EOF
)
977 (void) putc (ch
, fp3
);
981 bool result
= wxRenameFile(outfile
, file3
);
987 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
989 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
990 // CopyFile() copies file attributes and modification time too, so use it
991 // instead of our code if available
993 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
994 if ( !::CopyFile(file1
, file2
, !overwrite
) )
996 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
997 file1
.c_str(), file2
.c_str());
1001 #elif defined(__OS2__)
1002 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1007 // get permissions of file1
1008 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1010 // the file probably doesn't exist or we haven't the rights to read
1012 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1017 // open file1 for reading
1018 wxFile
fileIn(file1
, wxFile::read
);
1019 if ( !fileIn
.IsOpened() )
1022 // remove file2, if it exists. This is needed for creating
1023 // file2 with the correct permissions in the next step
1024 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1026 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1031 // reset the umask as we want to create the file with exactly the same
1032 // permissions as the original one
1035 // create file2 with the same permissions than file1 and open it for
1039 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1042 // copy contents of file1 to file2
1047 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1048 if ( fileIn
.Error() )
1055 if ( fileOut
.Write(buf
, count
) < count
)
1059 // we can expect fileIn to be closed successfully, but we should ensure
1060 // that fileOut was closed as some write errors (disk full) might not be
1061 // detected before doing this
1062 if ( !fileIn
.Close() || !fileOut
.Close() )
1065 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1066 // no chmod in VA. Should be some permission API for HPFS386 partitions
1068 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1070 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1074 #endif // OS/2 || Mac
1075 #endif // __WXMSW__ && __WIN32__
1081 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1084 // Normal system call
1085 if ( wxRename (file1
, file2
) == 0 )
1090 if (wxCopyFile(file1
, file2
)) {
1091 wxRemoveFile(file1
);
1098 bool wxRemoveFile(const wxString
& file
)
1100 #if defined(__VISUALC__) \
1101 || defined(__BORLANDC__) \
1102 || defined(__WATCOMC__) \
1103 || defined(__DMC__) \
1104 || defined(__GNUWIN32__) \
1105 || (defined(__MWERKS__) && defined(__MSL__))
1106 int res
= wxRemove(file
);
1107 #elif defined(__WXMAC__)
1108 int res
= unlink(wxFNCONV(file
));
1110 int res
= unlink(OS_FILENAME(file
));
1116 bool wxMkdir(const wxString
& dir
, int perm
)
1118 #if defined(__WXMAC__) && !defined(__UNIX__)
1119 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1121 const wxChar
*dirname
= dir
.c_str();
1123 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1124 // for the GNU compiler
1125 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1128 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1130 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1132 #elif defined(__OS2__)
1133 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1134 #elif defined(__DOS__)
1135 #if defined(__WATCOMC__)
1137 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1138 #elif defined(__DJGPP__)
1139 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1141 #error "Unsupported DOS compiler!"
1143 #else // !MSW, !DOS and !OS/2 VAC++
1146 if ( !CreateDirectory(dirname
, NULL
) )
1148 if ( wxMkDir(dir
.fn_str()) != 0 )
1152 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1161 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1164 return false; //to be changed since rmdir exists in VMS7.x
1165 #elif defined(__OS2__)
1166 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1170 return (CreateDirectory(dir
, NULL
) != 0);
1172 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1178 // does the path exists? (may have or not '/' or '\\' at the end)
1179 bool wxPathExists(const wxChar
*pszPathName
)
1181 wxString
strPath(pszPathName
);
1183 #if defined(__WINDOWS__) || defined(__OS2__)
1184 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1185 // so remove all trailing backslashes from the path - but don't do this for
1186 // the pathes "d:\" (which are different from "d:") nor for just "\"
1187 while ( wxEndsWithPathSeparator(strPath
) )
1189 size_t len
= strPath
.length();
1190 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1193 strPath
.Truncate(len
- 1);
1195 #endif // __WINDOWS__
1198 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1199 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1203 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1204 // stat() can't cope with network paths
1205 DWORD ret
= ::GetFileAttributes(strPath
);
1207 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1211 #ifndef __VISAGECPP__
1212 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1214 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1215 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1218 #endif // __WIN32__/!__WIN32__
1221 // Get a temporary filename, opening and closing the file.
1222 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1224 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1225 if ( filename
.empty() )
1229 wxStrcpy(buf
, filename
);
1231 buf
= MYcopystring(filename
);
1236 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1238 buf
= wxFileName::CreateTempFileName(prefix
);
1240 return !buf
.empty();
1243 // Get first file name matching given wild card.
1245 static wxDir
*gs_dir
= NULL
;
1246 static wxString gs_dirPath
;
1248 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1250 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1251 if ( gs_dirPath
.empty() )
1252 gs_dirPath
= wxT(".");
1253 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1254 gs_dirPath
<< wxFILE_SEP_PATH
;
1258 gs_dir
= new wxDir(gs_dirPath
);
1260 if ( !gs_dir
->IsOpened() )
1262 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1263 return wxEmptyString
;
1269 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1270 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1271 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1275 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1276 if ( result
.empty() )
1282 return gs_dirPath
+ result
;
1285 wxString
wxFindNextFile()
1287 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1290 gs_dir
->GetNext(&result
);
1292 if ( result
.empty() )
1298 return gs_dirPath
+ result
;
1302 // Get current working directory.
1303 // If buf is NULL, allocates space using new, else
1305 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1312 buf
= new wxChar
[sz
+ 1];
1315 bool ok
wxDUMMY_INITIALIZE(false);
1317 // for the compilers which have Unicode version of _getcwd(), call it
1318 // directly, for the others call the ANSI version and do the translation
1321 #else // wxUSE_UNICODE
1322 bool needsANSI
= true;
1324 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1325 // This is not legal code as the compiler
1326 // is allowed destroy the wxCharBuffer.
1327 // wxCharBuffer c_buffer(sz);
1328 // char *cbuf = (char*)(const char*)c_buffer;
1329 char cbuf
[_MAXPATHLEN
];
1333 #if wxUSE_UNICODE_MSLU
1334 if ( wxGetOsVersion() != wxWIN95
)
1336 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1339 ok
= _wgetcwd(buf
, sz
) != NULL
;
1345 #endif // wxUSE_UNICODE
1347 #if defined(_MSC_VER) || defined(__MINGW32__)
1348 ok
= _getcwd(cbuf
, sz
) != NULL
;
1349 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1351 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1353 wxString
res( lbuf
, *wxConvCurrent
) ;
1354 wxStrcpy( buf
, res
) ;
1359 #elif defined(__OS2__)
1361 ULONG ulDriveNum
= 0;
1362 ULONG ulDriveMap
= 0;
1363 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1368 rc
= ::DosQueryCurrentDir( 0 // current drive
1372 cbuf
[0] = 'A' + (ulDriveNum
- 1);
1377 #else // !Win32/VC++ !Mac !OS2
1378 ok
= getcwd(cbuf
, sz
) != NULL
;
1381 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1382 // finally convert the result to Unicode if needed
1383 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1384 #endif // wxUSE_UNICODE
1389 wxLogSysError(_("Failed to get the working directory"));
1391 // VZ: the old code used to return "." on error which didn't make any
1392 // sense at all to me - empty string is a better error indicator
1393 // (NULL might be even better but I'm afraid this could lead to
1394 // problems with the old code assuming the return is never NULL)
1397 else // ok, but we might need to massage the path into the right format
1400 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1401 // with / deliminers. We don't like that.
1402 for (wxChar
*ch
= buf
; *ch
; ch
++)
1404 if (*ch
== wxT('/'))
1409 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1410 // he needs Unix as opposed to Win32 pathnames
1411 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1412 // another example of DOS/Unix mix (Cygwin)
1413 wxString pathUnix
= buf
;
1414 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1415 #endif // __CYGWIN__
1430 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1431 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1432 wxString
str( buffer
);
1438 bool wxSetWorkingDirectory(const wxString
& d
)
1440 #if defined(__OS2__)
1441 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1442 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1443 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1444 #elif defined(__WINDOWS__)
1448 // No equivalent in WinCE
1451 return (bool)(SetCurrentDirectory(d
) != 0);
1454 // Must change drive, too.
1455 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1458 wxChar firstChar
= d
[0];
1462 firstChar
= firstChar
- 32;
1464 // To a drive number
1465 unsigned int driveNo
= firstChar
- 64;
1468 unsigned int noDrives
;
1469 _dos_setdrive(driveNo
, &noDrives
);
1472 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1480 // Get the OS directory if appropriate (such as the Windows directory).
1481 // On non-Windows platform, probably just return the empty string.
1482 wxString
wxGetOSDirectory()
1485 return wxString(wxT("\\Windows"));
1486 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1488 GetWindowsDirectory(buf
, 256);
1489 return wxString(buf
);
1490 #elif defined(__WXMAC__)
1491 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1493 return wxEmptyString
;
1497 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1499 size_t len
= wxStrlen(pszFileName
);
1501 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1504 // find a file in a list of directories, returns false if not found
1505 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1507 // we assume that it's not empty
1508 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1509 _T("empty file name in wxFindFileInPath"));
1511 // skip path separator in the beginning of the file name if present
1512 if ( wxIsPathSeparator(*pszFile
) )
1515 // copy the path (strtok will modify it)
1516 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1517 wxStrcpy(szPath
, pszPath
);
1520 wxChar
*pc
, *save_ptr
;
1521 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1523 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1525 // search for the file in this directory
1527 if ( !wxEndsWithPathSeparator(pc
) )
1528 strFile
+= wxFILE_SEP_PATH
;
1531 if ( wxFileExists(strFile
) ) {
1537 // suppress warning about unused variable save_ptr when wxStrtok() is a
1538 // macro which throws away its third argument
1543 return pc
!= NULL
; // if true => we breaked from the loop
1546 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1551 // it can be empty, but it shouldn't be NULL
1552 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1554 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1557 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1560 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1561 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1562 0, FILE_ATTRIBUTE_NORMAL
, 0);
1563 if (fileHandle
== INVALID_HANDLE_VALUE
)
1567 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1569 CloseHandle(fileHandle
);
1571 wxDateTime dateTime
;
1573 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1575 wxLogLastError(_T("FileTimeToLocalFileTime"));
1579 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1581 wxLogLastError(_T("FileTimeToSystemTime"));
1584 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1585 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1586 return dateTime
.GetTicks();
1593 wxStat( filename
, &buf
);
1595 return buf
.st_mtime
;
1600 // Parses the filterStr, returning the number of filters.
1601 // Returns 0 if none or if there's a problem.
1602 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1604 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
, wxArrayString
& descriptions
, wxArrayString
& filters
)
1606 descriptions
.Clear();
1609 wxString
str(filterStr
);
1611 wxString description
, filter
;
1613 while( pos
!= wxNOT_FOUND
)
1615 pos
= str
.Find(wxT('|'));
1616 if ( pos
== wxNOT_FOUND
)
1618 // if there are no '|'s at all in the string just take the entire
1619 // string as filter and make description empty for later autocompletion
1620 if ( filters
.IsEmpty() )
1622 descriptions
.Add(wxEmptyString
);
1623 filters
.Add(filterStr
);
1627 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1633 description
= str
.Left(pos
);
1634 str
= str
.Mid(pos
+ 1);
1635 pos
= str
.Find(wxT('|'));
1636 if ( pos
== wxNOT_FOUND
)
1642 filter
= str
.Left(pos
);
1643 str
= str
.Mid(pos
+ 1);
1646 descriptions
.Add(description
);
1647 filters
.Add(filter
);
1650 #if defined(__WXMOTIF__)
1651 // split it so there is one wildcard per entry
1652 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1654 pos
= filters
[i
].Find(wxT(';'));
1655 if (pos
!= wxNOT_FOUND
)
1657 // first split only filters
1658 descriptions
.Insert(descriptions
[i
],i
+1);
1659 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1660 filters
[i
]=filters
[i
].Left(pos
);
1662 // autoreplace new filter in description with pattern:
1663 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1664 // cause split into:
1665 // C/C++ Files(*.cpp)|*.cpp
1666 // C/C++ Files(*.c;*.h)|*.c;*.h
1667 // and next iteration cause another split into:
1668 // C/C++ Files(*.cpp)|*.cpp
1669 // C/C++ Files(*.c)|*.c
1670 // C/C++ Files(*.h)|*.h
1671 for ( size_t k
=i
;k
<i
+2;k
++ )
1673 pos
= descriptions
[k
].Find(filters
[k
]);
1674 if (pos
!= wxNOT_FOUND
)
1676 wxString before
= descriptions
[k
].Left(pos
);
1677 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1678 pos
= before
.Find(_T('('),true);
1679 if (pos
>before
.Find(_T(')'),true))
1681 before
= before
.Left(pos
+1);
1682 before
<< filters
[k
];
1683 pos
= after
.Find(_T(')'));
1684 int pos1
= after
.Find(_T('('));
1685 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1687 before
<< after
.Mid(pos
);
1688 descriptions
[k
] = before
;
1698 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1700 if ( descriptions
[j
] == wxEmptyString
&& filters
[j
] != wxEmptyString
)
1702 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1706 return filters
.GetCount();
1710 //------------------------------------------------------------------------
1711 // wild character routines
1712 //------------------------------------------------------------------------
1714 bool wxIsWild( const wxString
& pattern
)
1716 wxString tmp
= pattern
;
1717 wxChar
*pat
= WXSTRINGCAST(tmp
);
1722 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1733 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1735 * The match procedure is public domain code (from ircII's reg.c)
1738 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1742 /* Match if both are empty. */
1746 const wxChar
*m
= pat
.c_str(),
1757 if (dot_special
&& (*n
== wxT('.')))
1759 /* Never match so that hidden Unix files
1760 * are never found. */
1774 else if (*m
== wxT('?'))
1782 if (*m
== wxT('\\'))
1785 /* Quoting "nothing" is a bad thing */
1792 * If we are out of both strings or we just
1793 * saw a wildcard, then we can say we have a
1804 * We could check for *n == NULL at this point, but
1805 * since it's more common to have a character there,
1806 * check to see if they match first (m and n) and
1807 * then if they don't match, THEN we can check for
1825 * If there are no more characters in the
1826 * string, but we still need to find another
1827 * character (*m != NULL), then it will be
1828 * impossible to match it
1835 if (*np
== wxT(' '))
1859 // Return the type of an open file
1861 wxFileKind
wxGetFileKind(int fd
)
1863 #if !defined (__WXWINCE__)
1865 return wxFILE_KIND_TERMINAL
;
1868 #if defined __WXWINCE__
1869 return wxFILE_KIND_UNKNOWN
;
1870 #elif defined __WXMSW__
1871 switch (::GetFileType(wxGetOSFHandle(fd
)) & ~FILE_TYPE_REMOTE
)
1873 case FILE_TYPE_DISK
:
1874 return wxFILE_KIND_DISK
;
1875 case FILE_TYPE_PIPE
:
1876 return wxFILE_KIND_PIPE
;
1879 return wxFILE_KIND_UNKNOWN
;
1881 #elif defined __UNIX__
1885 if (S_ISFIFO(st
.st_mode
))
1886 return wxFILE_KIND_PIPE
;
1887 if (!S_ISREG(st
.st_mode
))
1888 return wxFILE_KIND_UNKNOWN
;
1891 if (st
.st_fab_rfm
!= FAB$C_STMLF
)
1892 return wxFILE_KIND_UNKNOWN
;
1895 return wxFILE_KIND_DISK
;
1898 if (lseek(fd
, 0, SEEK_CUR
) != -1)
1899 return wxFILE_KIND_DISK
;
1901 return wxFILE_KIND_UNKNOWN
;
1906 #pragma warning(default:4706) // assignment within conditional expression