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 off_t wxInvalidOffset
= (off_t
)-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
.IsEmpty() )
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 return wxStat(filename
, &st
) == 0 && (st
.st_mode
& S_IFREG
);
302 #endif // __WIN32__/!__WIN32__
306 wxIsAbsolutePath (const wxString
& filename
)
308 if (filename
!= wxT(""))
310 #if defined(__WXMAC__) && !defined(__DARWIN__)
311 // Classic or Carbon CodeWarrior like
312 // Carbon with Apple DevTools is Unix like
314 // This seems wrong to me, but there is no fix. since
315 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
316 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
317 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
320 // Unix like or Windows
321 if (filename
[0] == wxT('/'))
325 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
328 #if defined(__WINDOWS__) || defined(__OS2__)
330 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
338 * Strip off any extension (dot something) from end of file,
339 * IF one exists. Inserts zero into buffer.
343 void wxStripExtension(wxChar
*buffer
)
345 int len
= wxStrlen(buffer
);
349 if (buffer
[i
] == wxT('.'))
358 void wxStripExtension(wxString
& buffer
)
360 size_t len
= buffer
.Length();
364 if (buffer
.GetChar(i
) == wxT('.'))
366 buffer
= buffer
.Left(i
);
373 // Destructive removal of /./ and /../ stuff
374 wxChar
*wxRealPath (wxChar
*path
)
377 static const wxChar SEP
= wxT('\\');
378 wxUnix2DosFilename(path
);
380 static const wxChar SEP
= wxT('/');
382 if (path
[0] && path
[1]) {
383 /* MATTHEW: special case "/./x" */
385 if (path
[2] == SEP
&& path
[1] == wxT('.'))
393 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
396 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--)
401 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
402 && (q
- 1 <= path
|| q
[-1] != SEP
))
405 if (path
[0] == wxT('\0'))
410 #if defined(__WXMSW__) || defined(__OS2__)
411 /* Check that path[2] is NULL! */
412 else if (path
[1] == wxT(':') && !path
[2])
421 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
430 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
432 if (filename
== wxT(""))
433 return (wxChar
*) NULL
;
435 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
436 wxChar buf
[_MAXPATHLEN
];
438 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
439 wxChar ch
= buf
[wxStrlen(buf
) - 1];
441 if (ch
!= wxT('\\') && ch
!= wxT('/'))
442 wxStrcat(buf
, wxT("\\"));
445 wxStrcat(buf
, wxT("/"));
447 wxStrcat(buf
, wxFileFunctionsBuffer
);
448 return MYcopystring( wxRealPath(buf
) );
450 return MYcopystring( wxFileFunctionsBuffer
);
456 ~user/ => user's home dir
457 If the environment variable a = "foo" and b = "bar" then:
474 /* input name in name, pathname output to buf. */
476 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
478 register wxChar
*d
, *s
, *nm
;
479 wxChar lnm
[_MAXPATHLEN
];
482 // Some compilers don't like this line.
483 // const wxChar trimchars[] = wxT("\n \t");
486 trimchars
[0] = wxT('\n');
487 trimchars
[1] = wxT(' ');
488 trimchars
[2] = wxT('\t');
492 const wxChar SEP
= wxT('\\');
494 const wxChar SEP
= wxT('/');
497 if (name
== NULL
|| *name
== wxT('\0'))
499 nm
= MYcopystring(name
); // Make a scratch copy
502 /* Skip leading whitespace and cr */
503 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
505 /* And strip off trailing whitespace and cr */
506 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
507 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
515 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
518 /* Expand inline environment variables */
536 while ((*d
++ = *s
) != 0) {
538 if (*s
== wxT('\\')) {
539 if ((*(d
- 1) = *++s
)) {
547 // No env variables on WinCE
550 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
552 if (*s
++ == wxT('$'))
555 register wxChar
*start
= d
;
556 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
557 register wxChar
*value
;
558 while ((*d
++ = *s
) != 0)
559 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
564 value
= wxGetenv(braces
? start
+ 1 : start
);
566 for ((d
= start
- 1); (*d
++ = *value
++) != 0;)
580 /* Expand ~ and ~user */
582 if (nm
[0] == wxT('~') && !q
)
585 if (nm
[1] == SEP
|| nm
[1] == 0)
587 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
588 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
593 { /* ~user/filename */
594 register wxChar
*nnm
;
595 register wxChar
*home
;
596 for (s
= nm
; *s
&& *s
!= SEP
; s
++)
600 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
601 was_sep
= (*s
== SEP
);
602 nnm
= *s
? s
+ 1 : s
;
604 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
605 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
606 if (was_sep
) /* replace only if it was there: */
617 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
619 while (wxT('\0') != (*d
++ = *s
++))
622 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
626 while ((*d
++ = *s
++) != 0)
630 delete[] nm_tmp
; // clean up alloc
631 /* Now clean up the buffer */
632 return wxRealPath(buf
);
635 /* Contract Paths to be build upon an environment variable
638 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
640 The call wxExpandPath can convert these back!
643 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
645 static wxChar dest
[_MAXPATHLEN
];
647 if (filename
== wxT(""))
648 return (wxChar
*) NULL
;
650 wxStrcpy (dest
, WXSTRINGCAST filename
);
652 wxUnix2DosFilename(dest
);
655 // Handle environment
659 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
660 (tcp
= wxStrstr (dest
, val
)) != NULL
)
662 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
665 wxStrcpy (tcp
, WXSTRINGCAST envname
);
666 wxStrcat (tcp
, wxT("}"));
667 wxStrcat (tcp
, wxFileFunctionsBuffer
);
671 // Handle User's home (ignore root homes!)
672 val
= wxGetUserHome (user
);
676 const size_t len
= wxStrlen(val
);
680 if (wxStrncmp(dest
, val
, len
) == 0)
682 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
684 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
685 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
686 wxStrcpy (dest
, wxFileFunctionsBuffer
);
692 // Return just the filename, not the path (basename)
693 wxChar
*wxFileNameFromPath (wxChar
*path
)
696 wxString n
= wxFileNameFromPath(p
);
698 return path
+ p
.length() - n
.length();
701 wxString
wxFileNameFromPath (const wxString
& path
)
704 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
706 wxString fullname
= name
;
709 fullname
<< wxFILE_SEP_EXT
<< ext
;
715 // Return just the directory, or NULL if no directory
717 wxPathOnly (wxChar
*path
)
721 static wxChar buf
[_MAXPATHLEN
];
724 wxStrcpy (buf
, path
);
726 int l
= wxStrlen(path
);
729 // Search backward for a backward or forward slash
732 #if defined(__WXMAC__) && !defined(__DARWIN__)
733 // Classic or Carbon CodeWarrior like
734 // Carbon with Apple DevTools is Unix like
735 if (path
[i
] == wxT(':') )
741 // Unix like or Windows
742 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
749 if (path
[i
] == wxT(']'))
758 #if defined(__WXMSW__) || defined(__OS2__)
759 // Try Drive specifier
760 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
762 // A:junk --> A:. (since A:.\junk Not A:\junk)
769 return (wxChar
*) NULL
;
772 // Return just the directory, or NULL if no directory
773 wxString
wxPathOnly (const wxString
& path
)
777 wxChar buf
[_MAXPATHLEN
];
780 wxStrcpy (buf
, WXSTRINGCAST path
);
782 int l
= path
.Length();
785 // Search backward for a backward or forward slash
788 #if defined(__WXMAC__) && !defined(__DARWIN__)
789 // Classic or Carbon CodeWarrior like
790 // Carbon with Apple DevTools is Unix like
791 if (path
[i
] == wxT(':') )
794 return wxString(buf
);
797 // Unix like or Windows
798 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
800 // Don't return an empty string
804 return wxString(buf
);
808 if (path
[i
] == wxT(']'))
811 return wxString(buf
);
817 #if defined(__WXMSW__) || defined(__OS2__)
818 // Try Drive specifier
819 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
821 // A:junk --> A:. (since A:.\junk Not A:\junk)
824 return wxString(buf
);
828 return wxString(wxT(""));
831 // Utility for converting delimiters in DOS filenames to UNIX style
832 // and back again - or we get nasty problems with delimiters.
833 // Also, convert to lower case, since case is significant in UNIX.
835 #if defined(__WXMAC__)
837 #if TARGET_API_MAC_OSX
838 #define kDefaultPathStyle kCFURLPOSIXPathStyle
840 #define kDefaultPathStyle kCFURLHFSPathStyle
843 wxString
wxMacFSRefToPath( const FSRef
*fsRef
, CFStringRef additionalPathComponent
)
846 fullURLRef
= CFURLCreateFromFSRef(NULL
, fsRef
);
847 if ( additionalPathComponent
)
849 CFURLRef parentURLRef
= fullURLRef
;
850 fullURLRef
= CFURLCreateCopyAppendingPathComponent(NULL
, parentURLRef
,
851 additionalPathComponent
,false);
852 CFRelease( parentURLRef
) ;
854 CFStringRef cfString
= CFURLCopyFileSystemPath(fullURLRef
, kDefaultPathStyle
);
855 CFRelease( fullURLRef
) ;
856 return wxMacCFStringHolder(cfString
).AsString(wxLocale::GetSystemEncoding());
859 OSStatus
wxMacPathToFSRef( const wxString
&path
, FSRef
*fsRef
)
861 OSStatus err
= noErr
;
862 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
, wxMacCFStringHolder(path
,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle
, false);
865 if ( CFURLGetFSRef(url
, fsRef
) == false )
876 wxString
wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname
)
878 CFStringRef cfname
= CFStringCreateWithCharacters( kCFAllocatorDefault
,
881 return wxMacCFStringHolder(cfname
).AsString() ;
884 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
887 if ( FSpMakeFSRef( spec
, &fsRef
) == noErr
)
889 return wxMacFSRefToPath( &fsRef
) ;
891 return wxEmptyString
;
894 void wxMacFilename2FSSpec( const wxString
& path
, FSSpec
*spec
)
896 OSStatus err
= noErr
;
898 wxMacPathToFSRef( path
, &fsRef
) ;
899 err
= FSRefMakeFSSpec( &fsRef
, spec
) ;
905 wxDos2UnixFilename (wxChar
*s
)
914 *s
= wxTolower (*s
); // Case INDEPENDENT
921 #if defined(__WXMSW__) || defined(__OS2__)
922 wxUnix2DosFilename (wxChar
*s
)
924 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
927 // Yes, I really mean this to happen under DOS only! JACS
928 #if defined(__WXMSW__) || defined(__OS2__)
939 // Concatenate two files to form third
941 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
944 if ( !wxGetTempFileName( wxT("cat"), outfile
) )
947 FILE *fp1
wxDUMMY_INITIALIZE(NULL
);
950 // Open the inputs and outputs
951 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
952 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
953 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
965 while ((ch
= getc (fp1
)) != EOF
)
966 (void) putc (ch
, fp3
);
969 while ((ch
= getc (fp2
)) != EOF
)
970 (void) putc (ch
, fp3
);
974 bool result
= wxRenameFile(outfile
, file3
);
980 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
982 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
983 // CopyFile() copies file attributes and modification time too, so use it
984 // instead of our code if available
986 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
987 if ( !::CopyFile(file1
, file2
, !overwrite
) )
989 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
990 file1
.c_str(), file2
.c_str());
994 #elif defined(__OS2__)
995 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1000 // get permissions of file1
1001 if ( wxStat( file1
.c_str(), &fbuf
) != 0 )
1003 // the file probably doesn't exist or we haven't the rights to read
1005 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1010 // open file1 for reading
1011 wxFile
fileIn(file1
, wxFile::read
);
1012 if ( !fileIn
.IsOpened() )
1015 // remove file2, if it exists. This is needed for creating
1016 // file2 with the correct permissions in the next step
1017 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1019 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1024 // reset the umask as we want to create the file with exactly the same
1025 // permissions as the original one
1028 // create file2 with the same permissions than file1 and open it for
1032 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1035 // copy contents of file1 to file2
1040 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1041 if ( fileIn
.Error() )
1048 if ( fileOut
.Write(buf
, count
) < count
)
1052 // we can expect fileIn to be closed successfully, but we should ensure
1053 // that fileOut was closed as some write errors (disk full) might not be
1054 // detected before doing this
1055 if ( !fileIn
.Close() || !fileOut
.Close() )
1058 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1059 // no chmod in VA. Should be some permission API for HPFS386 partitions
1061 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1063 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1067 #endif // OS/2 || Mac
1068 #endif // __WXMSW__ && __WIN32__
1074 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1077 // Normal system call
1078 if ( wxRename (file1
, file2
) == 0 )
1083 if (wxCopyFile(file1
, file2
)) {
1084 wxRemoveFile(file1
);
1091 bool wxRemoveFile(const wxString
& file
)
1093 #if defined(__VISUALC__) \
1094 || defined(__BORLANDC__) \
1095 || defined(__WATCOMC__) \
1096 || defined(__DMC__) \
1097 || defined(__GNUWIN32__) \
1098 || (defined(__MWERKS__) && defined(__MSL__))
1099 int res
= wxRemove(file
);
1100 #elif defined(__WXMAC__)
1101 int res
= unlink(wxFNCONV(file
));
1103 int res
= unlink(OS_FILENAME(file
));
1109 bool wxMkdir(const wxString
& dir
, int perm
)
1111 #if defined(__WXMAC__) && !defined(__UNIX__)
1112 return (mkdir( wxFNCONV(dir
) , 0 ) == 0);
1114 const wxChar
*dirname
= dir
.c_str();
1116 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1117 // for the GNU compiler
1118 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1121 if ( mkdir(wxFNCONV(dirname
)) != 0 )
1123 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1125 #elif defined(__OS2__)
1126 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1127 #elif defined(__DOS__)
1128 #if defined(__WATCOMC__)
1130 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1131 #elif defined(__DJGPP__)
1132 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1134 #error "Unsupported DOS compiler!"
1136 #else // !MSW, !DOS and !OS/2 VAC++
1139 if ( !CreateDirectory(dirname
, NULL
) )
1141 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1145 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1154 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1157 return false; //to be changed since rmdir exists in VMS7.x
1158 #elif defined(__OS2__)
1159 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1163 return (CreateDirectory(dir
, NULL
) != 0);
1165 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1171 // does the path exists? (may have or not '/' or '\\' at the end)
1172 bool wxPathExists(const wxChar
*pszPathName
)
1174 wxString
strPath(pszPathName
);
1176 #if defined(__WINDOWS__) || defined(__OS2__)
1177 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1178 // so remove all trailing backslashes from the path - but don't do this for
1179 // the pathes "d:\" (which are different from "d:") nor for just "\"
1180 while ( wxEndsWithPathSeparator(strPath
) )
1182 size_t len
= strPath
.length();
1183 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1186 strPath
.Truncate(len
- 1);
1188 #endif // __WINDOWS__
1191 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1192 if (strPath
.length() == 2 && strPath
[1u] == _T(':'))
1196 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1197 // stat() can't cope with network paths
1198 DWORD ret
= ::GetFileAttributes(strPath
);
1200 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1204 #ifndef __VISAGECPP__
1205 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1207 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1208 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1211 #endif // __WIN32__/!__WIN32__
1214 // Get a temporary filename, opening and closing the file.
1215 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1217 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1218 if ( filename
.empty() )
1222 wxStrcpy(buf
, filename
);
1224 buf
= MYcopystring(filename
);
1229 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1231 buf
= wxFileName::CreateTempFileName(prefix
);
1233 return !buf
.empty();
1236 // Get first file name matching given wild card.
1238 static wxDir
*gs_dir
= NULL
;
1239 static wxString gs_dirPath
;
1241 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1243 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1244 if ( gs_dirPath
.IsEmpty() )
1245 gs_dirPath
= wxT(".");
1246 if ( !wxEndsWithPathSeparator(gs_dirPath
) )
1247 gs_dirPath
<< wxFILE_SEP_PATH
;
1251 gs_dir
= new wxDir(gs_dirPath
);
1253 if ( !gs_dir
->IsOpened() )
1255 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1256 return wxEmptyString
;
1262 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1263 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1264 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1268 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1269 if ( result
.IsEmpty() )
1275 return gs_dirPath
+ result
;
1278 wxString
wxFindNextFile()
1280 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1283 gs_dir
->GetNext(&result
);
1285 if ( result
.IsEmpty() )
1291 return gs_dirPath
+ result
;
1295 // Get current working directory.
1296 // If buf is NULL, allocates space using new, else
1298 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1305 buf
= new wxChar
[sz
+ 1];
1308 bool ok
wxDUMMY_INITIALIZE(false);
1310 // for the compilers which have Unicode version of _getcwd(), call it
1311 // directly, for the others call the ANSI version and do the translation
1314 #else // wxUSE_UNICODE
1315 bool needsANSI
= true;
1317 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1318 // This is not legal code as the compiler
1319 // is allowed destroy the wxCharBuffer.
1320 // wxCharBuffer c_buffer(sz);
1321 // char *cbuf = (char*)(const char*)c_buffer;
1322 char cbuf
[_MAXPATHLEN
];
1326 #if wxUSE_UNICODE_MSLU
1327 if ( wxGetOsVersion() != wxWIN95
)
1329 char *cbuf
= NULL
; // never really used because needsANSI will always be false
1332 ok
= _wgetcwd(buf
, sz
) != NULL
;
1338 #endif // wxUSE_UNICODE
1340 #if defined(_MSC_VER) || defined(__MINGW32__)
1341 ok
= _getcwd(cbuf
, sz
) != NULL
;
1342 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1344 if ( getcwd( lbuf
, sizeof( lbuf
) ) )
1346 wxString
res( lbuf
, *wxConvCurrent
) ;
1347 wxStrcpy( buf
, res
) ;
1352 #elif defined(__OS2__)
1354 ULONG ulDriveNum
= 0;
1355 ULONG ulDriveMap
= 0;
1356 rc
= ::DosQueryCurrentDisk(&ulDriveNum
, &ulDriveMap
);
1361 rc
= ::DosQueryCurrentDir( 0 // current drive
1365 cbuf
[0] = 'A' + (ulDriveNum
- 1);
1370 #else // !Win32/VC++ !Mac !OS2
1371 ok
= getcwd(cbuf
, sz
) != NULL
;
1374 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1375 // finally convert the result to Unicode if needed
1376 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1377 #endif // wxUSE_UNICODE
1382 wxLogSysError(_("Failed to get the working directory"));
1384 // VZ: the old code used to return "." on error which didn't make any
1385 // sense at all to me - empty string is a better error indicator
1386 // (NULL might be even better but I'm afraid this could lead to
1387 // problems with the old code assuming the return is never NULL)
1390 else // ok, but we might need to massage the path into the right format
1393 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1394 // with / deliminers. We don't like that.
1395 for (wxChar
*ch
= buf
; *ch
; ch
++)
1397 if (*ch
== wxT('/'))
1402 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1403 // he needs Unix as opposed to Win32 pathnames
1404 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1405 // another example of DOS/Unix mix (Cygwin)
1406 wxString pathUnix
= buf
;
1407 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1408 #endif // __CYGWIN__
1423 wxChar
*buffer
= new wxChar
[_MAXPATHLEN
];
1424 wxGetWorkingDirectory(buffer
, _MAXPATHLEN
);
1425 wxString
str( buffer
);
1431 bool wxSetWorkingDirectory(const wxString
& d
)
1433 #if defined(__OS2__)
1434 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1435 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1436 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1437 #elif defined(__WINDOWS__)
1441 // No equivalent in WinCE
1444 return (bool)(SetCurrentDirectory(d
) != 0);
1447 // Must change drive, too.
1448 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1451 wxChar firstChar
= d
[0];
1455 firstChar
= firstChar
- 32;
1457 // To a drive number
1458 unsigned int driveNo
= firstChar
- 64;
1461 unsigned int noDrives
;
1462 _dos_setdrive(driveNo
, &noDrives
);
1465 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1473 // Get the OS directory if appropriate (such as the Windows directory).
1474 // On non-Windows platform, probably just return the empty string.
1475 wxString
wxGetOSDirectory()
1478 return wxString(wxT("\\Windows"));
1479 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1481 GetWindowsDirectory(buf
, 256);
1482 return wxString(buf
);
1483 #elif defined(__WXMAC__)
1484 return wxMacFindFolder(kOnSystemDisk
, 'macs', false);
1486 return wxEmptyString
;
1490 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1492 size_t len
= wxStrlen(pszFileName
);
1494 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1497 // find a file in a list of directories, returns false if not found
1498 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1500 // we assume that it's not empty
1501 wxCHECK_MSG( !wxIsEmpty(pszFile
), false,
1502 _T("empty file name in wxFindFileInPath"));
1504 // skip path separator in the beginning of the file name if present
1505 if ( wxIsPathSeparator(*pszFile
) )
1508 // copy the path (strtok will modify it)
1509 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1510 wxStrcpy(szPath
, pszPath
);
1513 wxChar
*pc
, *save_ptr
;
1514 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1516 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1518 // search for the file in this directory
1520 if ( !wxEndsWithPathSeparator(pc
) )
1521 strFile
+= wxFILE_SEP_PATH
;
1524 if ( wxFileExists(strFile
) ) {
1530 // suppress warning about unused variable save_ptr when wxStrtok() is a
1531 // macro which throws away its third argument
1536 return pc
!= NULL
; // if true => we breaked from the loop
1539 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1544 // it can be empty, but it shouldn't be NULL
1545 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1547 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1550 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1553 FILETIME creationTime
, lastAccessTime
, lastWriteTime
;
1554 HANDLE fileHandle
= ::CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1555 0, FILE_ATTRIBUTE_NORMAL
, 0);
1556 if (fileHandle
== INVALID_HANDLE_VALUE
)
1560 if (GetFileTime(fileHandle
, & creationTime
, & lastAccessTime
, & lastWriteTime
))
1562 CloseHandle(fileHandle
);
1564 wxDateTime dateTime
;
1566 if ( !::FileTimeToLocalFileTime(&lastWriteTime
, &ftLocal
) )
1568 wxLogLastError(_T("FileTimeToLocalFileTime"));
1572 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
1574 wxLogLastError(_T("FileTimeToSystemTime"));
1577 dateTime
.Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
1578 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
1579 return dateTime
.GetTicks();
1586 wxStat( filename
, &buf
);
1588 return buf
.st_mtime
;
1593 // Parses the filterStr, returning the number of filters.
1594 // Returns 0 if none or if there's a problem.
1595 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1597 int WXDLLEXPORT
wxParseCommonDialogsFilter(const wxString
& filterStr
, wxArrayString
& descriptions
, wxArrayString
& filters
)
1599 descriptions
.Clear();
1602 wxString
str(filterStr
);
1604 wxString description
, filter
;
1606 while( pos
!= wxNOT_FOUND
)
1608 pos
= str
.Find(wxT('|'));
1609 if ( pos
== wxNOT_FOUND
)
1611 // if there are no '|'s at all in the string just take the entire
1612 // string as filter and make description empty for later autocompletion
1613 if ( filters
.IsEmpty() )
1615 descriptions
.Add(wxEmptyString
);
1616 filters
.Add(filterStr
);
1620 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1626 description
= str
.Left(pos
);
1627 str
= str
.Mid(pos
+ 1);
1628 pos
= str
.Find(wxT('|'));
1629 if ( pos
== wxNOT_FOUND
)
1635 filter
= str
.Left(pos
);
1636 str
= str
.Mid(pos
+ 1);
1639 descriptions
.Add(description
);
1640 filters
.Add(filter
);
1643 #if defined(__WXMOTIF__)
1644 // split it so there is one wildcard per entry
1645 for( size_t i
= 0 ; i
< descriptions
.GetCount() ; i
++ )
1647 pos
= filters
[i
].Find(wxT(';'));
1648 if (pos
!= wxNOT_FOUND
)
1650 // first split only filters
1651 descriptions
.Insert(descriptions
[i
],i
+1);
1652 filters
.Insert(filters
[i
].Mid(pos
+1),i
+1);
1653 filters
[i
]=filters
[i
].Left(pos
);
1655 // autoreplace new filter in description with pattern:
1656 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1657 // cause split into:
1658 // C/C++ Files(*.cpp)|*.cpp
1659 // C/C++ Files(*.c;*.h)|*.c;*.h
1660 // and next iteration cause another split into:
1661 // C/C++ Files(*.cpp)|*.cpp
1662 // C/C++ Files(*.c)|*.c
1663 // C/C++ Files(*.h)|*.h
1664 for ( size_t k
=i
;k
<i
+2;k
++ )
1666 pos
= descriptions
[k
].Find(filters
[k
]);
1667 if (pos
!= wxNOT_FOUND
)
1669 wxString before
= descriptions
[k
].Left(pos
);
1670 wxString after
= descriptions
[k
].Mid(pos
+filters
[k
].Len());
1671 pos
= before
.Find(_T('('),true);
1672 if (pos
>before
.Find(_T(')'),true))
1674 before
= before
.Left(pos
+1);
1675 before
<< filters
[k
];
1676 pos
= after
.Find(_T(')'));
1677 int pos1
= after
.Find(_T('('));
1678 if (pos
!= wxNOT_FOUND
&& (pos
<pos1
|| pos1
==wxNOT_FOUND
))
1680 before
<< after
.Mid(pos
);
1681 descriptions
[k
] = before
;
1691 for( size_t j
= 0 ; j
< descriptions
.GetCount() ; j
++ )
1693 if ( descriptions
[j
] == wxEmptyString
&& filters
[j
] != wxEmptyString
)
1695 descriptions
[j
].Printf(_("Files (%s)"), filters
[j
].c_str());
1699 return filters
.GetCount();
1703 //------------------------------------------------------------------------
1704 // wild character routines
1705 //------------------------------------------------------------------------
1707 bool wxIsWild( const wxString
& pattern
)
1709 wxString tmp
= pattern
;
1710 wxChar
*pat
= WXSTRINGCAST(tmp
);
1715 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1726 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1728 * The match procedure is public domain code (from ircII's reg.c)
1731 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1735 /* Match if both are empty. */
1739 const wxChar
*m
= pat
.c_str(),
1750 if (dot_special
&& (*n
== wxT('.')))
1752 /* Never match so that hidden Unix files
1753 * are never found. */
1767 else if (*m
== wxT('?'))
1775 if (*m
== wxT('\\'))
1778 /* Quoting "nothing" is a bad thing */
1785 * If we are out of both strings or we just
1786 * saw a wildcard, then we can say we have a
1797 * We could check for *n == NULL at this point, but
1798 * since it's more common to have a character there,
1799 * check to see if they match first (m and n) and
1800 * then if they don't match, THEN we can check for
1818 * If there are no more characters in the
1819 * string, but we still need to find another
1820 * character (*m != NULL), then it will be
1821 * impossible to match it
1828 if (*np
== wxT(' '))
1854 #pragma warning(default:4706) // assignment within conditional expression