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__
78 // TODO: Borland probably has _wgetcwd as well?
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
88 #define _MAXPATHLEN 1024
92 # include "MoreFilesX.h"
95 // ----------------------------------------------------------------------------
97 // ----------------------------------------------------------------------------
99 // MT-FIXME: get rid of this horror and all code using it
100 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
102 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
104 // VisualAge C++ V4.0 cannot have any external linkage const decs
105 // in headers included by more than one primary source
107 const int wxInvalidOffset
= -1;
110 // ----------------------------------------------------------------------------
112 // ----------------------------------------------------------------------------
114 // we need to translate Mac filenames before passing them to OS functions
115 #define OS_FILENAME(s) (s.fn_str())
117 // ============================================================================
119 // ============================================================================
121 #ifdef wxNEED_WX_UNISTD_H
123 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
125 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
128 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
130 return access( wxConvFile
.cWX2MB( pathname
), mode
);
133 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
135 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
139 // wxNEED_WX_UNISTD_H
141 // ----------------------------------------------------------------------------
143 // ----------------------------------------------------------------------------
145 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
147 static inline wxChar
* MYcopystring(const wxString
& s
)
149 wxChar
* copy
= new wxChar
[s
.length() + 1];
150 return wxStrcpy(copy
, s
.c_str());
153 static inline wxChar
* MYcopystring(const wxChar
* s
)
155 wxChar
* copy
= new wxChar
[wxStrlen(s
) + 1];
156 return wxStrcpy(copy
, s
);
159 void wxPathList::Add (const wxString
& path
)
161 wxStringList::Add (WXSTRINGCAST path
);
164 // Add paths e.g. from the PATH environment variable
165 void wxPathList::AddEnvList (const wxString
& envVariable
)
167 // No environment variables on WinCE
169 static const wxChar PATH_TOKS
[] =
170 #if defined(__WINDOWS__) || defined(__OS2__)
172 The space has been removed from the tokenizers, otherwise a
173 path such as "C:\Program Files" would be split into 2 paths:
174 "C:\Program" and "Files"
176 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
177 wxT(";"); // Don't seperate with colon in DOS (used for drive)
182 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
185 wxChar
*s
= MYcopystring (val
);
186 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
193 if ( (token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
))
201 // suppress warning about unused variable save_ptr when wxStrtok() is a
202 // macro which throws away its third argument
210 // Given a full filename (with path), ensure that that file can
211 // be accessed again USING FILENAME ONLY by adding the path
212 // to the list if not already there.
213 void wxPathList::EnsureFileAccessible (const wxString
& path
)
215 wxString
path_only(wxPathOnly(path
));
216 if ( !path_only
.empty() )
218 if ( !Member(path_only
) )
223 bool wxPathList::Member (const wxString
& path
)
225 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
227 wxString
path2( node
->GetData() );
229 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined (__WXMAC__)
231 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
233 // Case sensitive File System
234 path
.CompareTo (path2
) == 0
242 wxString
wxPathList::FindValidPath (const wxString
& file
)
244 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
245 return wxString(wxFileFunctionsBuffer
);
247 wxChar buf
[_MAXPATHLEN
];
248 wxStrcpy(buf
, wxFileFunctionsBuffer
);
250 wxChar
*filename
= wxIsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
252 for (wxStringList::compatibility_iterator node
= GetFirst(); node
; node
= node
->GetNext())
254 const wxChar
*path
= node
->GetData();
255 wxStrcpy (wxFileFunctionsBuffer
, path
);
256 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
257 if (ch
!= wxT('\\') && ch
!= wxT('/'))
258 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
259 wxStrcat (wxFileFunctionsBuffer
, filename
);
261 wxUnix2DosFilename (wxFileFunctionsBuffer
);
263 if (wxFileExists (wxFileFunctionsBuffer
))
265 return wxString(wxFileFunctionsBuffer
); // Found!
269 return wxEmptyString
; // Not found
272 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
274 wxString f
= FindValidPath(file
);
275 if ( f
.empty() || wxIsAbsolutePath(f
) )
279 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
281 if ( !wxEndsWithPathSeparator(buf
) )
283 buf
+= wxFILE_SEP_PATH
;
291 wxFileExists (const wxString
& filename
)
293 // we must use GetFileAttributes() instead of the ANSI C functions because
294 // it can cope with network (UNC) paths unlike them
295 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
296 DWORD ret
= ::GetFileAttributes(filename
);
298 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
301 #ifndef wxNEED_WX_UNISTD_H
302 return wxStat( filename
.fn_str() , &st
) == 0 && (st
.st_mode
& S_IFREG
);
304 return wxStat( filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
306 #endif // __WIN32__/!__WIN32__
310 wxIsAbsolutePath (const wxString
& filename
)
312 if (filename
!= wxT(""))
314 #if defined(__WXMAC__) && !defined(__DARWIN__)
315 // Classic or Carbon CodeWarrior like
316 // Carbon with Apple DevTools is Unix like
318 // This seems wrong to me, but there is no fix. since
319 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
320 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
321 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
324 // Unix like or Windows
325 if (filename
[0] == wxT('/'))
329 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
332 #if defined(__WINDOWS__) || defined(__OS2__)
334 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
342 * Strip off any extension (dot something) from end of file,
343 * IF one exists. Inserts zero into buffer.
347 void wxStripExtension(wxChar
*buffer
)
349 int len
= wxStrlen(buffer
);
353 if (buffer
[i
] == wxT('.'))
362 void wxStripExtension(wxString
& buffer
)
364 //RN: Be careful about the handling the case where
365 //buffer.Length() == 0
366 for(size_t i
= buffer
.Length() - 1; i
!= wxString::npos
; --i
)
368 if (buffer
.GetChar(i
) == wxT('.'))
370 buffer
= buffer
.Left(i
);
376 // Destructive removal of /./ and /../ stuff
377 wxChar
*wxRealPath (wxChar
*path
)
380 static const wxChar SEP
= wxT('\\');
381 wxUnix2DosFilename(path
);
383 static const wxChar SEP
= wxT('/');
385 if (path
[0] && path
[1]) {
386 /* MATTHEW: special case "/./x" */
388 if (path
[2] == SEP
&& path
[1] == wxT('.'))
396 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
399 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
404 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
405 && (q
- 1 <= path
|| q
[-1] != SEP
))
408 if (path
[0] == wxT('\0'))
413 #if defined(__WXMSW__) || defined(__OS2__)
414 /* Check that path[2] is NULL! */
415 else if (path
[1] == wxT(':') && !path
[2])
424 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
433 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
435 if (filename
== wxT(""))
436 return (wxChar
*) NULL
;
438 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
439 wxChar buf
[_MAXPATHLEN
];
441 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
442 wxChar ch
= buf
[wxStrlen(buf
) - 1];
444 if (ch
!= wxT('\\') && ch
!= wxT('/'))
445 wxStrcat(buf
, wxT("\\"));
448 wxStrcat(buf
, wxT("/"));
450 wxStrcat(buf
, wxFileFunctionsBuffer
);
451 return MYcopystring( wxRealPath(buf
) );
453 return MYcopystring( wxFileFunctionsBuffer
);
459 ~user/ => user's home dir
460 If the environment variable a = "foo" and b = "bar" then:
477 /* input name in name, pathname output to buf. */
479 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
481 register wxChar
*d
, *s
, *nm
;
482 wxChar lnm
[_MAXPATHLEN
];
485 // Some compilers don't like this line.
486 // const wxChar trimchars[] = wxT("\n \t");
489 trimchars
[0] = wxT('\n');
490 trimchars
[1] = wxT(' ');
491 trimchars
[2] = wxT('\t');
495 const wxChar SEP
= wxT('\\');
497 const wxChar SEP
= wxT('/');
500 if (name
== NULL
|| *name
== wxT('\0'))
502 nm
= MYcopystring(name
); // Make a scratch copy
505 /* Skip leading whitespace and cr */
506 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
508 /* And strip off trailing whitespace and cr */
509 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
510 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
518 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
521 /* Expand inline environment variables */
539 while ((*d
++ = *s
) != 0) {
541 if (*s
== wxT('\\')) {
542 if ((*(d
- 1) = *++s
)) {
550 // No env variables on WinCE
553 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
555 if (*s
++ == wxT('$'))
558 register wxChar
*start
= d
;
559 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
560 register wxChar
*value
;
561 while ((*d
++ = *s
) != 0)
562 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
567 value
= wxGetenv(braces
? start
+ 1 : start
);
569 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
583 /* Expand ~ and ~user */
585 if (nm
[0] == wxT('~') && !q
)
588 if (nm
[1] == SEP
|| nm
[1] == 0)
590 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
591 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
596 { /* ~user/filename */
597 register wxChar
*nnm
;
598 register wxChar
*home
;
599 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
603 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
604 was_sep
= (*s
== SEP
);
605 nnm
= *s
? s
+ 1 : s
;
607 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
608 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
609 if (was_sep
) /* replace only if it was there: */
620 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
622 while (wxT('\0') != (*d
++ = *s
++))
625 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
629 while ((*d
++ = *s
++) != 0)
633 delete[] nm_tmp
; // clean up alloc
634 /* Now clean up the buffer */
635 return wxRealPath(buf
);
638 /* Contract Paths to be build upon an environment variable
641 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
643 The call wxExpandPath can convert these back!
646 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
648 static wxChar dest
[_MAXPATHLEN
];
650 if (filename
== wxT(""))
651 return (wxChar
*) NULL
;
653 wxStrcpy (dest
, WXSTRINGCAST filename
);
655 wxUnix2DosFilename(dest
);
658 // Handle environment
662 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
663 (tcp
= wxStrstr (dest
, val
)) != NULL
)
665 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
668 wxStrcpy (tcp
, WXSTRINGCAST envname
);
669 wxStrcat (tcp
, wxT("}"));
670 wxStrcat (tcp
, wxFileFunctionsBuffer
);
674 // Handle User's home (ignore root homes!)
675 val
= wxGetUserHome (user
);
679 const size_t len
= wxStrlen(val
);
683 if (wxStrncmp(dest
, val
, len
) == 0)
685 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
687 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
688 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
689 wxStrcpy (dest
, wxFileFunctionsBuffer
);
695 // Return just the filename, not the path (basename)
696 wxChar
*wxFileNameFromPath (wxChar
*path
)
699 wxString n
= wxFileNameFromPath(p
);
701 return path
+ p
.length() - n
.length();
704 wxString
wxFileNameFromPath (const wxString
& path
)
707 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
709 wxString fullname
= name
;
712 fullname
<< wxFILE_SEP_EXT
<< ext
;
718 // Return just the directory, or NULL if no directory
720 wxPathOnly (wxChar
*path
)
724 static wxChar buf
[_MAXPATHLEN
];
727 wxStrcpy (buf
, path
);
729 int l
= wxStrlen(path
);
732 // Search backward for a backward or forward slash
735 #if defined(__WXMAC__) && !defined(__DARWIN__)
736 // Classic or Carbon CodeWarrior like
737 // Carbon with Apple DevTools is Unix like
738 if (path
[i
] == wxT(':') )
744 // Unix like or Windows
745 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
752 if (path
[i
] == wxT(']'))
761 #if defined(__WXMSW__) || defined(__OS2__)
762 // Try Drive specifier
763 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
765 // A:junk --> A:. (since A:.\junk Not A:\junk)
772 return (wxChar
*) NULL
;
775 // Return just the directory, or NULL if no directory
776 wxString
wxPathOnly (const wxString
& path
)
780 wxChar buf
[_MAXPATHLEN
];
783 wxStrcpy (buf
, WXSTRINGCAST path
);
785 int l
= path
.Length();
788 // Search backward for a backward or forward slash
791 #if defined(__WXMAC__) && !defined(__DARWIN__)
792 // Classic or Carbon CodeWarrior like
793 // Carbon with Apple DevTools is Unix like
794 if (path
[i
] == wxT(':') )
797 return wxString(buf
);
800 // Unix like or Windows
801 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
803 // Don't return an empty string
807 return wxString(buf
);
811 if (path
[i
] == wxT(']'))
814 return wxString(buf
);
820 #if defined(__WXMSW__) || defined(__OS2__)
821 // Try Drive specifier
822 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
824 // A:junk --> A:. (since A:.\junk Not A:\junk)
827 return wxString(buf
);
831 return wxString(wxT(""));
834 // Utility for converting delimiters in DOS filenames to UNIX style
835 // and back again - or we get nasty problems with delimiters.
836 // Also, convert to lower case, since case is significant in UNIX.
838 #if defined(__WXMAC__)
840 #if TARGET_API_MAC_OSX
841 #define kDefaultPathStyle kCFURLPOSIXPathStyle
843 #define kDefaultPathStyle kCFURLHFSPathStyle
846 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
849 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
850 if ( additionalPathComponent
)
852 CFURLRef parentURLRef
= fullURLRef
;
853 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
854 additionalPathComponent
,false);
855 CFRelease( parentURLRef
) ;
857 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
858 CFRelease( fullURLRef
) ;
859 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
862 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
864 OSStatus err
= noErr
;
865 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
868 if ( CFURLGetFSRef(url
, fsRef
) == false )
879 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
881 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
884 return wxMacCFStringHolder(cfname
).AsString() ;
887 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
890 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
892 return wxMacFSRefToPath( &fsRef
) ;
894 return wxEmptyString
;
897 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
899 OSStatus err
= noErr
;
901 wxMacPathToFSRef( path
, &fsRef
) ;
902 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
908 wxDos2UnixFilename (wxChar
*s
)
917 *s
= (wxChar
)wxTolower (*s
); // Case INDEPENDENT
924 #if defined(__WXMSW__) || defined(__OS2__)
925 wxUnix2DosFilename (wxChar
*s
)
927 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
930 // Yes, I really mean this to happen under DOS only! JACS
931 #if defined(__WXMSW__) || defined(__OS2__)
942 // Concatenate two files to form third
944 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
947 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
950 FILE *fp1
wxDUMMY_INITIALIZE(NULL
);
953 // Open the inputs and outputs
954 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
955 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
956 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
968 while ((ch
= getc (fp1
)) != EOF
)
969 (void) putc (ch
, fp3
);
972 while ((ch
= getc (fp2
)) != EOF
)
973 (void) putc (ch
, fp3
);
977 bool result
= wxRenameFile(outfile
, file3
);
983 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
985 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
986 // CopyFile() copies file attributes and modification time too, so use it
987 // instead of our code if available
989 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
990 if ( !::CopyFile(file1
, file2
, !overwrite
) )
992 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
993 file1
.c_str(), file2
.c_str());
997 #elif defined(__OS2__)
998 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1003 // get permissions of file1
1004 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1006 // the file probably doesn't exist or we haven't the rights to read
1008 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1013 // open file1 for reading
1014 wxFile
fileIn(file1
, wxFile::read
);
1015 if ( !fileIn
.IsOpened() )
1018 // remove file2, if it exists. This is needed for creating
1019 // file2 with the correct permissions in the next step
1020 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1022 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1027 // reset the umask as we want to create the file with exactly the same
1028 // permissions as the original one
1031 // create file2 with the same permissions than file1 and open it for
1035 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1038 // copy contents of file1 to file2
1043 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1044 if ( fileIn
.Error() )
1051 if ( fileOut
.Write(buf
, count
) < count
)
1055 // we can expect fileIn to be closed successfully, but we should ensure
1056 // that fileOut was closed as some write errors (disk full) might not be
1057 // detected before doing this
1058 if ( !fileIn
.Close() || !fileOut
.Close() )
1061 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1062 // no chmod in VA. Should be some permission API for HPFS386 partitions
1064 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1066 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1070 #endif // OS/2 || Mac
1071 #endif // __WXMSW__ && __WIN32__
1077 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1080 // Normal system call
1081 if ( wxRename (file1
, file2
) == 0 )
1086 if (wxCopyFile(file1
, file2
)) {
1087 wxRemoveFile(file1
);
1094 bool wxRemoveFile(const wxString
& file
)
1096 #if defined(__VISUALC__) \
1097 || defined(__BORLANDC__) \
1098 || defined(__WATCOMC__) \
1099 || defined(__DMC__) \
1100 || defined(__GNUWIN32__) \
1101 || (defined(__MWERKS__) && defined(__MSL__))
1102 int res
= wxRemove(file
);
1103 #elif defined(__WXMAC__)
1104 int res
= unlink(wxFNCONV(file
));
1106 int res
= unlink(OS_FILENAME(file
));
1112 bool wxMkdir(const wxString
& dir
, int perm
)
1114 #if defined(__WXMAC__) && !defined(__UNIX__)
1115 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1117 const wxChar
*dirname
= dir
.c_str();
1119 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1120 // for the GNU compiler
1121 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1124 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1126 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1128 #elif defined(__OS2__)
1129 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1130 #elif defined(__DOS__)
1131 #if defined(__WATCOMC__)
1133 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1134 #elif defined(__DJGPP__)
1135 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1137 #error "Unsupported DOS compiler!"
1139 #else // !MSW, !DOS and !OS/2 VAC++
1142 if ( !CreateDirectory(dirname
, NULL
) )
1144 if ( wxMkDir(dir
.fn_str()) != 0 )
1148 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1157 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1160 return false; //to be changed since rmdir exists in VMS7.x
1161 #elif defined(__OS2__)
1162 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1166 return (CreateDirectory(dir
, NULL
) != 0);
1168 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1174 // does the path exists? (may have or not '/' or '\\' at the end)
1175 bool wxPathExists(const wxChar
*pszPathName
)
1177 wxString
strPath(pszPathName
);
1179 #if defined(__WINDOWS__) || defined(__OS2__)
1180 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1181 // so remove all trailing backslashes from the path - but don't do this for
1182 // the pathes "d:\" (which are different from "d:") nor for just "\"
1183 while ( wxEndsWithPathSeparator(strPath
) )
1185 size_t len
= strPath
.length();
1186 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1189 strPath
.Truncate(len
- 1);
1191 #endif // __WINDOWS__
1194 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1195 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1199 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1200 // stat() can't cope with network paths
1201 DWORD ret
= ::GetFileAttributes(strPath
);
1203 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1207 #ifndef __VISAGECPP__
1208 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1210 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1211 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1214 #endif // __WIN32__/!__WIN32__
1217 // Get a temporary filename, opening and closing the file.
1218 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1220 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1221 if ( filename
.empty() )
1225 wxStrcpy(buf
, filename
);
1227 buf
= MYcopystring(filename
);
1232 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1234 buf
= wxFileName::CreateTempFileName(prefix
);
1236 return !buf
.empty();
1239 // Get first file name matching given wild card.
1241 static wxDir
*gs_dir
= NULL
;
1242 static wxString gs_dirPath
;
1244 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1246 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1247 if ( gs_dirPath
.empty() )
1248 gs_dirPath
= wxT(".");
1249 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1250 gs_dirPath
<< wxFILE_SEP_PATH
;
1254 gs_dir
= new wxDir(gs_dirPath
);
1256 if ( !gs_dir
->IsOpened() )
1258 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1259 return wxEmptyString
;
1265 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1266 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1267 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1271 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1272 if ( result
.empty() )
1278 return gs_dirPath
+ result
;
1281 wxString
wxFindNextFile()
1283 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1286 gs_dir
->GetNext(&result
);
1288 if ( result
.empty() )
1294 return gs_dirPath
+ result
;
1298 // Get current working directory.
1299 // If buf is NULL, allocates space using new, else
1301 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1308 buf
= new wxChar
[sz
+ 1];
1311 bool ok
wxDUMMY_INITIALIZE(false);
1313 // for the compilers which have Unicode version of _getcwd(), call it
1314 // directly, for the others call the ANSI version and do the translation
1317 #else // wxUSE_UNICODE
1318 bool needsANSI
= true;
1320 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1321 // This is not legal code as the compiler
1322 // is allowed destroy the wxCharBuffer.
1323 // wxCharBuffer c_buffer(sz);
1324 // char *cbuf = (char*)(const char*)c_buffer;
1325 char cbuf
[_MAXPATHLEN
];
1329 #if wxUSE_UNICODE_MSLU
1330 if ( wxGetOsVersion() != wxWIN95
)
1332 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1335 ok
= _wgetcwd(buf
, sz
) != NULL
;
1341 #endif // wxUSE_UNICODE
1343 #if defined(_MSC_VER) || defined(__MINGW32__)
1344 ok
= _getcwd(cbuf
, sz
) != NULL
;
1345 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1347 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1349 wxString
res( lbuf
, *wxConvCurrent
) ;
1350 wxStrcpy( buf
, res
) ;
1355 #elif defined(__OS2__)
1357 ULONG ulDriveNum
= 0;
1358 ULONG ulDriveMap
= 0;
1359 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1364 rc
= ::DosQueryCurrentDir( 0 // current drive
1368 cbuf
[0] = 'A' + (ulDriveNum
- 1);
1373 #else // !Win32/VC++ !Mac !OS2
1374 ok
= getcwd(cbuf
, sz
) != NULL
;
1377 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1378 // finally convert the result to Unicode if needed
1379 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1380 #endif // wxUSE_UNICODE
1385 wxLogSysError(_("Failed to get the working directory"));
1387 // VZ: the old code used to return "." on error which didn't make any
1388 // sense at all to me - empty string is a better error indicator
1389 // (NULL might be even better but I'm afraid this could lead to
1390 // problems with the old code assuming the return is never NULL)
1393 else // ok, but we might need to massage the path into the right format
1396 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1397 // with / deliminers. We don't like that.
1398 for (wxChar
*ch
= buf
; *ch
; ch
++)
1400 if (*ch
== wxT('/'))
1405 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1406 // he needs Unix as opposed to Win32 pathnames
1407 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1408 // another example of DOS/Unix mix (Cygwin)
1409 wxString pathUnix
= buf
;
1410 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1411 #endif // __CYGWIN__
1426 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1427 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1428 wxString
str( buffer
);
1434 bool wxSetWorkingDirectory(const wxString
& d
)
1436 #if defined(__OS2__)
1437 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1438 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1439 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1440 #elif defined(__WINDOWS__)
1444 // No equivalent in WinCE
1447 return (bool)(SetCurrentDirectory(d
) != 0);
1450 // Must change drive, too.
1451 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1454 wxChar firstChar
= d
[0];
1458 firstChar
= firstChar
- 32;
1460 // To a drive number
1461 unsigned int driveNo
= firstChar
- 64;
1464 unsigned int noDrives
;
1465 _dos_setdrive(driveNo
, &noDrives
);
1468 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1476 // Get the OS directory if appropriate (such as the Windows directory).
1477 // On non-Windows platform, probably just return the empty string.
1478 wxString
wxGetOSDirectory()
1481 return wxString(wxT("\\Windows"));
1482 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1484 GetWindowsDirectory(buf
, 256);
1485 return wxString(buf
);
1486 #elif defined(__WXMAC__)
1487 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1489 return wxEmptyString
;
1493 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1495 size_t len
= wxStrlen(pszFileName
);
1497 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1500 // find a file in a list of directories, returns false if not found
1501 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1503 // we assume that it's not empty
1504 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1505 _T("empty file name in wxFindFileInPath"));
1507 // skip path separator in the beginning of the file name if present
1508 if ( wxIsPathSeparator(*pszFile
) )
1511 // copy the path (strtok will modify it)
1512 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1513 wxStrcpy(szPath
, pszPath
);
1516 wxChar
*pc
, *save_ptr
;
1517 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1519 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1521 // search for the file in this directory
1523 if ( !wxEndsWithPathSeparator(pc
) )
1524 strFile
+= wxFILE_SEP_PATH
;
1527 if ( wxFileExists(strFile
) ) {
1533 // suppress warning about unused variable save_ptr when wxStrtok() is a
1534 // macro which throws away its third argument
1539 return pc
!= NULL
; // if true => we breaked from the loop
1542 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1547 // it can be empty, but it shouldn't be NULL
1548 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1550 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1553 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1556 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1557 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1558 0, FILE_ATTRIBUTE_NORMAL
, 0);
1559 if (fileHandle
== INVALID_HANDLE_VALUE
)
1563 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1565 CloseHandle(fileHandle
);
1567 wxDateTime dateTime
;
1569 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1571 wxLogLastError(_T("FileTimeToLocalFileTime"));
1575 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1577 wxLogLastError(_T("FileTimeToSystemTime"));
1580 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1581 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1582 return dateTime
.GetTicks();
1589 wxStat( filename
, &buf
);
1591 return buf
.st_mtime
;
1596 // Parses the filterStr, returning the number of filters.
1597 // Returns 0 if none or if there's a problem.
1598 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1600 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
, wxArrayString
& descriptions
, wxArrayString
& filters
)
1602 descriptions
.Clear();
1605 wxString
str(filterStr
);
1607 wxString description
, filter
;
1609 while( pos
!= wxNOT_FOUND
)
1611 pos
= str
.Find(wxT('|'));
1612 if ( pos
== wxNOT_FOUND
)
1614 // if there are no '|'s at all in the string just take the entire
1615 // string as filter and make description empty for later autocompletion
1616 if ( filters
.IsEmpty() )
1618 descriptions
.Add(wxEmptyString
);
1619 filters
.Add(filterStr
);
1623 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1629 description
= str
.Left(pos
);
1630 str
= str
.Mid(pos
+ 1);
1631 pos
= str
.Find(wxT('|'));
1632 if ( pos
== wxNOT_FOUND
)
1638 filter
= str
.Left(pos
);
1639 str
= str
.Mid(pos
+ 1);
1642 descriptions
.Add(description
);
1643 filters
.Add(filter
);
1646 #if defined(__WXMOTIF__)
1647 // split it so there is one wildcard per entry
1648 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1650 pos
= filters
[i
].Find(wxT(';'));
1651 if (pos
!= wxNOT_FOUND
)
1653 // first split only filters
1654 descriptions
.Insert(descriptions
[i
],i
+1);
1655 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1656 filters
[i
]=filters
[i
].Left(pos
);
1658 // autoreplace new filter in description with pattern:
1659 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1660 // cause split into:
1661 // C/C++ Files(*.cpp)|*.cpp
1662 // C/C++ Files(*.c;*.h)|*.c;*.h
1663 // and next iteration cause another split into:
1664 // C/C++ Files(*.cpp)|*.cpp
1665 // C/C++ Files(*.c)|*.c
1666 // C/C++ Files(*.h)|*.h
1667 for ( size_t k
=i
;k
<i
+2;k
++ )
1669 pos
= descriptions
[k
].Find(filters
[k
]);
1670 if (pos
!= wxNOT_FOUND
)
1672 wxString before
= descriptions
[k
].Left(pos
);
1673 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1674 pos
= before
.Find(_T('('),true);
1675 if (pos
>before
.Find(_T(')'),true))
1677 before
= before
.Left(pos
+1);
1678 before
<< filters
[k
];
1679 pos
= after
.Find(_T(')'));
1680 int pos1
= after
.Find(_T('('));
1681 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1683 before
<< after
.Mid(pos
);
1684 descriptions
[k
] = before
;
1694 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1696 if ( descriptions
[j
] == wxEmptyString
&& filters
[j
] != wxEmptyString
)
1698 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1702 return filters
.GetCount();
1706 //------------------------------------------------------------------------
1707 // wild character routines
1708 //------------------------------------------------------------------------
1710 bool wxIsWild( const wxString
& pattern
)
1712 wxString tmp
= pattern
;
1713 wxChar
*pat
= WXSTRINGCAST(tmp
);
1718 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1729 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1731 * The match procedure is public domain code (from ircII's reg.c)
1734 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1738 /* Match if both are empty. */
1742 const wxChar
*m
= pat
.c_str(),
1753 if (dot_special
&& (*n
== wxT('.')))
1755 /* Never match so that hidden Unix files
1756 * are never found. */
1770 else if (*m
== wxT('?'))
1778 if (*m
== wxT('\\'))
1781 /* Quoting "nothing" is a bad thing */
1788 * If we are out of both strings or we just
1789 * saw a wildcard, then we can say we have a
1800 * We could check for *n == NULL at this point, but
1801 * since it's more common to have a character there,
1802 * check to see if they match first (m and n) and
1803 * then if they don't match, THEN we can check for
1821 * If there are no more characters in the
1822 * string, but we still need to find another
1823 * character (*m != NULL), then it will be
1824 * impossible to match it
1831 if (*np
== wxT(' '))
1857 #pragma warning(default:4706) // assignment within conditional expression