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 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 #define _MAXPATHLEN 500
132 extern wxChar
*wxBuffer
;
135 # include "MoreFiles.h"
136 # include "MoreFilesExtras.h"
137 # include "FullPath.h"
138 # include "FSpCompat.h"
141 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
143 // ----------------------------------------------------------------------------
145 // ----------------------------------------------------------------------------
147 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
149 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
151 // VisualAge C++ V4.0 cannot have any external linkage const decs
152 // in headers included by more than one primary source
154 const off_t wxInvalidOffset
= (off_t
)-1;
157 // ----------------------------------------------------------------------------
159 // ----------------------------------------------------------------------------
161 // we need to translate Mac filenames before passing them to OS functions
162 #define OS_FILENAME(s) (s.fn_str())
164 // ============================================================================
166 // ============================================================================
168 void wxPathList::Add (const wxString
& path
)
170 wxStringList::Add (WXSTRINGCAST path
);
173 // Add paths e.g. from the PATH environment variable
174 void wxPathList::AddEnvList (const wxString
& envVariable
)
176 static const wxChar PATH_TOKS
[] =
178 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
183 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
186 wxChar
*s
= copystring (val
);
187 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
191 Add (copystring (token
));
194 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
195 Add (wxString(token
));
199 // suppress warning about unused variable save_ptr when wxStrtok() is a
200 // macro which throws away its third argument
207 // Given a full filename (with path), ensure that that file can
208 // be accessed again USING FILENAME ONLY by adding the path
209 // to the list if not already there.
210 void wxPathList::EnsureFileAccessible (const wxString
& path
)
212 wxString
path_only(wxPathOnly(path
));
213 if ( !path_only
.IsEmpty() )
215 if ( !Member(path_only
) )
220 bool wxPathList::Member (const wxString
& path
)
222 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
224 wxString
path2((wxChar
*) node
->Data ());
226 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
228 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
230 // Case sensitive File System
231 path
.CompareTo (path2
) == 0
239 wxString
wxPathList::FindValidPath (const wxString
& file
)
241 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
242 return wxString(wxFileFunctionsBuffer
);
244 wxChar buf
[_MAXPATHLEN
];
245 wxStrcpy(buf
, wxFileFunctionsBuffer
);
247 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
248 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
250 for (wxNode
* node
= First (); node
; node
= node
->Next ())
252 wxChar
*path
= (wxChar
*) node
->Data ();
253 wxStrcpy (wxFileFunctionsBuffer
, path
);
254 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
255 if (ch
!= wxT('\\') && ch
!= wxT('/'))
256 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
257 wxStrcat (wxFileFunctionsBuffer
, filename
);
259 Unix2DosFilename (wxFileFunctionsBuffer
);
261 if (wxFileExists (wxFileFunctionsBuffer
))
263 return wxString(wxFileFunctionsBuffer
); // Found!
267 return wxString(wxT("")); // Not found
270 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
272 wxString f
= FindValidPath(file
);
273 if ( wxIsAbsolutePath(f
) )
277 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
279 if ( !wxEndsWithPathSeparator(buf
) )
281 buf
+= wxFILE_SEP_PATH
;
289 wxFileExists (const wxString
& filename
)
291 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
292 // GetFileAttributes can copy with network paths
293 DWORD ret
= GetFileAttributes(filename
);
294 DWORD isDir
= (ret
& FILE_ATTRIBUTE_DIRECTORY
);
295 return ((ret
!= 0xffffffff) && (isDir
== 0));
298 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
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('.')))
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 Unix2DosFilename(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
--);
397 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
398 && (q
- 1 <= path
|| q
[-1] != SEP
))
401 if (path
[0] == wxT('\0'))
407 /* Check that path[2] is NULL! */
408 else if (path
[1] == wxT(':') && !path
[2])
417 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
426 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
428 if (filename
== wxT(""))
429 return (wxChar
*) NULL
;
431 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
432 wxChar buf
[_MAXPATHLEN
];
434 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
435 wxChar ch
= buf
[wxStrlen(buf
) - 1];
437 if (ch
!= wxT('\\') && ch
!= wxT('/'))
438 wxStrcat(buf
, wxT("\\"));
441 wxStrcat(buf
, wxT("/"));
443 wxStrcat(buf
, wxFileFunctionsBuffer
);
444 return copystring( wxRealPath(buf
) );
446 return copystring( wxFileFunctionsBuffer
);
452 ~user/ => user's home dir
453 If the environment variable a = "foo" and b = "bar" then:
470 /* input name in name, pathname output to buf. */
472 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
474 register wxChar
*d
, *s
, *nm
;
475 wxChar lnm
[_MAXPATHLEN
];
478 // Some compilers don't like this line.
479 // const wxChar trimchars[] = wxT("\n \t");
482 trimchars
[0] = wxT('\n');
483 trimchars
[1] = wxT(' ');
484 trimchars
[2] = wxT('\t');
488 const wxChar SEP
= wxT('\\');
490 const wxChar SEP
= wxT('/');
493 if (name
== NULL
|| *name
== wxT('\0'))
495 nm
= copystring(name
); // Make a scratch copy
498 /* Skip leading whitespace and cr */
499 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
501 /* And strip off trailing whitespace and cr */
502 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
503 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
511 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
514 /* Expand inline environment variables */
532 while ((*d
++ = *s
) != 0) {
534 if (*s
== wxT('\\')) {
535 if ((*(d
- 1) = *++s
)) {
544 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
546 if (*s
++ == wxT('$'))
549 register wxChar
*start
= d
;
550 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
551 register wxChar
*value
;
552 while ((*d
++ = *s
) != 0)
553 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
558 value
= wxGetenv(braces
? start
+ 1 : start
);
560 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
568 /* Expand ~ and ~user */
571 if (nm
[0] == wxT('~') && !q
)
574 if (nm
[1] == SEP
|| nm
[1] == 0)
576 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
577 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
582 { /* ~user/filename */
583 register wxChar
*nnm
;
584 register wxChar
*home
;
585 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
586 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
587 was_sep
= (*s
== SEP
);
588 nnm
= *s
? s
+ 1 : s
;
590 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
591 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
592 if (was_sep
) /* replace only if it was there: */
603 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
605 while (wxT('\0') != (*d
++ = *s
++))
608 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
612 while ((*d
++ = *s
++) != 0);
613 delete[] nm_tmp
; // clean up alloc
614 /* Now clean up the buffer */
615 return wxRealPath(buf
);
618 /* Contract Paths to be build upon an environment variable
621 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
623 The call wxExpandPath can convert these back!
626 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
628 static wxChar dest
[_MAXPATHLEN
];
630 if (filename
== wxT(""))
631 return (wxChar
*) NULL
;
633 wxStrcpy (dest
, WXSTRINGCAST filename
);
635 Unix2DosFilename(dest
);
638 // Handle environment
639 const wxChar
*val
= (const wxChar
*) NULL
;
640 wxChar
*tcp
= (wxChar
*) NULL
;
641 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
642 (tcp
= wxStrstr (dest
, val
)) != NULL
)
644 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
647 wxStrcpy (tcp
, WXSTRINGCAST envname
);
648 wxStrcat (tcp
, wxT("}"));
649 wxStrcat (tcp
, wxFileFunctionsBuffer
);
652 // Handle User's home (ignore root homes!)
654 if ((val
= wxGetUserHome (user
)) != NULL
&&
655 (len
= wxStrlen(val
)) > 2 &&
656 wxStrncmp(dest
, val
, len
) == 0)
658 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
660 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
662 // strcat(wxFileFunctionsBuffer, "\\");
664 // strcat(wxFileFunctionsBuffer, "/");
666 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
667 wxStrcpy (dest
, wxFileFunctionsBuffer
);
673 // Return just the filename, not the path
675 wxChar
*wxFileNameFromPath (wxChar
*path
)
679 register wxChar
*tcp
;
681 tcp
= path
+ wxStrlen (path
);
682 while (--tcp
>= path
)
684 #if defined(__WXMAC__) && !defined(__DARWIN__)
685 // Classic or Carbon CodeWarrior like
686 // Carbon with Apple DevTools is Unix like
687 if (*tcp
== wxT(':'))
690 // Unix like or Windows
691 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
695 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
699 #if defined(__WXMSW__) || defined(__WXPM__)
701 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
708 wxString
wxFileNameFromPath (const wxString
& path1
)
710 if (path1
!= wxT(""))
712 wxChar
*path
= WXSTRINGCAST path1
;
713 register wxChar
*tcp
;
715 tcp
= path
+ wxStrlen (path
);
716 while (--tcp
>= path
)
718 #if defined(__WXMAC__) && !defined(__DARWIN__)
719 // Classic or Carbon CodeWarrior like
720 // Carbon with Apple DevTools is Unix like
721 if (*tcp
== wxT(':') )
722 return wxString(tcp
+ 1);
724 // Unix like or Windows
725 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
726 return wxString(tcp
+ 1);
729 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
730 return wxString(tcp
+ 1);
733 #if defined(__WXMSW__) || defined(__WXPM__)
735 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
736 return wxString(path
+ 2);
739 // Yes, this should return the path, not an empty string, otherwise
740 // we get "thing.txt" -> "".
744 // Return just the directory, or NULL if no directory
746 wxPathOnly (wxChar
*path
)
750 static wxChar buf
[_MAXPATHLEN
];
753 wxStrcpy (buf
, path
);
755 int l
= wxStrlen(path
);
758 // Search backward for a backward or forward slash
761 #if defined(__WXMAC__) && !defined(__DARWIN__)
762 // Classic or Carbon CodeWarrior like
763 // Carbon with Apple DevTools is Unix like
764 if (path
[i
] == wxT(':') )
770 // Unix like or Windows
771 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
778 if (path
[i
] == wxT(']'))
787 #if defined(__WXMSW__) || defined(__WXPM__)
788 // Try Drive specifier
789 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
791 // A:junk --> A:. (since A:.\junk Not A:\junk)
798 return (wxChar
*) NULL
;
801 // Return just the directory, or NULL if no directory
802 wxString
wxPathOnly (const wxString
& path
)
806 wxChar buf
[_MAXPATHLEN
];
809 wxStrcpy (buf
, WXSTRINGCAST path
);
811 int l
= path
.Length();
814 // Search backward for a backward or forward slash
817 #if defined(__WXMAC__) && !defined(__DARWIN__)
818 // Classic or Carbon CodeWarrior like
819 // Carbon with Apple DevTools is Unix like
820 if (path
[i
] == wxT(':') )
823 return wxString(buf
);
826 // Unix like or Windows
827 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
830 return wxString(buf
);
834 if (path
[i
] == wxT(']'))
837 return wxString(buf
);
843 #if defined(__WXMSW__) || defined(__WXPM__)
844 // Try Drive specifier
845 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
847 // A:junk --> A:. (since A:.\junk Not A:\junk)
850 return wxString(buf
);
854 return wxString(wxT(""));
857 // Utility for converting delimiters in DOS filenames to UNIX style
858 // and back again - or we get nasty problems with delimiters.
859 // Also, convert to lower case, since case is significant in UNIX.
861 #if defined(__WXMAC__)
862 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
866 char thePath
[FILENAME_MAX
];
868 // convert the FSSpec to an FSRef
869 (void) FSpMakeFSRef( spec
, &theRef
);
870 // get the POSIX path associated with the FSRef
871 (void) FSRefMakePath( &theRef
, (UInt8
*)thePath
, sizeof(thePath
) );
873 // create path string for return value
874 wxString
result( thePath
) ;
879 // get length of path and allocate handle
880 FSpGetFullPath( spec
, &length
, &myPath
) ;
881 ::SetHandleSize( myPath
, length
+ 1 ) ;
883 (*myPath
)[length
] = 0 ;
884 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
885 (*myPath
)[length
-1] = 0 ;
887 // create path string for return value
888 wxString
result( (char*) *myPath
) ;
890 // free allocated handle
891 ::HUnlock( myPath
) ;
892 ::DisposeHandle( myPath
) ;
898 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
903 // get the FSRef associated with the POSIX path
904 (void) FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
905 // convert the FSRef to an FSSpec
906 (void) FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
908 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
913 // Mac file names are POSIX (Unix style) under Darwin
914 // therefore the conversion functions below are not needed
916 static char sMacFileNameConversion
[ 1000 ] ;
918 wxString
wxMac2UnixFilename (const char *str
)
920 char *s
= sMacFileNameConversion
;
924 memmove( s
+1 , s
,strlen( s
) + 1) ;
935 *s
= wxTolower(*s
); // Case INDEPENDENT
939 return wxString(sMacFileNameConversion
) ;
942 wxString
wxUnix2MacFilename (const char *str
)
944 char *s
= sMacFileNameConversion
;
950 // relative path , since it goes on with slash which is translated to a :
951 memmove( s
, s
+1 ,strlen( s
) ) ;
953 else if ( *s
== '/' )
955 // absolute path -> on mac just start with the drive name
956 memmove( s
, s
+1 ,strlen( s
) ) ;
960 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
964 if (*s
== '/' || *s
== '\\')
966 // convert any back-directory situations
967 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
970 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
978 return wxString (sMacFileNameConversion
) ;
981 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
983 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
986 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
988 wxString var
= wxUnix2MacFilename( path
) ;
989 wxMacFilename2FSSpec( var
, spec
) ;
991 #endif // ! __DARWIN__
996 wxDos2UnixFilename (char *s
)
1005 *s
= wxTolower (*s
); // Case INDEPENDENT
1012 #if defined(__WXMSW__) || defined(__WXPM__)
1013 wxUnix2DosFilename (wxChar
*s
)
1015 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1018 // Yes, I really mean this to happen under DOS only! JACS
1019 #if defined(__WXMSW__) || defined(__WXPM__)
1030 // Concatenate two files to form third
1032 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1035 if ( !wxGetTempFileName("cat", outfile
) )
1038 FILE *fp1
= (FILE *) NULL
;
1039 FILE *fp2
= (FILE *) NULL
;
1040 FILE *fp3
= (FILE *) NULL
;
1041 // Open the inputs and outputs
1042 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
1043 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
1044 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
1056 while ((ch
= getc (fp1
)) != EOF
)
1057 (void) putc (ch
, fp3
);
1060 while ((ch
= getc (fp2
)) != EOF
)
1061 (void) putc (ch
, fp3
);
1065 bool result
= wxRenameFile(outfile
, file3
);
1071 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1073 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1074 // CopyFile() copies file attributes and modification time too, so use it
1075 // instead of our code if available
1077 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1078 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1079 #elif defined(__WXPM__)
1080 if (::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) == 0)
1087 // get permissions of file1
1088 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1090 // the file probably doesn't exist or we haven't the rights to read
1092 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1097 // open file1 for reading
1098 wxFile
fileIn(file1
, wxFile::read
);
1099 if ( !fileIn
.IsOpened() )
1102 // remove file2, if it exists. This is needed for creating
1103 // file2 with the correct permissions in the next step
1104 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1106 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1112 // reset the umask as we want to create the file with exactly the same
1113 // permissions as the original one
1114 mode_t oldUmask
= umask( 0 );
1117 // create file2 with the same permissions than file1 and open it for
1120 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1124 /// restore the old umask
1128 // copy contents of file1 to file2
1133 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1134 if ( fileIn
.Error() )
1141 if ( fileOut
.Write(buf
, count
) < count
)
1145 // we can expect fileIn to be closed successfully, but we should ensure
1146 // that fileOut was closed as some write errors (disk full) might not be
1147 // detected before doing this
1148 if ( !fileIn
.Close() || !fileOut
.Close() )
1151 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1152 // no chmod in VA. Should be some permission API for HPFS386 partitions
1154 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1156 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1160 #endif // OS/2 || Mac
1163 #endif // __WXMSW__ && __WIN32__
1167 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1169 // Normal system call
1170 if ( wxRename (file1
, file2
) == 0 )
1174 if (wxCopyFile(file1
, file2
)) {
1175 wxRemoveFile(file1
);
1182 bool wxRemoveFile(const wxString
& file
)
1184 #if defined(__VISUALC__) \
1185 || defined(__BORLANDC__) \
1186 || defined(__WATCOMC__) \
1187 || defined(__GNUWIN32__)
1188 int res
= wxRemove(file
);
1190 int res
= unlink(OS_FILENAME(file
));
1196 bool wxMkdir(const wxString
& dir
, int perm
)
1198 #if defined(__WXMAC__) && !defined(__UNIX__)
1199 return (mkdir( dir
, 0 ) == 0);
1201 const wxChar
*dirname
= dir
.c_str();
1203 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1204 // for the GNU compiler
1205 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1206 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1207 #elif defined(__WXPM__)
1208 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1209 #elif defined(__DOS__)
1210 #if defined(__WATCOMC__)
1212 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1213 #elif defined(__DJGPP__)
1214 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1216 #error "Unsupported DOS compiler!"
1218 #else // !MSW, !DOS and !OS/2 VAC++
1220 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1223 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1232 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1235 return FALSE
; //to be changed since rmdir exists in VMS7.x
1236 #elif defined(__WXPM__)
1237 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1241 return FALSE
; // What to do?
1243 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1249 // does the path exists? (may have or not '/' or '\\' at the end)
1250 bool wxPathExists(const wxChar
*pszPathName
)
1252 wxString
strPath(pszPathName
);
1254 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1255 // so remove all trailing backslashes from the path - but don't do this for
1256 // the pathes "d:\" (which are different from "d:") nor for just "\"
1257 while ( wxEndsWithPathSeparator(strPath
) )
1259 size_t len
= strPath
.length();
1260 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1263 strPath
.Truncate(len
- 1);
1265 #endif // __WINDOWS__
1267 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1268 // Stat can't cope with network paths
1269 DWORD ret
= GetFileAttributes(strPath
.c_str());
1270 DWORD isDir
= (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1271 return ((ret
!= 0xffffffff) && (isDir
!= 0));
1275 #ifndef __VISAGECPP__
1276 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1277 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1279 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1280 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1281 (st
.st_mode
== S_IFDIR
);
1287 // Get a temporary filename, opening and closing the file.
1288 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1290 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1291 if ( filename
.empty() )
1295 wxStrcpy(buf
, filename
);
1297 buf
= copystring(filename
);
1302 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1304 buf
= wxFileName::CreateTempFileName(prefix
);
1306 return !buf
.empty();
1309 // Get first file name matching given wild card.
1311 static wxDir
*gs_dir
= NULL
;
1312 static wxString gs_dirPath
;
1314 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1316 gs_dirPath
= wxPathOnly(spec
);
1317 if ( gs_dirPath
.IsEmpty() )
1318 gs_dirPath
= wxT(".");
1319 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1320 gs_dirPath
<< wxFILE_SEP_PATH
;
1324 gs_dir
= new wxDir(gs_dirPath
);
1326 if ( !gs_dir
->IsOpened() )
1328 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1329 return wxEmptyString
;
1335 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1336 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1337 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1341 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1342 if ( result
.IsEmpty() )
1348 return gs_dirPath
+ result
;
1351 wxString
wxFindNextFile()
1353 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1356 gs_dir
->GetNext(&result
);
1358 if ( result
.IsEmpty() )
1364 return gs_dirPath
+ result
;
1368 // Get current working directory.
1369 // If buf is NULL, allocates space using new, else
1371 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1374 buf
= new wxChar
[sz
+1];
1376 char *cbuf
= new char[sz
+1];
1378 if (_getcwd(cbuf
, sz
) == NULL
) {
1379 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1382 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1386 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1387 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1388 strcpy( buf
, res
) ;
1391 if (getcwd(cbuf
, sz
) == NULL
) {
1396 if (_getcwd(buf
, sz
) == NULL
) {
1397 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1402 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1404 pb
.ioRefNum
= LMGetCurApRefNum();
1406 error
= PBGetFCBInfoSync(&pb
);
1407 if ( error
== noErr
)
1409 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1410 cwdSpec
.parID
= pb
.ioFCBParID
;
1411 cwdSpec
.name
[0] = 0 ;
1412 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1414 strcpy( buf
, res
) ;
1415 buf
[res
.length()]=0 ;
1420 this version will not always give back the application directory on mac
1423 SFSaveDisk = 0x214, CurDirStore = 0x398
1427 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1428 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1429 strcpy( buf , res ) ;
1432 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1434 rc
= ::DosQueryCurrentDir( 0 // current drive
1440 if (getcwd(buf
, sz
) == NULL
) {
1448 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1454 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths with
1455 // / deliminers. We don't like that.
1456 for (wxChar
*ch
= buf
; *ch
; ch
++)
1457 if (*ch
== wxT('/')) *ch
= wxT('\\');
1465 static const size_t maxPathLen
= 1024;
1468 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1469 str
.UngetWriteBuf();
1474 bool wxSetWorkingDirectory(const wxString
& d
)
1476 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1477 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1478 #elif defined(__WXPM__)
1479 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1480 #elif defined(__WINDOWS__)
1483 return (bool)(SetCurrentDirectory(d
) != 0);
1485 // Must change drive, too.
1486 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1489 wxChar firstChar
= d
[0];
1493 firstChar
= firstChar
- 32;
1495 // To a drive number
1496 unsigned int driveNo
= firstChar
- 64;
1499 unsigned int noDrives
;
1500 _dos_setdrive(driveNo
, &noDrives
);
1503 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1511 // Get the OS directory if appropriate (such as the Windows directory).
1512 // On non-Windows platform, probably just return the empty string.
1513 wxString
wxGetOSDirectory()
1515 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1517 GetWindowsDirectory(buf
, 256);
1518 return wxString(buf
);
1520 return wxEmptyString
;
1524 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1526 size_t len
= wxStrlen(pszFileName
);
1528 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1531 // find a file in a list of directories, returns false if not found
1532 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1534 // we assume that it's not empty
1535 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1536 _T("empty file name in wxFindFileInPath"));
1538 // skip path separator in the beginning of the file name if present
1539 if ( wxIsPathSeparator(*pszFile
) )
1542 // copy the path (strtok will modify it)
1543 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1544 wxStrcpy(szPath
, pszPath
);
1547 wxChar
*pc
, *save_ptr
;
1548 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1550 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1552 // search for the file in this directory
1554 if ( !wxEndsWithPathSeparator(pc
) )
1555 strFile
+= wxFILE_SEP_PATH
;
1558 if ( FileExists(strFile
) ) {
1564 // suppress warning about unused variable save_ptr when wxStrtok() is a
1565 // macro which throws away its third argument
1570 return pc
!= NULL
; // if true => we breaked from the loop
1573 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1578 // it can be empty, but it shouldn't be NULL
1579 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1581 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1584 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1588 wxStat(filename
.fn_str(), &buf
);
1589 return buf
.st_mtime
;
1593 //------------------------------------------------------------------------
1594 // wild character routines
1595 //------------------------------------------------------------------------
1597 bool wxIsWild( const wxString
& pattern
)
1599 wxString tmp
= pattern
;
1600 wxChar
*pat
= WXSTRINGCAST(tmp
);
1603 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1613 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1615 #if defined(HAVE_FNMATCH_H)
1617 // this probably won't work well for multibyte chars in Unicode mode?
1619 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1621 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1625 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1628 * WARNING: this code is broken!
1631 wxString tmp1
= pat
;
1632 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1633 wxString tmp2
= text
;
1634 wxChar
*str
= WXSTRINGCAST(tmp2
);
1637 bool done
= FALSE
, ret_code
, ok
;
1638 // Below is for vi fans
1639 const wxChar OB
= wxT('{'), CB
= wxT('}');
1641 // dot_special means '.' only matches '.'
1642 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1645 while ((*pattern
!= wxT('\0')) && (!done
)
1646 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1650 if (*pattern
!= wxT('\0'))
1656 while ((*str
!=wxT('\0'))
1657 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1660 while (*str
!= wxT('\0'))
1662 while (*pattern
!= wxT('\0'))
1669 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1673 if (*pattern
== wxT('\\')) {
1675 if (*pattern
== wxT('\0')) {
1680 if (*(pattern
+ 1) == wxT('-')) {
1683 if (*pattern
== wxT(']')) {
1687 if (*pattern
== wxT('\\')) {
1689 if (*pattern
== wxT('\0')) {
1694 if ((*str
< c
) || (*str
> *pattern
)) {
1698 } else if (*pattern
!= *str
) {
1703 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1704 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1708 if (*pattern
!= wxT('\0')) {
1718 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1721 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1722 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1723 if (*pattern
== wxT('\\'))
1725 ok
= (*pattern
++ == *cp
++);
1727 if (*pattern
== wxT('\0')) {
1733 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1734 if (*++pattern
== wxT('\\')) {
1735 if (*++pattern
== CB
)
1740 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1741 if (*++pattern
== wxT('\\')) {
1742 if (*++pattern
== CB
|| *pattern
== wxT(','))
1747 if (*pattern
!= wxT('\0'))
1752 if (*str
== *pattern
) {
1759 while (*pattern
== wxT('*'))
1761 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1767 #pragma warning(default:4706) // assignment within conditional expression
1770 //------------------------------------------------------------------------
1771 // Missing functions in Unicode for Win9x
1772 //------------------------------------------------------------------------
1774 // NB: MSLU only covers Win32 API, it doesn't provide Unicode implementation of
1775 // libc functions. Unfortunately, some of MSVCRT wchar_t functions
1776 // (e.g. _wopen) don't work on Windows 9x, so we have to workaround it
1777 // by calling the char version. We still want to use wchar_t version on
1778 // NT/2000/XP, though, because they allow for Unicode file names.
1779 #if wxUSE_UNICODE_MSLU
1781 #if defined( __VISUALC__ ) \
1782 || ( defined(__MINGW32__) && wxCHECK_W32API_VERSION( 0, 5 ) ) \
1783 || ( defined(__MWERKS__) && defined(__WXMSW__) )
1784 WXDLLEXPORT
int wxOpen(const wxChar
*name
, int flags
, int mode
)
1786 if ( wxGetOsVersion() == wxWINDOWS_NT
)
1787 return _wopen(name
, flags
, mode
);
1789 return _open(wxConvFile
.cWX2MB(name
), flags
, mode
);
1793 #endif // wxUSE_UNICODE_MSLU