1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "filefn.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.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
60 #include <sys/types.h>
75 #include "wx/os2/private.h"
77 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
78 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
83 #endif // native Win compiler
99 #include <sys/unistd.h>
103 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
104 // this (3.1 I believe) and how to test for it.
105 // If this works for Borland 4.0 as well, then no worries.
114 #include "wx/setup.h"
117 // No, Cygwin doesn't appear to have fnmatch.h after all.
118 #if defined(HAVE_FNMATCH_H)
126 // TODO: Borland probably has _wgetcwd as well?
131 // ----------------------------------------------------------------------------
133 // ----------------------------------------------------------------------------
136 #define _MAXPATHLEN 1024
139 extern wxChar
*wxBuffer
;
142 # include "MoreFiles.h"
143 # include "MoreFilesExtras.h"
144 # include "FullPath.h"
145 # include "FSpCompat.h"
148 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
150 // ----------------------------------------------------------------------------
152 // ----------------------------------------------------------------------------
154 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
156 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
158 // VisualAge C++ V4.0 cannot have any external linkage const decs
159 // in headers included by more than one primary source
161 const off_t wxInvalidOffset
= (off_t
)-1;
164 // ----------------------------------------------------------------------------
166 // ----------------------------------------------------------------------------
168 // we need to translate Mac filenames before passing them to OS functions
169 #define OS_FILENAME(s) (s.fn_str())
171 // ============================================================================
173 // ============================================================================
175 void wxPathList::Add (const wxString
& path
)
177 wxStringList::Add (WXSTRINGCAST path
);
180 // Add paths e.g. from the PATH environment variable
181 void wxPathList::AddEnvList (const wxString
& envVariable
)
183 static const wxChar PATH_TOKS
[] =
185 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
190 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
193 wxChar
*s
= copystring (val
);
194 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
198 Add (copystring (token
));
201 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
202 Add (wxString(token
));
206 // suppress warning about unused variable save_ptr when wxStrtok() is a
207 // 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
.IsEmpty() )
222 if ( !Member(path_only
) )
227 bool wxPathList::Member (const wxString
& path
)
229 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
231 wxString
path2((wxChar
*) node
->Data ());
233 #if defined(__WINDOWS__) || 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
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
255 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
257 for (wxNode
* node
= First (); node
; node
= node
->Next ())
259 wxChar
*path
= (wxChar
*) node
->Data ();
260 wxStrcpy (wxFileFunctionsBuffer
, path
);
261 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
262 if (ch
!= wxT('\\') && ch
!= wxT('/'))
263 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
264 wxStrcat (wxFileFunctionsBuffer
, filename
);
266 Unix2DosFilename (wxFileFunctionsBuffer
);
268 if (wxFileExists (wxFileFunctionsBuffer
))
270 return wxString(wxFileFunctionsBuffer
); // Found!
274 return wxString(wxT("")); // Not found
277 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
279 wxString f
= FindValidPath(file
);
280 if ( wxIsAbsolutePath(f
) )
284 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
286 if ( !wxEndsWithPathSeparator(buf
) )
288 buf
+= wxFILE_SEP_PATH
;
296 wxFileExists (const wxString
& filename
)
298 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
299 // GetFileAttributes can copy with network paths
300 DWORD ret
= GetFileAttributes(filename
);
301 DWORD isDir
= (ret
& FILE_ATTRIBUTE_DIRECTORY
);
302 return ((ret
!= 0xffffffff) && (isDir
== 0));
305 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
313 wxIsAbsolutePath (const wxString
& filename
)
315 if (filename
!= wxT(""))
317 #if defined(__WXMAC__) && !defined(__DARWIN__)
318 // Classic or Carbon CodeWarrior like
319 // Carbon with Apple DevTools is Unix like
321 // This seems wrong to me, but there is no fix. since
322 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
323 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
324 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
327 // Unix like or Windows
328 if (filename
[0] == wxT('/'))
332 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
337 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
345 * Strip off any extension (dot something) from end of file,
346 * IF one exists. Inserts zero into buffer.
350 void wxStripExtension(wxChar
*buffer
)
352 int len
= wxStrlen(buffer
);
356 if (buffer
[i
] == wxT('.'))
365 void wxStripExtension(wxString
& buffer
)
367 size_t len
= buffer
.Length();
371 if (buffer
.GetChar(i
) == wxT('.'))
373 buffer
= buffer
.Left(i
);
380 // Destructive removal of /./ and /../ stuff
381 wxChar
*wxRealPath (wxChar
*path
)
384 static const wxChar SEP
= wxT('\\');
385 Unix2DosFilename(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
--);
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'))
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 (! IsAbsolutePath(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 copystring( wxRealPath(buf
) );
453 return copystring( 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
= copystring(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
)) {
551 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
553 if (*s
++ == wxT('$'))
556 register wxChar
*start
= d
;
557 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
558 register wxChar
*value
;
559 while ((*d
++ = *s
) != 0)
560 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
565 value
= wxGetenv(braces
? start
+ 1 : start
);
567 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
575 /* Expand ~ and ~user */
577 if (nm
[0] == wxT('~') && !q
)
580 if (nm
[1] == SEP
|| nm
[1] == 0)
582 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
583 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
588 { /* ~user/filename */
589 register wxChar
*nnm
;
590 register wxChar
*home
;
591 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
592 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
593 was_sep
= (*s
== SEP
);
594 nnm
= *s
? s
+ 1 : s
;
596 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
597 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
598 if (was_sep
) /* replace only if it was there: */
609 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
611 while (wxT('\0') != (*d
++ = *s
++))
614 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
618 while ((*d
++ = *s
++) != 0);
619 delete[] nm_tmp
; // clean up alloc
620 /* Now clean up the buffer */
621 return wxRealPath(buf
);
624 /* Contract Paths to be build upon an environment variable
627 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
629 The call wxExpandPath can convert these back!
632 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
634 static wxChar dest
[_MAXPATHLEN
];
636 if (filename
== wxT(""))
637 return (wxChar
*) NULL
;
639 wxStrcpy (dest
, WXSTRINGCAST filename
);
641 Unix2DosFilename(dest
);
644 // Handle environment
645 const wxChar
*val
= (const wxChar
*) NULL
;
646 wxChar
*tcp
= (wxChar
*) NULL
;
647 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
648 (tcp
= wxStrstr (dest
, val
)) != NULL
)
650 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
653 wxStrcpy (tcp
, WXSTRINGCAST envname
);
654 wxStrcat (tcp
, wxT("}"));
655 wxStrcat (tcp
, wxFileFunctionsBuffer
);
658 // Handle User's home (ignore root homes!)
660 if ((val
= wxGetUserHome (user
)) != NULL
&&
661 (len
= wxStrlen(val
)) > 2 &&
662 wxStrncmp(dest
, val
, len
) == 0)
664 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
666 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
668 // strcat(wxFileFunctionsBuffer, "\\");
670 // strcat(wxFileFunctionsBuffer, "/");
672 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
673 wxStrcpy (dest
, wxFileFunctionsBuffer
);
679 // Return just the filename, not the path
681 wxChar
*wxFileNameFromPath (wxChar
*path
)
685 register wxChar
*tcp
;
687 tcp
= path
+ wxStrlen (path
);
688 while (--tcp
>= path
)
690 #if defined(__WXMAC__) && !defined(__DARWIN__)
691 // Classic or Carbon CodeWarrior like
692 // Carbon with Apple DevTools is Unix like
693 if (*tcp
== wxT(':'))
696 // Unix like or Windows
697 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
701 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
705 #if defined(__WXMSW__) || defined(__WXPM__)
707 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
714 wxString
wxFileNameFromPath (const wxString
& path1
)
716 if (path1
!= wxT(""))
718 wxChar
*path
= WXSTRINGCAST path1
;
719 register wxChar
*tcp
;
721 tcp
= path
+ wxStrlen (path
);
722 while (--tcp
>= path
)
724 #if defined(__WXMAC__) && !defined(__DARWIN__)
725 // Classic or Carbon CodeWarrior like
726 // Carbon with Apple DevTools is Unix like
727 if (*tcp
== wxT(':') )
728 return wxString(tcp
+ 1);
730 // Unix like or Windows
731 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
732 return wxString(tcp
+ 1);
735 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
736 return wxString(tcp
+ 1);
739 #if defined(__WXMSW__) || defined(__WXPM__)
741 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
742 return wxString(path
+ 2);
745 // Yes, this should return the path, not an empty string, otherwise
746 // we get "thing.txt" -> "".
750 // Return just the directory, or NULL if no directory
752 wxPathOnly (wxChar
*path
)
756 static wxChar buf
[_MAXPATHLEN
];
759 wxStrcpy (buf
, path
);
761 int l
= wxStrlen(path
);
764 // Search backward for a backward or forward slash
767 #if defined(__WXMAC__) && !defined(__DARWIN__)
768 // Classic or Carbon CodeWarrior like
769 // Carbon with Apple DevTools is Unix like
770 if (path
[i
] == wxT(':') )
776 // Unix like or Windows
777 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
784 if (path
[i
] == wxT(']'))
793 #if defined(__WXMSW__) || defined(__WXPM__)
794 // Try Drive specifier
795 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
797 // A:junk --> A:. (since A:.\junk Not A:\junk)
804 return (wxChar
*) NULL
;
807 // Return just the directory, or NULL if no directory
808 wxString
wxPathOnly (const wxString
& path
)
812 wxChar buf
[_MAXPATHLEN
];
815 wxStrcpy (buf
, WXSTRINGCAST path
);
817 int l
= path
.Length();
820 // Search backward for a backward or forward slash
823 #if defined(__WXMAC__) && !defined(__DARWIN__)
824 // Classic or Carbon CodeWarrior like
825 // Carbon with Apple DevTools is Unix like
826 if (path
[i
] == wxT(':') )
829 return wxString(buf
);
832 // Unix like or Windows
833 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
836 return wxString(buf
);
840 if (path
[i
] == wxT(']'))
843 return wxString(buf
);
849 #if defined(__WXMSW__) || defined(__WXPM__)
850 // Try Drive specifier
851 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
853 // A:junk --> A:. (since A:.\junk Not A:\junk)
856 return wxString(buf
);
860 return wxString(wxT(""));
863 // Utility for converting delimiters in DOS filenames to UNIX style
864 // and back again - or we get nasty problems with delimiters.
865 // Also, convert to lower case, since case is significant in UNIX.
867 #if defined(__WXMAC__)
868 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
872 char thePath
[FILENAME_MAX
];
874 // convert the FSSpec to an FSRef
875 (void) FSpMakeFSRef( spec
, &theRef
);
876 // get the POSIX path associated with the FSRef
877 (void) FSRefMakePath( &theRef
, (UInt8
*)thePath
, sizeof(thePath
) );
879 // create path string for return value
880 wxString
result( thePath
) ;
885 // get length of path and allocate handle
886 FSpGetFullPath( spec
, &length
, &myPath
) ;
887 ::SetHandleSize( myPath
, length
+ 1 ) ;
889 (*myPath
)[length
] = 0 ;
890 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
891 (*myPath
)[length
-1] = 0 ;
893 // create path string for return value
894 wxString
result( (char*) *myPath
) ;
896 // free allocated handle
897 ::HUnlock( myPath
) ;
898 ::DisposeHandle( myPath
) ;
904 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
909 // get the FSRef associated with the POSIX path
910 (void) FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
911 // convert the FSRef to an FSSpec
912 (void) FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
914 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
919 // Mac file names are POSIX (Unix style) under Darwin
920 // therefore the conversion functions below are not needed
922 static char sMacFileNameConversion
[ 1000 ] ;
924 wxString
wxMac2UnixFilename (const char *str
)
926 char *s
= sMacFileNameConversion
;
930 memmove( s
+1 , s
,strlen( s
) + 1) ;
941 *s
= wxTolower(*s
); // Case INDEPENDENT
945 return wxString(sMacFileNameConversion
) ;
948 wxString
wxUnix2MacFilename (const char *str
)
950 char *s
= sMacFileNameConversion
;
956 // relative path , since it goes on with slash which is translated to a :
957 memmove( s
, s
+1 ,strlen( s
) ) ;
959 else if ( *s
== '/' )
961 // absolute path -> on mac just start with the drive name
962 memmove( s
, s
+1 ,strlen( s
) ) ;
966 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
970 if (*s
== '/' || *s
== '\\')
972 // convert any back-directory situations
973 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
976 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
984 return wxString (sMacFileNameConversion
) ;
987 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
989 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
992 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
994 wxString var
= wxUnix2MacFilename( path
) ;
995 wxMacFilename2FSSpec( var
, spec
) ;
997 #endif // ! __DARWIN__
1002 wxDos2UnixFilename (char *s
)
1011 *s
= wxTolower (*s
); // Case INDEPENDENT
1018 #if defined(__WXMSW__) || defined(__WXPM__)
1019 wxUnix2DosFilename (wxChar
*s
)
1021 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1024 // Yes, I really mean this to happen under DOS only! JACS
1025 #if defined(__WXMSW__) || defined(__WXPM__)
1036 // Concatenate two files to form third
1038 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1041 if ( !wxGetTempFileName("cat", outfile
) )
1044 FILE *fp1
= (FILE *) NULL
;
1045 FILE *fp2
= (FILE *) NULL
;
1046 FILE *fp3
= (FILE *) NULL
;
1047 // Open the inputs and outputs
1048 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
1049 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
1050 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
1062 while ((ch
= getc (fp1
)) != EOF
)
1063 (void) putc (ch
, fp3
);
1066 while ((ch
= getc (fp2
)) != EOF
)
1067 (void) putc (ch
, fp3
);
1071 bool result
= wxRenameFile(outfile
, file3
);
1077 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1079 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1080 // CopyFile() copies file attributes and modification time too, so use it
1081 // instead of our code if available
1083 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1084 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1085 #elif defined(__WXPM__)
1086 if (::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) == 0)
1093 // get permissions of file1
1094 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1096 // the file probably doesn't exist or we haven't the rights to read
1098 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1103 // open file1 for reading
1104 wxFile
fileIn(file1
, wxFile::read
);
1105 if ( !fileIn
.IsOpened() )
1108 // remove file2, if it exists. This is needed for creating
1109 // file2 with the correct permissions in the next step
1110 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1112 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1118 // reset the umask as we want to create the file with exactly the same
1119 // permissions as the original one
1120 mode_t oldUmask
= umask( 0 );
1123 // create file2 with the same permissions than file1 and open it for
1126 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1130 /// restore the old umask
1134 // copy contents of file1 to file2
1139 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1140 if ( fileIn
.Error() )
1147 if ( fileOut
.Write(buf
, count
) < count
)
1151 // we can expect fileIn to be closed successfully, but we should ensure
1152 // that fileOut was closed as some write errors (disk full) might not be
1153 // detected before doing this
1154 if ( !fileIn
.Close() || !fileOut
.Close() )
1157 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1158 // no chmod in VA. Should be some permission API for HPFS386 partitions
1160 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1162 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1166 #endif // OS/2 || Mac
1169 #endif // __WXMSW__ && __WIN32__
1173 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1175 // Normal system call
1176 if ( wxRename (file1
, file2
) == 0 )
1180 if (wxCopyFile(file1
, file2
)) {
1181 wxRemoveFile(file1
);
1188 bool wxRemoveFile(const wxString
& file
)
1190 #if defined(__VISUALC__) \
1191 || defined(__BORLANDC__) \
1192 || defined(__WATCOMC__) \
1193 || defined(__GNUWIN32__)
1194 int res
= wxRemove(file
);
1196 int res
= unlink(OS_FILENAME(file
));
1202 bool wxMkdir(const wxString
& dir
, int perm
)
1204 #if defined(__WXMAC__) && !defined(__UNIX__)
1205 return (mkdir( dir
, 0 ) == 0);
1207 const wxChar
*dirname
= dir
.c_str();
1209 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1210 // for the GNU compiler
1211 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1212 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1213 #elif defined(__WXPM__)
1214 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1215 #elif defined(__DOS__)
1216 #if defined(__WATCOMC__)
1218 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1219 #elif defined(__DJGPP__)
1220 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1222 #error "Unsupported DOS compiler!"
1224 #else // !MSW, !DOS and !OS/2 VAC++
1226 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1229 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1238 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1241 return FALSE
; //to be changed since rmdir exists in VMS7.x
1242 #elif defined(__WXPM__)
1243 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1247 return FALSE
; // What to do?
1249 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1255 // does the path exists? (may have or not '/' or '\\' at the end)
1256 bool wxPathExists(const wxChar
*pszPathName
)
1258 wxString
strPath(pszPathName
);
1260 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1261 // so remove all trailing backslashes from the path - but don't do this for
1262 // the pathes "d:\" (which are different from "d:") nor for just "\"
1263 while ( wxEndsWithPathSeparator(strPath
) )
1265 size_t len
= strPath
.length();
1266 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1269 strPath
.Truncate(len
- 1);
1271 #endif // __WINDOWS__
1273 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1274 // Stat can't cope with network paths
1275 DWORD ret
= GetFileAttributes(strPath
.c_str());
1276 DWORD isDir
= (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1277 return ((ret
!= 0xffffffff) && (isDir
!= 0));
1281 #ifndef __VISAGECPP__
1282 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1283 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1285 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1286 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1287 (st
.st_mode
== S_IFDIR
);
1293 // Get a temporary filename, opening and closing the file.
1294 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1296 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1297 if ( filename
.empty() )
1301 wxStrcpy(buf
, filename
);
1303 buf
= copystring(filename
);
1308 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1310 buf
= wxFileName::CreateTempFileName(prefix
);
1312 return !buf
.empty();
1315 // Get first file name matching given wild card.
1317 static wxDir
*gs_dir
= NULL
;
1318 static wxString gs_dirPath
;
1320 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1322 gs_dirPath
= wxPathOnly(spec
);
1323 if ( gs_dirPath
.IsEmpty() )
1324 gs_dirPath
= wxT(".");
1325 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1326 gs_dirPath
<< wxFILE_SEP_PATH
;
1330 gs_dir
= new wxDir(gs_dirPath
);
1332 if ( !gs_dir
->IsOpened() )
1334 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1335 return wxEmptyString
;
1341 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1342 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1343 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1347 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1348 if ( result
.IsEmpty() )
1354 return gs_dirPath
+ result
;
1357 wxString
wxFindNextFile()
1359 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1362 gs_dir
->GetNext(&result
);
1364 if ( result
.IsEmpty() )
1370 return gs_dirPath
+ result
;
1374 // Get current working directory.
1375 // If buf is NULL, allocates space using new, else
1377 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1381 buf
= new wxChar
[sz
+ 1];
1386 // for the compilers which have Unicode version of _getcwd(), call it
1387 // directly, for the others call the ANSI version and do the translation
1390 ok
= _wgetcwd(buf
, sz
) != NULL
;
1391 #else // !HAVE_WGETCWD
1392 wxCharBuffer
cbuf(sz
);
1396 #if !wxUSE_UNICODE || !defined(HAVE_WGETCWD)
1398 ok
= _getcwd(buf
, sz
) != NULL
;
1399 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1404 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1406 pb
.ioRefNum
= LMGetCurApRefNum();
1408 error
= PBGetFCBInfoSync(&pb
);
1409 if ( error
== noErr
)
1411 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1412 cwdSpec
.parID
= pb
.ioFCBParID
;
1413 cwdSpec
.name
[0] = 0 ;
1414 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1416 strcpy( buf
, res
) ;
1417 buf
[res
.length()]=0 ;
1425 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1427 rc
= ::DosQueryCurrentDir( 0 // current drive
1432 #else // !Win32/VC++ !Mac !OS2
1433 ok
= getcwd(buf
, sz
) != NULL
;
1435 #endif // !wxUSE_UNICODE || !HAVE_WGETCWD
1439 wxLogSysError(_("Failed to get the working directory"));
1441 // VZ: the old code used to return "." on error which didn't make any
1442 // sense at all to me - empty string is a better error indicator
1443 // (NULL might be even better but I'm afraid this could lead to
1444 // problems with the old code assuming the return is never NULL)
1447 else // ok, but we might need to massage the path into the right format
1450 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1451 // with / deliminers. We don't like that.
1452 for (wxChar
*ch
= buf
; *ch
; ch
++)
1454 if (*ch
== wxT('/'))
1460 // another example of DOS/Unix mix
1461 wxString pathUnix
= buf
;
1462 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1463 #endif // __CYGWIN10__
1465 // finally convert the result to Unicode if needed
1466 #if wxUSE_UNICODE && !defined(HAVE_WGETCWD)
1467 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1468 #endif // wxUSE_UNICODE
1478 // we can't create wxStringBuffer object inline: Sun CC generates buggy
1479 // code in this case!
1481 wxStringBuffer
buf(str
, _MAXPATHLEN
);
1482 wxGetWorkingDirectory(buf
, _MAXPATHLEN
);
1488 bool wxSetWorkingDirectory(const wxString
& d
)
1490 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1491 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1492 #elif defined(__WXPM__)
1493 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1494 #elif defined(__WINDOWS__)
1497 return (bool)(SetCurrentDirectory(d
) != 0);
1499 // Must change drive, too.
1500 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1503 wxChar firstChar
= d
[0];
1507 firstChar
= firstChar
- 32;
1509 // To a drive number
1510 unsigned int driveNo
= firstChar
- 64;
1513 unsigned int noDrives
;
1514 _dos_setdrive(driveNo
, &noDrives
);
1517 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1525 // Get the OS directory if appropriate (such as the Windows directory).
1526 // On non-Windows platform, probably just return the empty string.
1527 wxString
wxGetOSDirectory()
1529 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1531 GetWindowsDirectory(buf
, 256);
1532 return wxString(buf
);
1534 return wxEmptyString
;
1538 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1540 size_t len
= wxStrlen(pszFileName
);
1542 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1545 // find a file in a list of directories, returns false if not found
1546 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1548 // we assume that it's not empty
1549 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1550 _T("empty file name in wxFindFileInPath"));
1552 // skip path separator in the beginning of the file name if present
1553 if ( wxIsPathSeparator(*pszFile
) )
1556 // copy the path (strtok will modify it)
1557 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1558 wxStrcpy(szPath
, pszPath
);
1561 wxChar
*pc
, *save_ptr
;
1562 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1564 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1566 // search for the file in this directory
1568 if ( !wxEndsWithPathSeparator(pc
) )
1569 strFile
+= wxFILE_SEP_PATH
;
1572 if ( FileExists(strFile
) ) {
1578 // suppress warning about unused variable save_ptr when wxStrtok() is a
1579 // macro which throws away its third argument
1584 return pc
!= NULL
; // if true => we breaked from the loop
1587 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1592 // it can be empty, but it shouldn't be NULL
1593 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1595 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1598 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1602 wxStat(filename
.fn_str(), &buf
);
1603 return buf
.st_mtime
;
1607 //------------------------------------------------------------------------
1608 // wild character routines
1609 //------------------------------------------------------------------------
1611 bool wxIsWild( const wxString
& pattern
)
1613 wxString tmp
= pattern
;
1614 wxChar
*pat
= WXSTRINGCAST(tmp
);
1617 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1627 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1629 #if defined(HAVE_FNMATCH_H)
1631 // this probably won't work well for multibyte chars in Unicode mode?
1633 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1635 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1639 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1642 * WARNING: this code is broken!
1645 wxString tmp1
= pat
;
1646 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1647 wxString tmp2
= text
;
1648 wxChar
*str
= WXSTRINGCAST(tmp2
);
1651 bool done
= FALSE
, ret_code
, ok
;
1652 // Below is for vi fans
1653 const wxChar OB
= wxT('{'), CB
= wxT('}');
1655 // dot_special means '.' only matches '.'
1656 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1659 while ((*pattern
!= wxT('\0')) && (!done
)
1660 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1664 if (*pattern
!= wxT('\0'))
1670 while ((*str
!=wxT('\0'))
1671 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1674 while (*str
!= wxT('\0'))
1676 while (*pattern
!= wxT('\0'))
1683 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1687 if (*pattern
== wxT('\\')) {
1689 if (*pattern
== wxT('\0')) {
1694 if (*(pattern
+ 1) == wxT('-')) {
1697 if (*pattern
== wxT(']')) {
1701 if (*pattern
== wxT('\\')) {
1703 if (*pattern
== wxT('\0')) {
1708 if ((*str
< c
) || (*str
> *pattern
)) {
1712 } else if (*pattern
!= *str
) {
1717 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1718 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1722 if (*pattern
!= wxT('\0')) {
1732 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1735 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1736 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1737 if (*pattern
== wxT('\\'))
1739 ok
= (*pattern
++ == *cp
++);
1741 if (*pattern
== wxT('\0')) {
1747 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1748 if (*++pattern
== wxT('\\')) {
1749 if (*++pattern
== CB
)
1754 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1755 if (*++pattern
== wxT('\\')) {
1756 if (*++pattern
== CB
|| *pattern
== wxT(','))
1761 if (*pattern
!= wxT('\0'))
1766 if (*str
== *pattern
) {
1773 while (*pattern
== wxT('*'))
1775 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1781 #pragma warning(default:4706) // assignment within conditional expression
1784 //------------------------------------------------------------------------
1785 // Missing functions in Unicode for Win9x
1786 //------------------------------------------------------------------------
1788 // NB: MSLU only covers Win32 API, it doesn't provide Unicode implementation of
1789 // libc functions. Unfortunately, some of MSVCRT wchar_t functions
1790 // (e.g. _wopen) don't work on Windows 9x, so we have to workaround it
1791 // by calling the char version. We still want to use wchar_t version on
1792 // NT/2000/XP, though, because they allow for Unicode file names.
1793 #if wxUSE_UNICODE_MSLU
1795 #if defined( __VISUALC__ ) \
1796 || ( defined(__MINGW32__) && wxCHECK_W32API_VERSION( 0, 5 ) ) \
1797 || ( defined(__MWERKS__) && defined(__WXMSW__) )
1798 WXDLLEXPORT
int wxOpen(const wxChar
*name
, int flags
, int mode
)
1800 if ( wxGetOsVersion() == wxWINDOWS_NT
)
1801 return _wopen(name
, flags
, mode
);
1803 return _open(wxConvFile
.cWX2MB(name
), flags
, mode
);
1807 #endif // wxUSE_UNICODE_MSLU