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>
76 #include "wx/os2/private.h"
78 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
79 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
84 #endif // native Win compiler
97 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
98 // this (3.1 I believe) and how to test for it.
99 // If this works for Borland 4.0 as well, then no worries.
108 #include "wx/setup.h"
111 // No, Cygwin doesn't appear to have fnmatch.h after all.
112 #if defined(HAVE_FNMATCH_H)
118 #include "wx/msw/mslu.h"
120 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
122 // note that it must be included after <windows.h>
125 #include <sys/cygwin.h>
129 #include <sys/unistd.h>
131 #endif // __GNUWIN32__
132 #endif // __WINDOWS__
134 // TODO: Borland probably has _wgetcwd as well?
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
144 #define _MAXPATHLEN 1024
148 # include "MoreFiles.h"
149 # include "MoreFilesExtras.h"
150 # include "FullPath.h"
151 # include "FSpCompat.h"
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
158 // MT-FIXME: get rid of this horror and all code using it
159 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
161 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
163 // VisualAge C++ V4.0 cannot have any external linkage const decs
164 // in headers included by more than one primary source
166 const off_t wxInvalidOffset
= (off_t
)-1;
169 // ----------------------------------------------------------------------------
171 // ----------------------------------------------------------------------------
173 // we need to translate Mac filenames before passing them to OS functions
174 #define OS_FILENAME(s) (s.fn_str())
176 // ============================================================================
178 // ============================================================================
180 #ifdef wxNEED_WX_UNISTD_H
182 WXDLLEXPORT
int wxStat( const wxChar
*file_name
, wxStructStat
*buf
)
184 return stat( wxConvFile
.cWX2MB( file_name
), buf
);
187 WXDLLEXPORT
int wxAccess( const wxChar
*pathname
, int mode
)
189 return access( wxConvFile
.cWX2MB( pathname
), mode
);
192 WXDLLEXPORT
int wxOpen( const wxChar
*pathname
, int flags
, mode_t mode
)
194 return open( wxConvFile
.cWX2MB( pathname
), flags
, mode
);
198 // wxNEED_WX_UNISTD_H
200 // ----------------------------------------------------------------------------
202 // ----------------------------------------------------------------------------
204 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
206 void wxPathList::Add (const wxString
& path
)
208 wxStringList::Add (WXSTRINGCAST path
);
211 // Add paths e.g. from the PATH environment variable
212 void wxPathList::AddEnvList (const wxString
& envVariable
)
214 static const wxChar PATH_TOKS
[] =
216 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
221 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
224 wxChar
*s
= copystring (val
);
225 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
229 Add (copystring (token
));
232 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
233 Add (wxString(token
));
237 // suppress warning about unused variable save_ptr when wxStrtok() is a
238 // macro which throws away its third argument
245 // Given a full filename (with path), ensure that that file can
246 // be accessed again USING FILENAME ONLY by adding the path
247 // to the list if not already there.
248 void wxPathList::EnsureFileAccessible (const wxString
& path
)
250 wxString
path_only(wxPathOnly(path
));
251 if ( !path_only
.IsEmpty() )
253 if ( !Member(path_only
) )
258 bool wxPathList::Member (const wxString
& path
)
260 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
262 wxString
path2((wxChar
*) node
->Data ());
264 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
266 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
268 // Case sensitive File System
269 path
.CompareTo (path2
) == 0
277 wxString
wxPathList::FindValidPath (const wxString
& file
)
279 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
280 return wxString(wxFileFunctionsBuffer
);
282 wxChar buf
[_MAXPATHLEN
];
283 wxStrcpy(buf
, wxFileFunctionsBuffer
);
285 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
286 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
288 for (wxNode
* node
= First (); node
; node
= node
->Next ())
290 wxChar
*path
= (wxChar
*) node
->Data ();
291 wxStrcpy (wxFileFunctionsBuffer
, path
);
292 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
293 if (ch
!= wxT('\\') && ch
!= wxT('/'))
294 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
295 wxStrcat (wxFileFunctionsBuffer
, filename
);
297 Unix2DosFilename (wxFileFunctionsBuffer
);
299 if (wxFileExists (wxFileFunctionsBuffer
))
301 return wxString(wxFileFunctionsBuffer
); // Found!
305 return wxString(wxT("")); // Not found
308 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
310 wxString f
= FindValidPath(file
);
311 if ( wxIsAbsolutePath(f
) )
315 wxGetWorkingDirectory(wxStringBuffer(buf
, _MAXPATHLEN
), _MAXPATHLEN
);
317 if ( !wxEndsWithPathSeparator(buf
) )
319 buf
+= wxFILE_SEP_PATH
;
327 wxFileExists (const wxString
& filename
)
329 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
330 // GetFileAttributes can copy with network paths unlike stat()
331 DWORD ret
= ::GetFileAttributes(filename
);
333 return (ret
!= (DWORD
)-1) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
336 if ( !filename
.empty() && wxStat( filename
, &stbuf
) == 0 )
344 wxIsAbsolutePath (const wxString
& filename
)
346 if (filename
!= wxT(""))
348 #if defined(__WXMAC__) && !defined(__DARWIN__)
349 // Classic or Carbon CodeWarrior like
350 // Carbon with Apple DevTools is Unix like
352 // This seems wrong to me, but there is no fix. since
353 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
354 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
355 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
358 // Unix like or Windows
359 if (filename
[0] == wxT('/'))
363 if ((filename
[0] == wxT('[') && filename
[1] != wxT('.')))
368 if (filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':')))
376 * Strip off any extension (dot something) from end of file,
377 * IF one exists. Inserts zero into buffer.
381 void wxStripExtension(wxChar
*buffer
)
383 int len
= wxStrlen(buffer
);
387 if (buffer
[i
] == wxT('.'))
396 void wxStripExtension(wxString
& buffer
)
398 size_t len
= buffer
.Length();
402 if (buffer
.GetChar(i
) == wxT('.'))
404 buffer
= buffer
.Left(i
);
411 // Destructive removal of /./ and /../ stuff
412 wxChar
*wxRealPath (wxChar
*path
)
415 static const wxChar SEP
= wxT('\\');
416 Unix2DosFilename(path
);
418 static const wxChar SEP
= wxT('/');
420 if (path
[0] && path
[1]) {
421 /* MATTHEW: special case "/./x" */
423 if (path
[2] == SEP
&& path
[1] == wxT('.'))
431 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
434 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
435 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
436 && (q
- 1 <= path
|| q
[-1] != SEP
))
439 if (path
[0] == wxT('\0'))
445 /* Check that path[2] is NULL! */
446 else if (path
[1] == wxT(':') && !path
[2])
455 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
464 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
466 if (filename
== wxT(""))
467 return (wxChar
*) NULL
;
469 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
470 wxChar buf
[_MAXPATHLEN
];
472 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
473 wxChar ch
= buf
[wxStrlen(buf
) - 1];
475 if (ch
!= wxT('\\') && ch
!= wxT('/'))
476 wxStrcat(buf
, wxT("\\"));
479 wxStrcat(buf
, wxT("/"));
481 wxStrcat(buf
, wxFileFunctionsBuffer
);
482 return copystring( wxRealPath(buf
) );
484 return copystring( wxFileFunctionsBuffer
);
490 ~user/ => user's home dir
491 If the environment variable a = "foo" and b = "bar" then:
508 /* input name in name, pathname output to buf. */
510 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
512 register wxChar
*d
, *s
, *nm
;
513 wxChar lnm
[_MAXPATHLEN
];
516 // Some compilers don't like this line.
517 // const wxChar trimchars[] = wxT("\n \t");
520 trimchars
[0] = wxT('\n');
521 trimchars
[1] = wxT(' ');
522 trimchars
[2] = wxT('\t');
526 const wxChar SEP
= wxT('\\');
528 const wxChar SEP
= wxT('/');
531 if (name
== NULL
|| *name
== wxT('\0'))
533 nm
= copystring(name
); // Make a scratch copy
536 /* Skip leading whitespace and cr */
537 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
539 /* And strip off trailing whitespace and cr */
540 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
541 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
549 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
552 /* Expand inline environment variables */
570 while ((*d
++ = *s
) != 0) {
572 if (*s
== wxT('\\')) {
573 if ((*(d
- 1) = *++s
)) {
582 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
584 if (*s
++ == wxT('$'))
587 register wxChar
*start
= d
;
588 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
589 register wxChar
*value
;
590 while ((*d
++ = *s
) != 0)
591 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
596 value
= wxGetenv(braces
? start
+ 1 : start
);
598 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
606 /* Expand ~ and ~user */
608 if (nm
[0] == wxT('~') && !q
)
611 if (nm
[1] == SEP
|| nm
[1] == 0)
613 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
614 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
619 { /* ~user/filename */
620 register wxChar
*nnm
;
621 register wxChar
*home
;
622 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
623 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
624 was_sep
= (*s
== SEP
);
625 nnm
= *s
? s
+ 1 : s
;
627 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
628 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
629 if (was_sep
) /* replace only if it was there: */
640 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
642 while (wxT('\0') != (*d
++ = *s
++))
645 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
649 while ((*d
++ = *s
++) != 0);
650 delete[] nm_tmp
; // clean up alloc
651 /* Now clean up the buffer */
652 return wxRealPath(buf
);
655 /* Contract Paths to be build upon an environment variable
658 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
660 The call wxExpandPath can convert these back!
663 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
665 static wxChar dest
[_MAXPATHLEN
];
667 if (filename
== wxT(""))
668 return (wxChar
*) NULL
;
670 wxStrcpy (dest
, WXSTRINGCAST filename
);
672 Unix2DosFilename(dest
);
675 // Handle environment
676 const wxChar
*val
= (const wxChar
*) NULL
;
677 wxChar
*tcp
= (wxChar
*) NULL
;
678 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
679 (tcp
= wxStrstr (dest
, val
)) != NULL
)
681 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
684 wxStrcpy (tcp
, WXSTRINGCAST envname
);
685 wxStrcat (tcp
, wxT("}"));
686 wxStrcat (tcp
, wxFileFunctionsBuffer
);
689 // Handle User's home (ignore root homes!)
691 if ((val
= wxGetUserHome (user
)) != NULL
&&
692 (len
= wxStrlen(val
)) > 2 &&
693 wxStrncmp(dest
, val
, len
) == 0)
695 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
697 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
698 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
699 wxStrcpy (dest
, wxFileFunctionsBuffer
);
705 // Return just the filename, not the path (basename)
706 wxChar
*wxFileNameFromPath (wxChar
*path
)
709 wxString n
= wxFileNameFromPath(p
);
711 return path
+ p
.length() - n
.length();
714 wxString
wxFileNameFromPath (const wxString
& path
)
717 wxFileName::SplitPath(path
, NULL
, &name
, &ext
);
719 wxString fullname
= name
;
722 fullname
<< wxFILE_SEP_EXT
<< ext
;
728 // Return just the directory, or NULL if no directory
730 wxPathOnly (wxChar
*path
)
734 static wxChar buf
[_MAXPATHLEN
];
737 wxStrcpy (buf
, path
);
739 int l
= wxStrlen(path
);
742 // Search backward for a backward or forward slash
745 #if defined(__WXMAC__) && !defined(__DARWIN__)
746 // Classic or Carbon CodeWarrior like
747 // Carbon with Apple DevTools is Unix like
748 if (path
[i
] == wxT(':') )
754 // Unix like or Windows
755 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
762 if (path
[i
] == wxT(']'))
771 #if defined(__WXMSW__) || defined(__WXPM__)
772 // Try Drive specifier
773 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
775 // A:junk --> A:. (since A:.\junk Not A:\junk)
782 return (wxChar
*) NULL
;
785 // Return just the directory, or NULL if no directory
786 wxString
wxPathOnly (const wxString
& path
)
790 wxChar buf
[_MAXPATHLEN
];
793 wxStrcpy (buf
, WXSTRINGCAST path
);
795 int l
= path
.Length();
798 // Search backward for a backward or forward slash
801 #if defined(__WXMAC__) && !defined(__DARWIN__)
802 // Classic or Carbon CodeWarrior like
803 // Carbon with Apple DevTools is Unix like
804 if (path
[i
] == wxT(':') )
807 return wxString(buf
);
810 // Unix like or Windows
811 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
814 return wxString(buf
);
818 if (path
[i
] == wxT(']'))
821 return wxString(buf
);
827 #if defined(__WXMSW__) || defined(__WXPM__)
828 // Try Drive specifier
829 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
831 // A:junk --> A:. (since A:.\junk Not A:\junk)
834 return wxString(buf
);
838 return wxString(wxT(""));
841 // Utility for converting delimiters in DOS filenames to UNIX style
842 // and back again - or we get nasty problems with delimiters.
843 // Also, convert to lower case, since case is significant in UNIX.
845 #if defined(__WXMAC__)
846 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
853 Boolean isDirectory
= false;
854 Str255 theParentPath
= "\p";
855 FSSpec theParentSpec
;
857 char theFileName
[FILENAME_MAX
];
858 char thePath
[FILENAME_MAX
];
862 // GD: Separate file name from path and make a FSRef to the parent
863 // directory. This is necessary since FSRefs cannot reference files
864 // that have not yet been created.
865 // Based on example code from Apple Technical Note TN2022
866 // http://developer.apple.com/technotes/tn/tn2022.html
868 // check whether we are converting a directory
869 isDirectory
= ((spec
->name
)[spec
->name
[0]] == ':');
870 // count length of file name
871 for (i
= spec
->name
[0] - (isDirectory
? 1 : 0); ((spec
->name
[i
] != ':') && (i
> 0)); i
--);
873 // prepend path separator since it will later be appended to the path
874 theFileName
[0] = wxFILE_SEP_PATH
;
875 for (j
= i
+ 1; j
<= spec
->name
[0] - (isDirectory
? 1 : 0); j
++) {
876 theFileName
[j
- i
] = spec
->name
[j
];
878 theFileName
[j
- i
] = '\0';
880 for (j
= 1; j
<= i
; j
++) {
881 theParentPath
[++theParentPath
[0]] = spec
->name
[j
];
883 theErr
= FSMakeFSSpec(spec
->vRefNum
, spec
->parID
, theParentPath
, &theParentSpec
);
884 if (theErr
== noErr
) {
885 // convert the FSSpec to an FSRef
886 theErr
= FSpMakeFSRef(&theParentSpec
, &theParentRef
);
888 if (theErr
== noErr
) {
889 // get the POSIX path associated with the FSRef
890 theStatus
= FSRefMakePath(&theParentRef
,
891 (UInt8
*)thePath
, sizeof(thePath
));
893 if (theStatus
== noErr
) {
894 // append file name to path
895 // includes previously prepended path separator
896 strcat(thePath
, theFileName
);
899 // create path string for return value
900 wxString
result( thePath
) ;
905 // get length of path and allocate handle
906 FSpGetFullPath( spec
, &length
, &myPath
) ;
907 ::SetHandleSize( myPath
, length
+ 1 ) ;
909 (*myPath
)[length
] = 0 ;
910 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
911 (*myPath
)[length
-1] = 0 ;
913 // create path string for return value
914 wxString
result( (char*) *myPath
) ;
916 // free allocated handle
917 ::HUnlock( myPath
) ;
918 ::DisposeHandle( myPath
) ;
924 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
929 // get the FSRef associated with the POSIX path
930 (void) FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
931 // convert the FSRef to an FSSpec
932 (void) FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
934 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
939 // Mac file names are POSIX (Unix style) under Darwin
940 // therefore the conversion functions below are not needed
942 static char sMacFileNameConversion
[ 1000 ] ;
944 wxString
wxMac2UnixFilename (const char *str
)
946 char *s
= sMacFileNameConversion
;
950 memmove( s
+1 , s
,strlen( s
) + 1) ;
961 *s
= wxTolower(*s
); // Case INDEPENDENT
965 return wxString(sMacFileNameConversion
) ;
968 wxString
wxUnix2MacFilename (const char *str
)
970 char *s
= sMacFileNameConversion
;
976 // relative path , since it goes on with slash which is translated to a :
977 memmove( s
, s
+1 ,strlen( s
) ) ;
979 else if ( *s
== '/' )
981 // absolute path -> on mac just start with the drive name
982 memmove( s
, s
+1 ,strlen( s
) ) ;
986 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
990 if (*s
== '/' || *s
== '\\')
992 // convert any back-directory situations
993 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
996 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
1004 return wxString (sMacFileNameConversion
) ;
1007 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
1009 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
1012 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
1014 wxString var
= wxUnix2MacFilename( path
) ;
1015 wxMacFilename2FSSpec( var
, spec
) ;
1017 #endif // ! __DARWIN__
1022 wxDos2UnixFilename (char *s
)
1031 *s
= wxTolower (*s
); // Case INDEPENDENT
1038 #if defined(__WXMSW__) || defined(__WXPM__)
1039 wxUnix2DosFilename (wxChar
*s
)
1041 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1044 // Yes, I really mean this to happen under DOS only! JACS
1045 #if defined(__WXMSW__) || defined(__WXPM__)
1056 // Concatenate two files to form third
1058 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1061 if ( !wxGetTempFileName("cat", outfile
) )
1064 FILE *fp1
= (FILE *) NULL
;
1065 FILE *fp2
= (FILE *) NULL
;
1066 FILE *fp3
= (FILE *) NULL
;
1067 // Open the inputs and outputs
1068 if ((fp1
= wxFopen ( file1
, wxT("rb"))) == NULL
||
1069 (fp2
= wxFopen ( file2
, wxT("rb"))) == NULL
||
1070 (fp3
= wxFopen ( outfile
, wxT("wb"))) == NULL
)
1082 while ((ch
= getc (fp1
)) != EOF
)
1083 (void) putc (ch
, fp3
);
1086 while ((ch
= getc (fp2
)) != EOF
)
1087 (void) putc (ch
, fp3
);
1091 bool result
= wxRenameFile(outfile
, file3
);
1097 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1099 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1100 // CopyFile() copies file attributes and modification time too, so use it
1101 // instead of our code if available
1103 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1104 if ( !::CopyFile(file1
, file2
, !overwrite
) )
1106 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1107 file1
.c_str(), file2
.c_str());
1111 #elif defined(__WXPM__)
1112 if ( ::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) != 0 )
1117 // get permissions of file1
1118 if ( wxStat( file1
, &fbuf
) != 0 )
1120 // the file probably doesn't exist or we haven't the rights to read
1122 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1127 // open file1 for reading
1128 wxFile
fileIn(file1
, wxFile::read
);
1129 if ( !fileIn
.IsOpened() )
1132 // remove file2, if it exists. This is needed for creating
1133 // file2 with the correct permissions in the next step
1134 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1136 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1142 // reset the umask as we want to create the file with exactly the same
1143 // permissions as the original one
1144 mode_t oldUmask
= umask( 0 );
1147 // create file2 with the same permissions than file1 and open it for
1150 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1154 /// restore the old umask
1158 // copy contents of file1 to file2
1163 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1164 if ( fileIn
.Error() )
1171 if ( fileOut
.Write(buf
, count
) < count
)
1175 // we can expect fileIn to be closed successfully, but we should ensure
1176 // that fileOut was closed as some write errors (disk full) might not be
1177 // detected before doing this
1178 if ( !fileIn
.Close() || !fileOut
.Close() )
1181 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1182 // no chmod in VA. Should be some permission API for HPFS386 partitions
1184 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1186 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1190 #endif // OS/2 || Mac
1191 #endif // __WXMSW__ && __WIN32__
1197 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1199 // Normal system call
1200 if ( wxRename (file1
, file2
) == 0 )
1204 if (wxCopyFile(file1
, file2
)) {
1205 wxRemoveFile(file1
);
1212 bool wxRemoveFile(const wxString
& file
)
1214 #if defined(__VISUALC__) \
1215 || defined(__BORLANDC__) \
1216 || defined(__WATCOMC__) \
1217 || defined(__GNUWIN32__)
1218 int res
= wxRemove(file
);
1220 int res
= unlink(OS_FILENAME(file
));
1226 bool wxMkdir(const wxString
& dir
, int perm
)
1228 #if defined(__WXMAC__) && !defined(__UNIX__)
1229 return (mkdir( dir
, 0 ) == 0);
1231 const wxChar
*dirname
= dir
.c_str();
1233 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1234 // for the GNU compiler
1235 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1236 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1237 #elif defined(__WXPM__)
1238 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1239 #elif defined(__DOS__)
1240 #if defined(__WATCOMC__)
1242 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1243 #elif defined(__DJGPP__)
1244 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1246 #error "Unsupported DOS compiler!"
1248 #else // !MSW, !DOS and !OS/2 VAC++
1250 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1253 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1262 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1265 return FALSE
; //to be changed since rmdir exists in VMS7.x
1266 #elif defined(__WXPM__)
1267 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1271 return FALSE
; // What to do?
1273 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1279 // does the path exists? (may have or not '/' or '\\' at the end)
1280 bool wxPathExists(const wxChar
*pszPathName
)
1282 wxString
strPath(pszPathName
);
1285 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1286 // so remove all trailing backslashes from the path - but don't do this for
1287 // the pathes "d:\" (which are different from "d:") nor for just "\"
1288 while ( wxEndsWithPathSeparator(strPath
) )
1290 size_t len
= strPath
.length();
1291 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1294 strPath
.Truncate(len
- 1);
1296 #endif // __WINDOWS__
1298 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1299 // stat() can't cope with network paths
1300 DWORD ret
= ::GetFileAttributes(strPath
);
1302 return (ret
!= (DWORD
)-1) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1306 #ifndef __VISAGECPP__
1307 return wxStat(pszPathName
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1309 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1310 return wxStat(pszPathName
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
1313 #endif // __WIN32__/!__WIN32__
1316 // Get a temporary filename, opening and closing the file.
1317 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1319 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1320 if ( filename
.empty() )
1324 wxStrcpy(buf
, filename
);
1326 buf
= copystring(filename
);
1331 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1333 buf
= wxFileName::CreateTempFileName(prefix
);
1335 return !buf
.empty();
1338 // Get first file name matching given wild card.
1340 static wxDir
*gs_dir
= NULL
;
1341 static wxString gs_dirPath
;
1343 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1345 wxSplitPath(spec
, &gs_dirPath
, NULL
, NULL
);
1346 if ( gs_dirPath
.IsEmpty() )
1347 gs_dirPath
= wxT(".");
1348 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1349 gs_dirPath
<< wxFILE_SEP_PATH
;
1353 gs_dir
= new wxDir(gs_dirPath
);
1355 if ( !gs_dir
->IsOpened() )
1357 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1358 return wxEmptyString
;
1364 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1365 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1366 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1370 gs_dir
->GetFirst(&result
, wxFileNameFromPath(wxString(spec
)), dirFlags
);
1371 if ( result
.IsEmpty() )
1377 return gs_dirPath
+ result
;
1380 wxString
wxFindNextFile()
1382 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1385 gs_dir
->GetNext(&result
);
1387 if ( result
.IsEmpty() )
1393 return gs_dirPath
+ result
;
1397 // Get current working directory.
1398 // If buf is NULL, allocates space using new, else
1400 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1404 buf
= new wxChar
[sz
+ 1];
1409 // for the compilers which have Unicode version of _getcwd(), call it
1410 // directly, for the others call the ANSI version and do the translation
1413 #else // wxUSE_UNICODE
1414 bool needsANSI
= TRUE
;
1416 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1417 wxCharBuffer
c_buffer(sz
);
1418 char *cbuf
= (char*)(const char*)c_buffer
;
1422 #if wxUSE_UNICODE_MSLU
1423 if ( wxGetOsVersion() != wxWIN95
)
1425 char *cbuf
= NULL
; // never really used because needsANSI will always be FALSE
1428 ok
= _wgetcwd(buf
, sz
) != NULL
;
1434 #endif // wxUSE_UNICODE
1437 ok
= _getcwd(cbuf
, sz
) != NULL
;
1438 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1443 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1445 pb
.ioRefNum
= LMGetCurApRefNum();
1447 error
= PBGetFCBInfoSync(&pb
);
1448 if ( error
== noErr
)
1450 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1451 cwdSpec
.parID
= pb
.ioFCBParID
;
1452 cwdSpec
.name
[0] = 0 ;
1453 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1455 strcpy( cbuf
, res
) ;
1456 cbuf
[res
.length()]=0 ;
1464 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1466 rc
= ::DosQueryCurrentDir( 0 // current drive
1471 #else // !Win32/VC++ !Mac !OS2
1472 ok
= getcwd(cbuf
, sz
) != NULL
;
1476 // finally convert the result to Unicode if needed
1477 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1478 #endif // wxUSE_UNICODE
1483 wxLogSysError(_("Failed to get the working directory"));
1485 // VZ: the old code used to return "." on error which didn't make any
1486 // sense at all to me - empty string is a better error indicator
1487 // (NULL might be even better but I'm afraid this could lead to
1488 // problems with the old code assuming the return is never NULL)
1491 else // ok, but we might need to massage the path into the right format
1494 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1495 // with / deliminers. We don't like that.
1496 for (wxChar
*ch
= buf
; *ch
; ch
++)
1498 if (*ch
== wxT('/'))
1503 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1504 // he needs Unix as opposed to Win32 pathnames
1505 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1506 // another example of DOS/Unix mix (Cygwin)
1507 wxString pathUnix
= buf
;
1508 cygwin_conv_to_full_win32_path(pathUnix
, buf
);
1509 #endif // __CYGWIN__
1523 // we can't create wxStringBuffer object inline: Sun CC generates buggy
1524 // code in this case!
1526 wxStringBuffer
buf(str
, _MAXPATHLEN
);
1527 wxGetWorkingDirectory(buf
, _MAXPATHLEN
);
1533 bool wxSetWorkingDirectory(const wxString
& d
)
1535 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1536 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1537 #elif defined(__WXPM__)
1538 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1539 #elif defined(__WINDOWS__)
1542 return (bool)(SetCurrentDirectory(d
) != 0);
1544 // Must change drive, too.
1545 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1548 wxChar firstChar
= d
[0];
1552 firstChar
= firstChar
- 32;
1554 // To a drive number
1555 unsigned int driveNo
= firstChar
- 64;
1558 unsigned int noDrives
;
1559 _dos_setdrive(driveNo
, &noDrives
);
1562 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1570 // Get the OS directory if appropriate (such as the Windows directory).
1571 // On non-Windows platform, probably just return the empty string.
1572 wxString
wxGetOSDirectory()
1574 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1576 GetWindowsDirectory(buf
, 256);
1577 return wxString(buf
);
1579 return wxEmptyString
;
1583 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1585 size_t len
= wxStrlen(pszFileName
);
1587 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1590 // find a file in a list of directories, returns false if not found
1591 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1593 // we assume that it's not empty
1594 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1595 _T("empty file name in wxFindFileInPath"));
1597 // skip path separator in the beginning of the file name if present
1598 if ( wxIsPathSeparator(*pszFile
) )
1601 // copy the path (strtok will modify it)
1602 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1603 wxStrcpy(szPath
, pszPath
);
1606 wxChar
*pc
, *save_ptr
;
1607 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1609 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1611 // search for the file in this directory
1613 if ( !wxEndsWithPathSeparator(pc
) )
1614 strFile
+= wxFILE_SEP_PATH
;
1617 if ( FileExists(strFile
) ) {
1623 // suppress warning about unused variable save_ptr when wxStrtok() is a
1624 // macro which throws away its third argument
1629 return pc
!= NULL
; // if true => we breaked from the loop
1632 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1637 // it can be empty, but it shouldn't be NULL
1638 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1640 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1643 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1646 wxStat( filename
, &buf
);
1648 return buf
.st_mtime
;
1652 //------------------------------------------------------------------------
1653 // wild character routines
1654 //------------------------------------------------------------------------
1656 bool wxIsWild( const wxString
& pattern
)
1658 wxString tmp
= pattern
;
1659 wxChar
*pat
= WXSTRINGCAST(tmp
);
1662 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1672 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1676 // this probably won't work well for multibyte chars in Unicode mode?
1678 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1680 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1682 #else // !HAVE_FNMATCH
1684 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1687 * WARNING: this code is broken!
1690 wxString tmp1
= pat
;
1691 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1692 wxString tmp2
= text
;
1693 wxChar
*str
= WXSTRINGCAST(tmp2
);
1696 bool done
= FALSE
, ret_code
, ok
;
1697 // Below is for vi fans
1698 const wxChar OB
= wxT('{'), CB
= wxT('}');
1700 // dot_special means '.' only matches '.'
1701 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1704 while ((*pattern
!= wxT('\0')) && (!done
)
1705 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1709 if (*pattern
!= wxT('\0'))
1715 while ((*str
!=wxT('\0'))
1716 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1719 while (*str
!= wxT('\0'))
1721 while (*pattern
!= wxT('\0'))
1728 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1732 if (*pattern
== wxT('\\')) {
1734 if (*pattern
== wxT('\0')) {
1739 if (*(pattern
+ 1) == wxT('-')) {
1742 if (*pattern
== wxT(']')) {
1746 if (*pattern
== wxT('\\')) {
1748 if (*pattern
== wxT('\0')) {
1753 if ((*str
< c
) || (*str
> *pattern
)) {
1757 } else if (*pattern
!= *str
) {
1762 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1763 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1767 if (*pattern
!= wxT('\0')) {
1777 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1780 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1781 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1782 if (*pattern
== wxT('\\'))
1784 ok
= (*pattern
++ == *cp
++);
1786 if (*pattern
== wxT('\0')) {
1792 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1793 if (*++pattern
== wxT('\\')) {
1794 if (*++pattern
== CB
)
1799 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1800 if (*++pattern
== wxT('\\')) {
1801 if (*++pattern
== CB
|| *pattern
== wxT(','))
1806 if (*pattern
!= wxT('\0'))
1811 if (*str
== *pattern
) {
1818 while (*pattern
== wxT('*'))
1820 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1823 #endif // HAVE_FNMATCH/!HAVE_FNMATCH
1826 #pragma warning(default:4706) // assignment within conditional expression