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 */
570 if (nm
[0] == wxT('~') && !q
)
573 if (nm
[1] == SEP
|| nm
[1] == 0)
575 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
576 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
581 { /* ~user/filename */
582 register wxChar
*nnm
;
583 register wxChar
*home
;
584 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
585 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
586 was_sep
= (*s
== SEP
);
587 nnm
= *s
? s
+ 1 : s
;
589 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
590 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
591 if (was_sep
) /* replace only if it was there: */
602 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
604 while (wxT('\0') != (*d
++ = *s
++))
607 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
611 while ((*d
++ = *s
++) != 0);
612 delete[] nm_tmp
; // clean up alloc
613 /* Now clean up the buffer */
614 return wxRealPath(buf
);
617 /* Contract Paths to be build upon an environment variable
620 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
622 The call wxExpandPath can convert these back!
625 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
627 static wxChar dest
[_MAXPATHLEN
];
629 if (filename
== wxT(""))
630 return (wxChar
*) NULL
;
632 wxStrcpy (dest
, WXSTRINGCAST filename
);
634 Unix2DosFilename(dest
);
637 // Handle environment
638 const wxChar
*val
= (const wxChar
*) NULL
;
639 wxChar
*tcp
= (wxChar
*) NULL
;
640 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
641 (tcp
= wxStrstr (dest
, val
)) != NULL
)
643 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
646 wxStrcpy (tcp
, WXSTRINGCAST envname
);
647 wxStrcat (tcp
, wxT("}"));
648 wxStrcat (tcp
, wxFileFunctionsBuffer
);
651 // Handle User's home (ignore root homes!)
653 if ((val
= wxGetUserHome (user
)) != NULL
&&
654 (len
= wxStrlen(val
)) > 2 &&
655 wxStrncmp(dest
, val
, len
) == 0)
657 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
659 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
661 // strcat(wxFileFunctionsBuffer, "\\");
663 // strcat(wxFileFunctionsBuffer, "/");
665 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
666 wxStrcpy (dest
, wxFileFunctionsBuffer
);
672 // Return just the filename, not the path
674 wxChar
*wxFileNameFromPath (wxChar
*path
)
678 register wxChar
*tcp
;
680 tcp
= path
+ wxStrlen (path
);
681 while (--tcp
>= path
)
683 #if defined(__WXMAC__) && !defined(__DARWIN__)
684 // Classic or Carbon CodeWarrior like
685 // Carbon with Apple DevTools is Unix like
686 if (*tcp
== wxT(':'))
689 // Unix like or Windows
690 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
694 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
698 #if defined(__WXMSW__) || defined(__WXPM__)
700 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
707 wxString
wxFileNameFromPath (const wxString
& path1
)
709 if (path1
!= wxT(""))
711 wxChar
*path
= WXSTRINGCAST path1
;
712 register wxChar
*tcp
;
714 tcp
= path
+ wxStrlen (path
);
715 while (--tcp
>= path
)
717 #if defined(__WXMAC__) && !defined(__DARWIN__)
718 // Classic or Carbon CodeWarrior like
719 // Carbon with Apple DevTools is Unix like
720 if (*tcp
== wxT(':') )
721 return wxString(tcp
+ 1);
723 // Unix like or Windows
724 if (*tcp
== wxT('/') || *tcp
== wxT('\\'))
725 return wxString(tcp
+ 1);
728 if (*tcp
== wxT(':') || *tcp
== wxT(']'))
729 return wxString(tcp
+ 1);
732 #if defined(__WXMSW__) || defined(__WXPM__)
734 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
735 return wxString(path
+ 2);
738 // Yes, this should return the path, not an empty string, otherwise
739 // we get "thing.txt" -> "".
743 // Return just the directory, or NULL if no directory
745 wxPathOnly (wxChar
*path
)
749 static wxChar buf
[_MAXPATHLEN
];
752 wxStrcpy (buf
, path
);
754 int l
= wxStrlen(path
);
757 // Search backward for a backward or forward slash
760 #if defined(__WXMAC__) && !defined(__DARWIN__)
761 // Classic or Carbon CodeWarrior like
762 // Carbon with Apple DevTools is Unix like
763 if (path
[i
] == wxT(':') )
769 // Unix like or Windows
770 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
777 if (path
[i
] == wxT(']'))
786 #if defined(__WXMSW__) || defined(__WXPM__)
787 // Try Drive specifier
788 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
790 // A:junk --> A:. (since A:.\junk Not A:\junk)
797 return (wxChar
*) NULL
;
800 // Return just the directory, or NULL if no directory
801 wxString
wxPathOnly (const wxString
& path
)
805 wxChar buf
[_MAXPATHLEN
];
808 wxStrcpy (buf
, WXSTRINGCAST path
);
810 int l
= path
.Length();
813 // Search backward for a backward or forward slash
816 #if defined(__WXMAC__) && !defined(__DARWIN__)
817 // Classic or Carbon CodeWarrior like
818 // Carbon with Apple DevTools is Unix like
819 if (path
[i
] == wxT(':') )
822 return wxString(buf
);
825 // Unix like or Windows
826 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\'))
829 return wxString(buf
);
833 if (path
[i
] == wxT(']'))
836 return wxString(buf
);
842 #if defined(__WXMSW__) || defined(__WXPM__)
843 // Try Drive specifier
844 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
846 // A:junk --> A:. (since A:.\junk Not A:\junk)
849 return wxString(buf
);
853 return wxString(wxT(""));
856 // Utility for converting delimiters in DOS filenames to UNIX style
857 // and back again - or we get nasty problems with delimiters.
858 // Also, convert to lower case, since case is significant in UNIX.
860 #if defined(__WXMAC__)
861 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
865 char thePath
[FILENAME_MAX
];
867 // convert the FSSpec to an FSRef
868 (void) FSpMakeFSRef( spec
, &theRef
);
869 // get the POSIX path associated with the FSRef
870 (void) FSRefMakePath( &theRef
, (UInt8
*)thePath
, sizeof(thePath
) );
872 // create path string for return value
873 wxString
result( thePath
) ;
878 // get length of path and allocate handle
879 FSpGetFullPath( spec
, &length
, &myPath
) ;
880 ::SetHandleSize( myPath
, length
+ 1 ) ;
882 (*myPath
)[length
] = 0 ;
883 if ((length
> 0) && ((*myPath
)[length
-1] == ':'))
884 (*myPath
)[length
-1] = 0 ;
886 // create path string for return value
887 wxString
result( (char*) *myPath
) ;
889 // free allocated handle
890 ::HUnlock( myPath
) ;
891 ::DisposeHandle( myPath
) ;
897 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
902 // get the FSRef associated with the POSIX path
903 (void) FSPathMakeRef((const UInt8
*) path
, &theRef
, NULL
);
904 // convert the FSRef to an FSSpec
905 (void) FSGetCatalogInfo(&theRef
, kFSCatInfoNone
, NULL
, NULL
, spec
, NULL
);
907 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
912 // Mac file names are POSIX (Unix style) under Darwin
913 // therefore the conversion functions below are not needed
915 static char sMacFileNameConversion
[ 1000 ] ;
917 wxString
wxMac2UnixFilename (const char *str
)
919 char *s
= sMacFileNameConversion
;
923 memmove( s
+1 , s
,strlen( s
) + 1) ;
934 *s
= wxTolower(*s
); // Case INDEPENDENT
938 return wxString(sMacFileNameConversion
) ;
941 wxString
wxUnix2MacFilename (const char *str
)
943 char *s
= sMacFileNameConversion
;
949 // relative path , since it goes on with slash which is translated to a :
950 memmove( s
, s
+1 ,strlen( s
) ) ;
952 else if ( *s
== '/' )
954 // absolute path -> on mac just start with the drive name
955 memmove( s
, s
+1 ,strlen( s
) ) ;
959 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
963 if (*s
== '/' || *s
== '\\')
965 // convert any back-directory situations
966 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
969 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
977 return wxString (sMacFileNameConversion
) ;
980 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
982 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
985 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
987 wxString var
= wxUnix2MacFilename( path
) ;
988 wxMacFilename2FSSpec( var
, spec
) ;
990 #endif // ! __DARWIN__
995 wxDos2UnixFilename (char *s
)
1004 *s
= wxTolower (*s
); // Case INDEPENDENT
1011 #if defined(__WXMSW__) || defined(__WXPM__)
1012 wxUnix2DosFilename (wxChar
*s
)
1014 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
1017 // Yes, I really mean this to happen under DOS only! JACS
1018 #if defined(__WXMSW__) || defined(__WXPM__)
1029 // Concatenate two files to form third
1031 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
1034 if ( !wxGetTempFileName("cat", outfile
) )
1037 FILE *fp1
= (FILE *) NULL
;
1038 FILE *fp2
= (FILE *) NULL
;
1039 FILE *fp3
= (FILE *) NULL
;
1040 // Open the inputs and outputs
1041 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
1042 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
1043 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
1055 while ((ch
= getc (fp1
)) != EOF
)
1056 (void) putc (ch
, fp3
);
1059 while ((ch
= getc (fp2
)) != EOF
)
1060 (void) putc (ch
, fp3
);
1064 bool result
= wxRenameFile(outfile
, file3
);
1070 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1072 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1073 // CopyFile() copies file attributes and modification time too, so use it
1074 // instead of our code if available
1076 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1077 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1078 #elif defined(__WXPM__)
1079 if (::DosCopy(file2
, file2
, overwrite
? DCPY_EXISTING
: 0) == 0)
1086 // get permissions of file1
1087 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1089 // the file probably doesn't exist or we haven't the rights to read
1091 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1096 // open file1 for reading
1097 wxFile
fileIn(file1
, wxFile::read
);
1098 if ( !fileIn
.IsOpened() )
1101 // remove file2, if it exists. This is needed for creating
1102 // file2 with the correct permissions in the next step
1103 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1105 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1111 // reset the umask as we want to create the file with exactly the same
1112 // permissions as the original one
1113 mode_t oldUmask
= umask( 0 );
1116 // create file2 with the same permissions than file1 and open it for
1119 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1123 /// restore the old umask
1127 // copy contents of file1 to file2
1132 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1133 if ( fileIn
.Error() )
1140 if ( fileOut
.Write(buf
, count
) < count
)
1144 // we can expect fileIn to be closed successfully, but we should ensure
1145 // that fileOut was closed as some write errors (disk full) might not be
1146 // detected before doing this
1147 if ( !fileIn
.Close() || !fileOut
.Close() )
1150 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1151 // no chmod in VA. Should be some permission API for HPFS386 partitions
1153 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1155 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1159 #endif // OS/2 || Mac
1162 #endif // __WXMSW__ && __WIN32__
1166 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1168 // Normal system call
1169 if ( wxRename (file1
, file2
) == 0 )
1173 if (wxCopyFile(file1
, file2
)) {
1174 wxRemoveFile(file1
);
1181 bool wxRemoveFile(const wxString
& file
)
1183 #if defined(__VISUALC__) \
1184 || defined(__BORLANDC__) \
1185 || defined(__WATCOMC__) \
1186 || defined(__GNUWIN32__)
1187 int res
= wxRemove(file
);
1189 int res
= unlink(OS_FILENAME(file
));
1195 bool wxMkdir(const wxString
& dir
, int perm
)
1197 #if defined(__WXMAC__) && !defined(__UNIX__)
1198 return (mkdir( dir
, 0 ) == 0);
1200 const wxChar
*dirname
= dir
.c_str();
1202 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1203 // for the GNU compiler
1204 #if (!(defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1205 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1206 #elif defined(__WXPM__)
1207 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1208 #elif defined(__DOS__)
1209 #if defined(__WATCOMC__)
1211 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1212 #elif defined(__DJGPP__)
1213 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1215 #error "Unsupported DOS compiler!"
1217 #else // !MSW, !DOS and !OS/2 VAC++
1219 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1222 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1231 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1234 return FALSE
; //to be changed since rmdir exists in VMS7.x
1235 #elif defined(__WXPM__)
1236 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1240 return FALSE
; // What to do?
1242 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1248 // does the path exists? (may have or not '/' or '\\' at the end)
1249 bool wxPathExists(const wxChar
*pszPathName
)
1251 wxString
strPath(pszPathName
);
1253 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1254 // so remove all trailing backslashes from the path - but don't do this for
1255 // the pathes "d:\" (which are different from "d:") nor for just "\"
1256 while ( wxEndsWithPathSeparator(strPath
) )
1258 size_t len
= strPath
.length();
1259 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == _T(':')) )
1262 strPath
.Truncate(len
- 1);
1264 #endif // __WINDOWS__
1266 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1267 // Stat can't cope with network paths
1268 DWORD ret
= GetFileAttributes(strPath
.c_str());
1269 DWORD isDir
= (ret
& FILE_ATTRIBUTE_DIRECTORY
);
1270 return ((ret
!= 0xffffffff) && (isDir
!= 0));
1274 #ifndef __VISAGECPP__
1275 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1276 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1278 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1279 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1280 (st
.st_mode
== S_IFDIR
);
1286 // Get a temporary filename, opening and closing the file.
1287 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1289 wxString filename
= wxFileName::CreateTempFileName(prefix
);
1290 if ( filename
.empty() )
1294 wxStrcpy(buf
, filename
);
1296 buf
= copystring(filename
);
1301 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1303 buf
= wxFileName::CreateTempFileName(prefix
);
1305 return !buf
.empty();
1308 // Get first file name matching given wild card.
1310 static wxDir
*gs_dir
= NULL
;
1311 static wxString gs_dirPath
;
1313 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1315 gs_dirPath
= wxPathOnly(spec
);
1316 if ( gs_dirPath
.IsEmpty() )
1317 gs_dirPath
= wxT(".");
1318 if ( gs_dirPath
.Last() != wxFILE_SEP_PATH
)
1319 gs_dirPath
<< wxFILE_SEP_PATH
;
1323 gs_dir
= new wxDir(gs_dirPath
);
1325 if ( !gs_dir
->IsOpened() )
1327 wxLogSysError(_("Can not enumerate files '%s'"), spec
);
1328 return wxEmptyString
;
1334 case wxDIR
: dirFlags
= wxDIR_DIRS
; break;
1335 case wxFILE
: dirFlags
= wxDIR_FILES
; break;
1336 default: dirFlags
= wxDIR_DIRS
| wxDIR_FILES
; break;
1340 gs_dir
->GetFirst(&result
, wxFileNameFromPath(spec
), dirFlags
);
1341 if ( result
.IsEmpty() )
1347 return gs_dirPath
+ result
;
1350 wxString
wxFindNextFile()
1352 wxASSERT_MSG( gs_dir
, wxT("You must call wxFindFirstFile before!") );
1355 gs_dir
->GetNext(&result
);
1357 if ( result
.IsEmpty() )
1363 return gs_dirPath
+ result
;
1367 // Get current working directory.
1368 // If buf is NULL, allocates space using new, else
1370 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1373 buf
= new wxChar
[sz
+1];
1375 char *cbuf
= new char[sz
+1];
1377 if (_getcwd(cbuf
, sz
) == NULL
) {
1378 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1381 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1385 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1386 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1387 strcpy( buf
, res
) ;
1390 if (getcwd(cbuf
, sz
) == NULL
) {
1395 if (_getcwd(buf
, sz
) == NULL
) {
1396 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1401 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1403 pb
.ioRefNum
= LMGetCurApRefNum();
1405 error
= PBGetFCBInfoSync(&pb
);
1406 if ( error
== noErr
)
1408 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1409 cwdSpec
.parID
= pb
.ioFCBParID
;
1410 cwdSpec
.name
[0] = 0 ;
1411 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1413 strcpy( buf
, res
) ;
1414 buf
[res
.length()]=0 ;
1419 this version will not always give back the application directory on mac
1422 SFSaveDisk = 0x214, CurDirStore = 0x398
1426 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1427 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1428 strcpy( buf , res ) ;
1431 #elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
1433 rc
= ::DosQueryCurrentDir( 0 // current drive
1439 if (getcwd(buf
, sz
) == NULL
) {
1447 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1453 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths with
1454 // / deliminers. We don't like that.
1455 for (wxChar
*ch
= buf
; *ch
; ch
++)
1456 if (*ch
== wxT('/')) *ch
= wxT('\\');
1464 static const size_t maxPathLen
= 1024;
1467 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1468 str
.UngetWriteBuf();
1473 bool wxSetWorkingDirectory(const wxString
& d
)
1475 #if defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1476 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1477 #elif defined(__WXPM__)
1478 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1479 #elif defined(__WINDOWS__)
1482 return (bool)(SetCurrentDirectory(d
) != 0);
1484 // Must change drive, too.
1485 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1488 wxChar firstChar
= d
[0];
1492 firstChar
= firstChar
- 32;
1494 // To a drive number
1495 unsigned int driveNo
= firstChar
- 64;
1498 unsigned int noDrives
;
1499 _dos_setdrive(driveNo
, &noDrives
);
1502 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1510 // Get the OS directory if appropriate (such as the Windows directory).
1511 // On non-Windows platform, probably just return the empty string.
1512 wxString
wxGetOSDirectory()
1514 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1516 GetWindowsDirectory(buf
, 256);
1517 return wxString(buf
);
1519 return wxEmptyString
;
1523 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1525 size_t len
= wxStrlen(pszFileName
);
1527 return len
&& wxIsPathSeparator(pszFileName
[len
- 1]);
1530 // find a file in a list of directories, returns false if not found
1531 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1533 // we assume that it's not empty
1534 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1535 _T("empty file name in wxFindFileInPath"));
1537 // skip path separator in the beginning of the file name if present
1538 if ( wxIsPathSeparator(*pszFile
) )
1541 // copy the path (strtok will modify it)
1542 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1543 wxStrcpy(szPath
, pszPath
);
1546 wxChar
*pc
, *save_ptr
;
1547 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1549 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1551 // search for the file in this directory
1553 if ( !wxEndsWithPathSeparator(pc
) )
1554 strFile
+= wxFILE_SEP_PATH
;
1557 if ( FileExists(strFile
) ) {
1563 // suppress warning about unused variable save_ptr when wxStrtok() is a
1564 // macro which throws away its third argument
1569 return pc
!= NULL
; // if true => we breaked from the loop
1572 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1577 // it can be empty, but it shouldn't be NULL
1578 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1580 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1583 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1587 wxStat(filename
.fn_str(), &buf
);
1588 return buf
.st_mtime
;
1592 //------------------------------------------------------------------------
1593 // wild character routines
1594 //------------------------------------------------------------------------
1596 bool wxIsWild( const wxString
& pattern
)
1598 wxString tmp
= pattern
;
1599 wxChar
*pat
= WXSTRINGCAST(tmp
);
1602 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1612 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1614 #if defined(HAVE_FNMATCH_H)
1616 // this probably won't work well for multibyte chars in Unicode mode?
1618 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1620 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1624 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1627 * WARNING: this code is broken!
1630 wxString tmp1
= pat
;
1631 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1632 wxString tmp2
= text
;
1633 wxChar
*str
= WXSTRINGCAST(tmp2
);
1636 bool done
= FALSE
, ret_code
, ok
;
1637 // Below is for vi fans
1638 const wxChar OB
= wxT('{'), CB
= wxT('}');
1640 // dot_special means '.' only matches '.'
1641 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1644 while ((*pattern
!= wxT('\0')) && (!done
)
1645 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1649 if (*pattern
!= wxT('\0'))
1655 while ((*str
!=wxT('\0'))
1656 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1659 while (*str
!= wxT('\0'))
1661 while (*pattern
!= wxT('\0'))
1668 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1672 if (*pattern
== wxT('\\')) {
1674 if (*pattern
== wxT('\0')) {
1679 if (*(pattern
+ 1) == wxT('-')) {
1682 if (*pattern
== wxT(']')) {
1686 if (*pattern
== wxT('\\')) {
1688 if (*pattern
== wxT('\0')) {
1693 if ((*str
< c
) || (*str
> *pattern
)) {
1697 } else if (*pattern
!= *str
) {
1702 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1703 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1707 if (*pattern
!= wxT('\0')) {
1717 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1720 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1721 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1722 if (*pattern
== wxT('\\'))
1724 ok
= (*pattern
++ == *cp
++);
1726 if (*pattern
== wxT('\0')) {
1732 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1733 if (*++pattern
== wxT('\\')) {
1734 if (*++pattern
== CB
)
1739 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1740 if (*++pattern
== wxT('\\')) {
1741 if (*++pattern
== CB
|| *pattern
== wxT(','))
1746 if (*pattern
!= wxT('\0'))
1751 if (*str
== *pattern
) {
1758 while (*pattern
== wxT('*'))
1760 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1766 #pragma warning(default:4706) // assignment within conditional expression
1769 //------------------------------------------------------------------------
1770 // Missing functions in Unicode for Win9x
1771 //------------------------------------------------------------------------
1773 // NB: MSLU only covers Win32 API, it doesn't provide Unicode implementation of
1774 // libc functions. Unfortunately, some of MSVCRT wchar_t functions
1775 // (e.g. _wopen) don't work on Windows 9x, so we have to workaround it
1776 // by calling the char version. We still want to use wchar_t version on
1777 // NT/2000/XP, though, because they allow for Unicode file names.
1778 #if wxUSE_UNICODE_MSLU
1780 #if defined( __VISUALC__ ) \
1781 || ( defined(__MINGW32__) && wxCHECK_W32API_VERSION( 0, 5 ) ) \
1782 || ( defined(__MWERKS__) && defined(__WXMSW__) )
1783 WXDLLEXPORT
int wxOpen(const wxChar
*name
, int flags
, int mode
)
1785 if ( wxGetOsVersion() == wxWINDOWS_NT
)
1786 return _wopen(name
, flags
, mode
);
1788 return _open(wxConvFile
.cWX2MB(name
), flags
, mode
);
1792 #endif // wxUSE_UNICODE_MSLU