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"
37 // there are just too many of those...
39 #pragma warning(disable:4706) // assignment within conditional expression
46 #if !defined(__WATCOMC__)
47 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
55 #include <sys/types.h>
70 #include "wx/os2/private.h"
73 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
78 #endif // native Win compiler
82 #include <sys/unistd.h>
86 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
87 // this (3.1 I believe) and how to test for it.
88 // If this works for Borland 4.0 as well, then no worries.
100 // No, Cygwin doesn't appear to have fnmatch.h after all.
101 #if defined(HAVE_FNMATCH_H)
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 #define _MAXPATHLEN 500
115 extern wxChar
*wxBuffer
;
117 #if defined(__WXMAC__) && !defined(__UNIX__)
118 #include "morefile.h"
119 #include "moreextr.h"
120 #include "fullpath.h"
121 #include "fspcompa.h"
124 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
126 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
132 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
134 // VisualAge C++ V4.0 cannot have any external linkage const decs
135 // in headers included by more than one primary source
137 const off_t wxInvalidOffset
= (off_t
)-1;
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
144 // we need to translate Mac filenames before passing them to OS functions
145 #define OS_FILENAME(s) (s.fn_str())
147 // ============================================================================
149 // ============================================================================
151 void wxPathList::Add (const wxString
& path
)
153 wxStringList::Add (WXSTRINGCAST path
);
156 // Add paths e.g. from the PATH environment variable
157 void wxPathList::AddEnvList (const wxString
& envVariable
)
159 static const wxChar PATH_TOKS
[] =
161 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
166 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
169 wxChar
*s
= copystring (val
);
170 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
174 Add (copystring (token
));
177 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
178 Add (wxString(token
));
182 // suppress warning about unused variable save_ptr when wxStrtok() is a
183 // macro which throws away its third argument
190 // Given a full filename (with path), ensure that that file can
191 // be accessed again USING FILENAME ONLY by adding the path
192 // to the list if not already there.
193 void wxPathList::EnsureFileAccessible (const wxString
& path
)
195 wxString
path_only(wxPathOnly(path
));
196 if ( !path_only
.IsEmpty() )
198 if ( !Member(path_only
) )
203 bool wxPathList::Member (const wxString
& path
)
205 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
207 wxString
path2((wxChar
*) node
->Data ());
209 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
211 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
213 // Case sensitive File System
214 path
.CompareTo (path2
) == 0
222 wxString
wxPathList::FindValidPath (const wxString
& file
)
224 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
225 return wxString(wxFileFunctionsBuffer
);
227 wxChar buf
[_MAXPATHLEN
];
228 wxStrcpy(buf
, wxFileFunctionsBuffer
);
230 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
231 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
233 for (wxNode
* node
= First (); node
; node
= node
->Next ())
235 wxChar
*path
= (wxChar
*) node
->Data ();
236 wxStrcpy (wxFileFunctionsBuffer
, path
);
237 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
238 if (ch
!= wxT('\\') && ch
!= wxT('/'))
239 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
240 wxStrcat (wxFileFunctionsBuffer
, filename
);
242 Unix2DosFilename (wxFileFunctionsBuffer
);
244 if (wxFileExists (wxFileFunctionsBuffer
))
246 return wxString(wxFileFunctionsBuffer
); // Found!
250 return wxString(wxT("")); // Not found
253 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
255 wxString f
= FindValidPath(file
);
256 if ( wxIsAbsolutePath(f
) )
260 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
262 if ( !wxEndsWithPathSeparator(buf
) )
264 buf
+= wxFILE_SEP_PATH
;
272 wxFileExists (const wxString
& filename
)
274 #ifdef __GNUWIN32__ // (fix a B20 bug)
275 return GetFileAttributes(filename
) != 0xFFFFFFFF;
278 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
286 wxIsAbsolutePath (const wxString
& filename
)
288 if (filename
!= wxT(""))
290 if (filename
[0] == wxT('/')
292 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
296 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
305 * Strip off any extension (dot something) from end of file,
306 * IF one exists. Inserts zero into buffer.
310 void wxStripExtension(wxChar
*buffer
)
312 int len
= wxStrlen(buffer
);
316 if (buffer
[i
] == wxT('.'))
325 void wxStripExtension(wxString
& buffer
)
327 size_t len
= buffer
.Length();
331 if (buffer
.GetChar(i
) == wxT('.'))
333 buffer
= buffer
.Left(i
);
340 // Destructive removal of /./ and /../ stuff
341 wxChar
*wxRealPath (wxChar
*path
)
344 static const wxChar SEP
= wxT('\\');
345 Unix2DosFilename(path
);
347 static const wxChar SEP
= wxT('/');
349 if (path
[0] && path
[1]) {
350 /* MATTHEW: special case "/./x" */
352 if (path
[2] == SEP
&& path
[1] == wxT('.'))
360 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
363 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
364 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
365 && (q
- 1 <= path
|| q
[-1] != SEP
))
368 if (path
[0] == wxT('\0'))
374 /* Check that path[2] is NULL! */
375 else if (path
[1] == wxT(':') && !path
[2])
384 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
393 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
395 if (filename
== wxT(""))
396 return (wxChar
*) NULL
;
398 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
399 wxChar buf
[_MAXPATHLEN
];
401 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
402 wxChar ch
= buf
[wxStrlen(buf
) - 1];
404 if (ch
!= wxT('\\') && ch
!= wxT('/'))
405 wxStrcat(buf
, wxT("\\"));
408 wxStrcat(buf
, wxT("/"));
410 wxStrcat(buf
, wxFileFunctionsBuffer
);
411 return copystring( wxRealPath(buf
) );
413 return copystring( wxFileFunctionsBuffer
);
419 ~user/ => user's home dir
420 If the environment variable a = "foo" and b = "bar" then:
437 /* input name in name, pathname output to buf. */
439 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
441 register wxChar
*d
, *s
, *nm
;
442 wxChar lnm
[_MAXPATHLEN
];
445 // Some compilers don't like this line.
446 // const wxChar trimchars[] = wxT("\n \t");
449 trimchars
[0] = wxT('\n');
450 trimchars
[1] = wxT(' ');
451 trimchars
[2] = wxT('\t');
455 const wxChar SEP
= wxT('\\');
457 const wxChar SEP
= wxT('/');
460 if (name
== NULL
|| *name
== wxT('\0'))
462 nm
= copystring(name
); // Make a scratch copy
465 /* Skip leading whitespace and cr */
466 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
468 /* And strip off trailing whitespace and cr */
469 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
470 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
478 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
481 /* Expand inline environment variables */
499 while ((*d
++ = *s
) != 0) {
501 if (*s
== wxT('\\')) {
502 if ((*(d
- 1) = *++s
)) {
511 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
513 if (*s
++ == wxT('$'))
516 register wxChar
*start
= d
;
517 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
518 register wxChar
*value
;
519 while ((*d
++ = *s
) != 0)
520 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
525 value
= wxGetenv(braces
? start
+ 1 : start
);
527 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
535 /* Expand ~ and ~user */
538 if (nm
[0] == wxT('~') && !q
)
541 if (nm
[1] == SEP
|| nm
[1] == 0)
543 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
544 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
549 { /* ~user/filename */
550 register wxChar
*nnm
;
551 register wxChar
*home
;
552 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
553 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
554 was_sep
= (*s
== SEP
);
555 nnm
= *s
? s
+ 1 : s
;
557 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
558 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
559 if (was_sep
) /* replace only if it was there: */
570 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
572 while (wxT('\0') != (*d
++ = *s
++))
575 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
579 while ((*d
++ = *s
++) != 0);
580 delete[] nm_tmp
; // clean up alloc
581 /* Now clean up the buffer */
582 return wxRealPath(buf
);
585 /* Contract Paths to be build upon an environment variable
588 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
590 The call wxExpandPath can convert these back!
593 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
595 static wxChar dest
[_MAXPATHLEN
];
597 if (filename
== wxT(""))
598 return (wxChar
*) NULL
;
600 wxStrcpy (dest
, WXSTRINGCAST filename
);
602 Unix2DosFilename(dest
);
605 // Handle environment
606 const wxChar
*val
= (const wxChar
*) NULL
;
607 wxChar
*tcp
= (wxChar
*) NULL
;
608 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
609 (tcp
= wxStrstr (dest
, val
)) != NULL
)
611 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
614 wxStrcpy (tcp
, WXSTRINGCAST envname
);
615 wxStrcat (tcp
, wxT("}"));
616 wxStrcat (tcp
, wxFileFunctionsBuffer
);
619 // Handle User's home (ignore root homes!)
621 if ((val
= wxGetUserHome (user
)) != NULL
&&
622 (len
= wxStrlen(val
)) > 2 &&
623 wxStrncmp(dest
, val
, len
) == 0)
625 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
627 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
629 // strcat(wxFileFunctionsBuffer, "\\");
631 // strcat(wxFileFunctionsBuffer, "/");
633 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
634 wxStrcpy (dest
, wxFileFunctionsBuffer
);
640 // Return just the filename, not the path
642 wxChar
*wxFileNameFromPath (wxChar
*path
)
646 register wxChar
*tcp
;
648 tcp
= path
+ wxStrlen (path
);
649 while (--tcp
>= path
)
652 if (*tcp
== wxT(':') )
654 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
656 || *tcp
== wxT(':') || *tcp
== wxT(']'))
663 #if defined(__WXMSW__) || defined(__WXPM__)
664 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
671 wxString
wxFileNameFromPath (const wxString
& path1
)
673 if (path1
!= wxT(""))
676 wxChar
*path
= WXSTRINGCAST path1
;
677 register wxChar
*tcp
;
679 tcp
= path
+ wxStrlen (path
);
680 while (--tcp
>= path
)
683 if (*tcp
== wxT(':') )
685 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
687 || *tcp
== wxT(':') || *tcp
== wxT(']'))
692 return wxString(tcp
+ 1);
694 #if defined(__WXMSW__) || defined(__WXPM__)
695 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
696 return wxString(path
+ 2);
699 // Yes, this should return the path, not an empty string, otherwise
700 // we get "thing.txt" -> "".
704 // Return just the directory, or NULL if no directory
706 wxPathOnly (wxChar
*path
)
710 static wxChar buf
[_MAXPATHLEN
];
713 wxStrcpy (buf
, path
);
715 int l
= wxStrlen(path
);
720 // Search backward for a backward or forward slash
721 while (!done
&& i
> -1)
725 if (path
[i
] == wxT(':') )
727 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
732 if ( path
[i
] == wxT(']') )
743 #if defined(__WXMSW__) || defined(__WXPM__)
744 // Try Drive specifier
745 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
747 // A:junk --> A:. (since A:.\junk Not A:\junk)
755 return (wxChar
*) NULL
;
758 // Return just the directory, or NULL if no directory
759 wxString
wxPathOnly (const wxString
& path
)
763 wxChar buf
[_MAXPATHLEN
];
766 wxStrcpy (buf
, WXSTRINGCAST path
);
768 int l
= path
.Length();
773 // Search backward for a backward or forward slash
774 while (!done
&& i
> -1)
778 if (path
[i
] == wxT(':') )
780 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
785 if ( path
[i
] == wxT(']') )
791 return wxString(buf
);
796 #if defined(__WXMSW__) || defined(__WXPM__)
797 // Try Drive specifier
798 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
800 // A:junk --> A:. (since A:.\junk Not A:\junk)
803 return wxString(buf
);
808 return wxString(wxT(""));
811 // Utility for converting delimiters in DOS filenames to UNIX style
812 // and back again - or we get nasty problems with delimiters.
813 // Also, convert to lower case, since case is significant in UNIX.
815 #if defined(__WXMAC__) && !defined(__UNIX__)
816 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
821 FSpGetFullPath( spec
, &length
, &myPath
) ;
822 ::SetHandleSize( myPath
, length
+ 1 ) ;
824 (*myPath
)[length
] = 0 ;
825 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
826 (*myPath
)[length
-1] = 0 ;
828 wxString
result( (char*) *myPath
) ;
829 ::HUnlock( myPath
) ;
830 ::DisposeHandle( myPath
) ;
834 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
836 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
840 static char sMacFileNameConversion[ 1000 ] ;
842 wxString wxMac2UnixFilename (const char *str)
844 char *s = sMacFileNameConversion ;
848 memmove( s+1 , s ,strlen( s ) + 1) ;
859 *s = wxTolower (*s); // Case INDEPENDENT
863 return wxString (sMacFileNameConversion) ;
866 wxString wxUnix2MacFilename (const char *str)
868 char *s = sMacFileNameConversion ;
874 // relative path , since it goes on with slash which is translated to a :
875 memmove( s , s+1 ,strlen( s ) ) ;
877 else if ( *s == '/' )
879 // absolute path -> on mac just start with the drive name
880 memmove( s , s+1 ,strlen( s ) ) ;
884 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
888 if (*s == '/' || *s == '\\')
890 // convert any back-directory situations
891 if ( *(s+1) == '.' && *(s+2) == '.' && ( (*(s+3) == '/' || *(s+3) == '\\') ) )
894 memmove( s+1 , s+3 ,strlen( s+3 ) + 1 ) ;
903 return wxString (sMacFileNameConversion) ;
906 wxString wxMacFSSpec2UnixFilename( const FSSpec *spec )
908 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec) ) ;
911 void wxMacFilename2FSSpec( const char *path , FSSpec *spec )
913 FSpLocationFromFullPath( strlen(path ) , path , spec ) ;
916 void wxUnixFilename2FSSpec( const char *path , FSSpec *spec )
918 wxString var = wxUnix2MacFilename( path ) ;
919 wxMacFilename2FSSpec( var , spec ) ;
924 wxDos2UnixFilename (char *s
)
933 *s
= wxTolower (*s
); // Case INDEPENDENT
940 #if defined(__WXMSW__) || defined(__WXPM__)
941 wxUnix2DosFilename (wxChar
*s
)
943 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
946 // Yes, I really mean this to happen under DOS only! JACS
947 #if defined(__WXMSW__) || defined(__WXPM__)
958 // Concatenate two files to form third
960 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
963 if ( !wxGetTempFileName("cat", outfile
) )
966 FILE *fp1
= (FILE *) NULL
;
967 FILE *fp2
= (FILE *) NULL
;
968 FILE *fp3
= (FILE *) NULL
;
969 // Open the inputs and outputs
970 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
971 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
972 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
984 while ((ch
= getc (fp1
)) != EOF
)
985 (void) putc (ch
, fp3
);
988 while ((ch
= getc (fp2
)) != EOF
)
989 (void) putc (ch
, fp3
);
993 bool result
= wxRenameFile(outfile
, file3
);
999 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1001 #if defined(__WIN32__)
1002 // CopyFile() copies file attributes and modification time too, so use it
1003 // instead of our code if available
1005 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1006 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1010 // get permissions of file1
1011 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1013 // the file probably doesn't exist or we haven't the rights to read
1015 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1020 // open file1 for reading
1021 wxFile
fileIn(file1
, wxFile::read
);
1022 if ( !fileIn
.IsOpened() )
1025 // remove file2, if it exists. This is needed for creating
1026 // file2 with the correct permissions in the next step
1027 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1029 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1035 // reset the umask as we want to create the file with exactly the same
1036 // permissions as the original one
1037 mode_t oldUmask
= umask( 0 );
1040 // create file2 with the same permissions than file1 and open it for
1043 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1047 /// restore the old umask
1051 // copy contents of file1 to file2
1056 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1057 if ( fileIn
.Error() )
1064 if ( fileOut
.Write(buf
, count
) < count
)
1068 // we can expect fileIn to be closed successfully, but we should ensure
1069 // that fileOut was closed as some write errors (disk full) might not be
1070 // detected before doing this
1071 if ( !fileIn
.Close() || !fileOut
.Close() )
1074 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1075 // no chmod in VA. Should be some permission API for HPFS386 partitions
1077 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1079 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1083 #endif // OS/2 || Mac
1086 #endif // __WXMSW__ && __WIN32__
1090 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1092 // Normal system call
1093 if ( wxRename (file1
, file2
) == 0 )
1097 if (wxCopyFile(file1
, file2
)) {
1098 wxRemoveFile(file1
);
1105 bool wxRemoveFile(const wxString
& file
)
1107 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1108 int res
= wxRemove(file
);
1110 int res
= unlink(OS_FILENAME(file
));
1116 bool wxMkdir(const wxString
& dir
, int perm
)
1118 #if defined(__WXMAC__) && !defined(__UNIX__)
1119 return (mkdir( dir
, 0 ) == 0);
1121 const wxChar
*dirname
= dir
.c_str();
1123 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1124 // for the GNU compiler
1125 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1126 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1127 #elif defined(__WXPM__)
1128 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1129 #else // !MSW and !OS/2 VAC++
1131 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1134 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1143 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1146 return FALSE
; //to be changed since rmdir exists in VMS7.x
1147 #elif defined(__WXPM__)
1148 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1152 return FALSE
; // What to do?
1154 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1160 // does the path exists? (may have or not '/' or '\\' at the end)
1161 bool wxPathExists(const wxChar
*pszPathName
)
1163 wxString
strPath(pszPathName
);
1165 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1166 // so remove all trailing backslashes from the path - but don't do this for
1167 // the pathes "d:\" (which are different from "d:") nor for just "\"
1168 while ( wxEndsWithPathSeparator(strPath
) )
1170 size_t len
= strPath
.length();
1171 if ( len
== 1 || strPath
[len
- 1] == _T(':') )
1174 strPath
.Truncate(len
- 1);
1176 #endif // __WINDOWS__
1179 #ifndef __VISAGECPP__
1180 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1181 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1183 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1184 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1185 (st
.st_mode
== S_IFDIR
);
1190 // Get a temporary filename, opening and closing the file.
1191 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1197 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1199 wxChar tmp
[MAX_PATH
];
1200 wxChar tmpPath
[MAX_PATH
];
1201 ::GetTempPath(MAX_PATH
, tmpPath
);
1202 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1204 if (buf
) wxStrcpy(buf
, tmp
);
1205 else buf
= copystring(tmp
);
1209 static short last_temp
= 0; // cache last to speed things a bit
1210 // At most 1000 temp files to a process! We use a ring count.
1211 wxChar tmp
[100]; // FIXME static buffer
1213 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1215 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1216 if (!wxFileExists( tmp
))
1218 // Touch the file to create it (reserve name)
1219 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1224 wxStrcpy( buf
, tmp
);
1226 buf
= copystring( tmp
);
1230 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1231 if (buf
) buf
[0] = 0;
1232 return (wxChar
*) NULL
;
1236 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1239 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1248 // Get first file name matching given wild card.
1252 // Get first file name matching given wild card.
1253 // Flags are reserved for future use.
1255 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1256 static DIR *gs_dirStream
= (DIR *) NULL
;
1257 static wxString gs_strFileSpec
;
1258 static int gs_findFlags
= 0;
1261 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1265 wxChar
*specvms
= NULL
;
1268 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1270 closedir(gs_dirStream
); // edz 941103: better housekeping
1272 gs_findFlags
= flags
;
1274 gs_strFileSpec
= spec
;
1276 // Find path only so we can concatenate
1277 // found file onto path
1278 wxString
path(wxPathOnly(gs_strFileSpec
));
1280 // special case: path is really "/"
1281 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1284 wxStrcpy( specvms
, wxT( "[000000]" ) );
1285 gs_strFileSpec
= specvms
;
1286 wxString
path_vms(wxPathOnly(gs_strFileSpec
));
1292 // path is empty => Local directory
1296 wxStrcpy( specvms
, wxT( "[]" ) );
1297 gs_strFileSpec
= specvms
;
1298 wxString
path_vms1(wxPathOnly(gs_strFileSpec
));
1305 gs_dirStream
= opendir(path
.fn_str());
1306 if ( !gs_dirStream
)
1308 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1313 result
= wxFindNextFile();
1315 #endif // !VMS6.x or earlier
1320 wxString
wxFindNextFile()
1324 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1325 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1327 // Find path only so we can concatenate
1328 // found file onto path
1329 wxString
path(wxPathOnly(gs_strFileSpec
));
1330 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1332 /* MATTHEW: special case: path is really "/" */
1333 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1337 struct dirent
*nextDir
;
1338 for ( nextDir
= readdir(gs_dirStream
);
1340 nextDir
= readdir(gs_dirStream
) )
1342 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1343 strcmp(nextDir
->d_name
, ".") &&
1344 strcmp(nextDir
->d_name
, "..") )
1347 if ( !path
.IsEmpty() )
1350 if ( path
!= wxT('/') )
1354 result
+= nextDir
->d_name
;
1356 // Only return "." and ".." when they match
1358 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1359 (strcmp(nextDir
->d_name
, "..") == 0))
1361 if ( (gs_findFlags
& wxDIR
) != 0 )
1367 isdir
= wxDirExists(result
);
1369 // and only return directories when flags & wxDIR
1370 if ( !gs_findFlags
||
1371 ((gs_findFlags
& wxDIR
) && isdir
) ||
1372 ((gs_findFlags
& wxFILE
) && !isdir
) )
1379 result
.Empty(); // not found
1381 closedir(gs_dirStream
);
1382 gs_dirStream
= (DIR *) NULL
;
1383 #endif // !VMS6.2 or earlier
1388 #elif defined(__WXMAC__)
1390 struct MacDirectoryIterator
1398 static int g_iter_flags
;
1400 static MacDirectoryIterator g_iter
;
1402 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1406 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1408 // Find path only so we can concatenate found file onto path
1409 wxString
path(wxPathOnly(spec
));
1410 if ( !path
.IsEmpty() )
1411 result
<< path
<< wxT('\\');
1415 wxMacFilename2FSSpec( result
, &fsspec
) ;
1416 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1417 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1418 g_iter
.m_index
= 0 ;
1421 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1423 return wxEmptyString
;
1425 return wxFindNextFile( ) ;
1428 wxString
wxFindNextFile()
1434 while ( err
== noErr
)
1437 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1438 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1439 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1443 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1446 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1454 return wxEmptyString
;
1458 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1463 return wxMacFSSpec2MacFilename( &spec
) ;
1466 #elif defined(__WXMSW__)
1469 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1470 static WIN32_FIND_DATA gs_findDataStruct
;
1473 static struct ffblk gs_findDataStruct
;
1475 static struct _find_t gs_findDataStruct
;
1479 static wxString gs_strFileSpec
;
1480 static int gs_findFlags
= 0;
1482 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1486 gs_strFileSpec
= spec
;
1487 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1489 // Find path only so we can concatenate found file onto path
1490 wxString
path(wxPathOnly(gs_strFileSpec
));
1491 if ( !path
.IsEmpty() )
1492 result
<< path
<< wxT('\\');
1495 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1496 FindClose(gs_hFileStruct
);
1498 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1500 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1507 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1509 if (isdir
&& !(flags
& wxDIR
))
1510 return wxFindNextFile();
1511 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1512 return wxFindNextFile();
1514 result
+= gs_findDataStruct
.cFileName
;
1518 int flag
= _A_NORMAL
;
1523 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1525 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1531 attrib
= gs_findDataStruct
.ff_attrib
;
1533 attrib
= gs_findDataStruct
.attrib
;
1536 if (attrib
& _A_SUBDIR
) {
1537 if (!(gs_findFlags
& wxDIR
))
1538 return wxFindNextFile();
1539 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1540 return wxFindNextFile();
1544 gs_findDataStruct
.ff_name
1546 gs_findDataStruct
.name
1556 wxString
wxFindNextFile()
1560 // Find path only so we can concatenate found file onto path
1561 wxString
path(wxPathOnly(gs_strFileSpec
));
1566 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1569 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1572 FindClose(gs_hFileStruct
);
1573 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1577 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1579 if (isdir
&& !(gs_findFlags
& wxDIR
))
1581 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1584 if ( !path
.IsEmpty() )
1585 result
<< path
<< wxT('\\');
1586 result
<< gs_findDataStruct
.cFileName
;
1593 if (findnext(&gs_findDataStruct
) == 0)
1595 if (_dos_findnext(&gs_findDataStruct
) == 0)
1598 /* MATTHEW: [5] Check directory flag */
1602 attrib
= gs_findDataStruct
.ff_attrib
;
1604 attrib
= gs_findDataStruct
.attrib
;
1607 if (attrib
& _A_SUBDIR
) {
1608 if (!(gs_findFlags
& wxDIR
))
1610 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1616 gs_findDataStruct
.ff_name
1618 gs_findDataStruct
.name
1627 #elif defined(__WXPM__)
1629 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1634 // TODO: figure something out here for OS/2
1635 gs_strFileSpec = spec;
1636 gs_findFlags = flags;
1638 // Find path only so we can concatenate found file onto path
1639 wxString path(wxPathOnly(gs_strFileSpec));
1640 if ( !path.IsEmpty() )
1641 result << path << wxT('\\');
1643 int flag = _A_NORMAL;
1647 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1650 attrib = gs_findDataStruct.attrib;
1652 if (attrib & _A_SUBDIR) {
1653 if (!(gs_findFlags & wxDIR))
1654 return wxFindNextFile();
1655 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1656 return wxFindNextFile();
1658 result += gs_findDataStruct.name;
1664 wxString
wxFindNextFile()
1671 #endif // Unix/Windows/OS/2
1673 // Get current working directory.
1674 // If buf is NULL, allocates space using new, else
1676 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1679 buf
= new wxChar
[sz
+1];
1681 char *cbuf
= new char[sz
+1];
1683 if (_getcwd(cbuf
, sz
) == NULL
) {
1684 #elif defined(__WXMAC__) && !defined(__UNIX__)
1687 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1691 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1692 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1693 strcpy( buf
, res
) ;
1696 if (getcwd(cbuf
, sz
) == NULL
) {
1701 if (_getcwd(buf
, sz
) == NULL
) {
1702 #elif defined(__WXMAC__) && !defined(__UNIX__)
1707 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1709 pb
.ioRefNum
= LMGetCurApRefNum();
1711 error
= PBGetFCBInfoSync(&pb
);
1712 if ( error
== noErr
)
1714 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1715 cwdSpec
.parID
= pb
.ioFCBParID
;
1716 cwdSpec
.name
[0] = 0 ;
1717 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1719 strcpy( buf
, res
) ;
1720 buf
[res
.length()-1]=0 ;
1725 this version will not always give back the application directory on mac
1728 SFSaveDisk = 0x214, CurDirStore = 0x398
1732 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1733 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1734 strcpy( buf , res ) ;
1737 #elif(__VISAGECPP__)
1739 rc
= ::DosQueryCurrentDir( 0 // current drive
1745 if (getcwd(buf
, sz
) == NULL
) {
1753 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1762 static const size_t maxPathLen
= 1024;
1765 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1766 str
.UngetWriteBuf();
1771 bool wxSetWorkingDirectory(const wxString
& d
)
1773 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1774 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1775 #elif defined(__WXPM__)
1776 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1777 #elif defined(__WINDOWS__)
1780 return (bool)(SetCurrentDirectory(d
) != 0);
1782 // Must change drive, too.
1783 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1786 wxChar firstChar
= d
[0];
1790 firstChar
= firstChar
- 32;
1792 // To a drive number
1793 unsigned int driveNo
= firstChar
- 64;
1796 unsigned int noDrives
;
1797 _dos_setdrive(driveNo
, &noDrives
);
1800 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1808 // Get the OS directory if appropriate (such as the Windows directory).
1809 // On non-Windows platform, probably just return the empty string.
1810 wxString
wxGetOSDirectory()
1814 GetWindowsDirectory(buf
, 256);
1815 return wxString(buf
);
1817 return wxEmptyString
;
1821 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1823 size_t len
= wxStrlen(pszFileName
);
1827 return wxIsPathSeparator(pszFileName
[len
- 1]);
1830 // find a file in a list of directories, returns false if not found
1831 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1833 // we assume that it's not empty
1834 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1835 _T("empty file name in wxFindFileInPath"));
1837 // skip path separator in the beginning of the file name if present
1838 if ( wxIsPathSeparator(*pszFile
) )
1841 // copy the path (strtok will modify it)
1842 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1843 wxStrcpy(szPath
, pszPath
);
1846 wxChar
*pc
, *save_ptr
;
1847 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1849 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1851 // search for the file in this directory
1853 if ( !wxEndsWithPathSeparator(pc
) )
1854 strFile
+= wxFILE_SEP_PATH
;
1857 if ( FileExists(strFile
) ) {
1863 // suppress warning about unused variable save_ptr when wxStrtok() is a
1864 // macro which throws away its third argument
1869 return pc
!= NULL
; // if true => we breaked from the loop
1872 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1877 // it can be empty, but it shouldn't be NULL
1878 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1880 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1883 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1887 wxStat(filename
.fn_str(), &buf
);
1888 return buf
.st_mtime
;
1892 //------------------------------------------------------------------------
1893 // wild character routines
1894 //------------------------------------------------------------------------
1896 bool wxIsWild( const wxString
& pattern
)
1898 wxString tmp
= pattern
;
1899 wxChar
*pat
= WXSTRINGCAST(tmp
);
1902 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1912 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1914 #if defined(HAVE_FNMATCH_H)
1916 // this probably won't work well for multibyte chars in Unicode mode?
1918 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1920 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1924 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1927 * WARNING: this code is broken!
1930 wxString tmp1
= pat
;
1931 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1932 wxString tmp2
= text
;
1933 wxChar
*str
= WXSTRINGCAST(tmp2
);
1936 bool done
= FALSE
, ret_code
, ok
;
1937 // Below is for vi fans
1938 const wxChar OB
= wxT('{'), CB
= wxT('}');
1940 // dot_special means '.' only matches '.'
1941 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1944 while ((*pattern
!= wxT('\0')) && (!done
)
1945 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1949 if (*pattern
!= wxT('\0'))
1955 while ((*str
!=wxT('\0'))
1956 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1959 while (*str
!= wxT('\0'))
1961 while (*pattern
!= wxT('\0'))
1968 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1972 if (*pattern
== wxT('\\')) {
1974 if (*pattern
== wxT('\0')) {
1979 if (*(pattern
+ 1) == wxT('-')) {
1982 if (*pattern
== wxT(']')) {
1986 if (*pattern
== wxT('\\')) {
1988 if (*pattern
== wxT('\0')) {
1993 if ((*str
< c
) || (*str
> *pattern
)) {
1997 } else if (*pattern
!= *str
) {
2002 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
2003 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
2007 if (*pattern
!= wxT('\0')) {
2017 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2020 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
2021 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
2022 if (*pattern
== wxT('\\'))
2024 ok
= (*pattern
++ == *cp
++);
2026 if (*pattern
== wxT('\0')) {
2032 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2033 if (*++pattern
== wxT('\\')) {
2034 if (*++pattern
== CB
)
2039 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2040 if (*++pattern
== wxT('\\')) {
2041 if (*++pattern
== CB
|| *pattern
== wxT(','))
2046 if (*pattern
!= wxT('\0'))
2051 if (*str
== *pattern
) {
2058 while (*pattern
== wxT('*'))
2060 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2066 #pragma warning(default:4706) // assignment within conditional expression