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
83 #include <sys/unistd.h>
87 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
88 // this (3.1 I believe) and how to test for it.
89 // If this works for Borland 4.0 as well, then no worries.
101 // No, Cygwin doesn't appear to have fnmatch.h after all.
102 #if defined(HAVE_FNMATCH_H)
110 // ----------------------------------------------------------------------------
112 // ----------------------------------------------------------------------------
114 #define _MAXPATHLEN 500
116 extern wxChar
*wxBuffer
;
118 #if defined(__WXMAC__) && !defined(__UNIX__)
119 #include "morefile.h"
120 #include "moreextr.h"
121 #include "fullpath.h"
122 #include "fspcompa.h"
125 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
127 // ----------------------------------------------------------------------------
129 // ----------------------------------------------------------------------------
131 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
133 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
135 // VisualAge C++ V4.0 cannot have any external linkage const decs
136 // in headers included by more than one primary source
138 const off_t wxInvalidOffset
= (off_t
)-1;
141 // ----------------------------------------------------------------------------
143 // ----------------------------------------------------------------------------
145 // we need to translate Mac filenames before passing them to OS functions
146 #define OS_FILENAME(s) (s.fn_str())
148 // ============================================================================
150 // ============================================================================
152 void wxPathList::Add (const wxString
& path
)
154 wxStringList::Add (WXSTRINGCAST path
);
157 // Add paths e.g. from the PATH environment variable
158 void wxPathList::AddEnvList (const wxString
& envVariable
)
160 static const wxChar PATH_TOKS
[] =
162 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
167 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
170 wxChar
*s
= copystring (val
);
171 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
175 Add (copystring (token
));
178 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
179 Add (wxString(token
));
183 // suppress warning about unused variable save_ptr when wxStrtok() is a
184 // macro which throws away its third argument
191 // Given a full filename (with path), ensure that that file can
192 // be accessed again USING FILENAME ONLY by adding the path
193 // to the list if not already there.
194 void wxPathList::EnsureFileAccessible (const wxString
& path
)
196 wxString
path_only(wxPathOnly(path
));
197 if ( !path_only
.IsEmpty() )
199 if ( !Member(path_only
) )
204 bool wxPathList::Member (const wxString
& path
)
206 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
208 wxString
path2((wxChar
*) node
->Data ());
210 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
212 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
214 // Case sensitive File System
215 path
.CompareTo (path2
) == 0
223 wxString
wxPathList::FindValidPath (const wxString
& file
)
225 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
226 return wxString(wxFileFunctionsBuffer
);
228 wxChar buf
[_MAXPATHLEN
];
229 wxStrcpy(buf
, wxFileFunctionsBuffer
);
231 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
232 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
234 for (wxNode
* node
= First (); node
; node
= node
->Next ())
236 wxChar
*path
= (wxChar
*) node
->Data ();
237 wxStrcpy (wxFileFunctionsBuffer
, path
);
238 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
239 if (ch
!= wxT('\\') && ch
!= wxT('/'))
240 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
241 wxStrcat (wxFileFunctionsBuffer
, filename
);
243 Unix2DosFilename (wxFileFunctionsBuffer
);
245 if (wxFileExists (wxFileFunctionsBuffer
))
247 return wxString(wxFileFunctionsBuffer
); // Found!
251 return wxString(wxT("")); // Not found
254 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
256 wxString f
= FindValidPath(file
);
257 if ( wxIsAbsolutePath(f
) )
261 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
263 if ( !wxEndsWithPathSeparator(buf
) )
265 buf
+= wxFILE_SEP_PATH
;
273 wxFileExists (const wxString
& filename
)
275 #ifdef __GNUWIN32__ // (fix a B20 bug)
276 return GetFileAttributes(filename
) != 0xFFFFFFFF;
279 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
287 wxIsAbsolutePath (const wxString
& filename
)
290 if (filename
!= wxT(""))
292 // This seems wrong to me, but there is no fix. since
293 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
294 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
296 if (filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':')
301 if (filename
!= wxT(""))
303 if (filename
[0] == wxT('/')
305 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
309 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
319 * Strip off any extension (dot something) from end of file,
320 * IF one exists. Inserts zero into buffer.
324 void wxStripExtension(wxChar
*buffer
)
326 int len
= wxStrlen(buffer
);
330 if (buffer
[i
] == wxT('.'))
339 void wxStripExtension(wxString
& buffer
)
341 size_t len
= buffer
.Length();
345 if (buffer
.GetChar(i
) == wxT('.'))
347 buffer
= buffer
.Left(i
);
354 // Destructive removal of /./ and /../ stuff
355 wxChar
*wxRealPath (wxChar
*path
)
358 static const wxChar SEP
= wxT('\\');
359 Unix2DosFilename(path
);
361 static const wxChar SEP
= wxT('/');
363 if (path
[0] && path
[1]) {
364 /* MATTHEW: special case "/./x" */
366 if (path
[2] == SEP
&& path
[1] == wxT('.'))
374 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
377 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
378 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
379 && (q
- 1 <= path
|| q
[-1] != SEP
))
382 if (path
[0] == wxT('\0'))
388 /* Check that path[2] is NULL! */
389 else if (path
[1] == wxT(':') && !path
[2])
398 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
407 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
409 if (filename
== wxT(""))
410 return (wxChar
*) NULL
;
412 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
413 wxChar buf
[_MAXPATHLEN
];
415 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
416 wxChar ch
= buf
[wxStrlen(buf
) - 1];
418 if (ch
!= wxT('\\') && ch
!= wxT('/'))
419 wxStrcat(buf
, wxT("\\"));
422 wxStrcat(buf
, wxT("/"));
424 wxStrcat(buf
, wxFileFunctionsBuffer
);
425 return copystring( wxRealPath(buf
) );
427 return copystring( wxFileFunctionsBuffer
);
433 ~user/ => user's home dir
434 If the environment variable a = "foo" and b = "bar" then:
451 /* input name in name, pathname output to buf. */
453 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
455 register wxChar
*d
, *s
, *nm
;
456 wxChar lnm
[_MAXPATHLEN
];
459 // Some compilers don't like this line.
460 // const wxChar trimchars[] = wxT("\n \t");
463 trimchars
[0] = wxT('\n');
464 trimchars
[1] = wxT(' ');
465 trimchars
[2] = wxT('\t');
469 const wxChar SEP
= wxT('\\');
471 const wxChar SEP
= wxT('/');
474 if (name
== NULL
|| *name
== wxT('\0'))
476 nm
= copystring(name
); // Make a scratch copy
479 /* Skip leading whitespace and cr */
480 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
482 /* And strip off trailing whitespace and cr */
483 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
484 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
492 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
495 /* Expand inline environment variables */
513 while ((*d
++ = *s
) != 0) {
515 if (*s
== wxT('\\')) {
516 if ((*(d
- 1) = *++s
)) {
525 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
527 if (*s
++ == wxT('$'))
530 register wxChar
*start
= d
;
531 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
532 register wxChar
*value
;
533 while ((*d
++ = *s
) != 0)
534 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
539 value
= wxGetenv(braces
? start
+ 1 : start
);
541 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
549 /* Expand ~ and ~user */
552 if (nm
[0] == wxT('~') && !q
)
555 if (nm
[1] == SEP
|| nm
[1] == 0)
557 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
558 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
563 { /* ~user/filename */
564 register wxChar
*nnm
;
565 register wxChar
*home
;
566 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
567 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
568 was_sep
= (*s
== SEP
);
569 nnm
= *s
? s
+ 1 : s
;
571 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
572 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
573 if (was_sep
) /* replace only if it was there: */
584 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
586 while (wxT('\0') != (*d
++ = *s
++))
589 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
593 while ((*d
++ = *s
++) != 0);
594 delete[] nm_tmp
; // clean up alloc
595 /* Now clean up the buffer */
596 return wxRealPath(buf
);
599 /* Contract Paths to be build upon an environment variable
602 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
604 The call wxExpandPath can convert these back!
607 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
609 static wxChar dest
[_MAXPATHLEN
];
611 if (filename
== wxT(""))
612 return (wxChar
*) NULL
;
614 wxStrcpy (dest
, WXSTRINGCAST filename
);
616 Unix2DosFilename(dest
);
619 // Handle environment
620 const wxChar
*val
= (const wxChar
*) NULL
;
621 wxChar
*tcp
= (wxChar
*) NULL
;
622 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
623 (tcp
= wxStrstr (dest
, val
)) != NULL
)
625 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
628 wxStrcpy (tcp
, WXSTRINGCAST envname
);
629 wxStrcat (tcp
, wxT("}"));
630 wxStrcat (tcp
, wxFileFunctionsBuffer
);
633 // Handle User's home (ignore root homes!)
635 if ((val
= wxGetUserHome (user
)) != NULL
&&
636 (len
= wxStrlen(val
)) > 2 &&
637 wxStrncmp(dest
, val
, len
) == 0)
639 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
641 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
643 // strcat(wxFileFunctionsBuffer, "\\");
645 // strcat(wxFileFunctionsBuffer, "/");
647 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
648 wxStrcpy (dest
, wxFileFunctionsBuffer
);
654 // Return just the filename, not the path
656 wxChar
*wxFileNameFromPath (wxChar
*path
)
660 register wxChar
*tcp
;
662 tcp
= path
+ wxStrlen (path
);
663 while (--tcp
>= path
)
666 if (*tcp
== wxT(':') )
668 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
670 || *tcp
== wxT(':') || *tcp
== wxT(']'))
677 #if defined(__WXMSW__) || defined(__WXPM__)
678 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
685 wxString
wxFileNameFromPath (const wxString
& path1
)
687 if (path1
!= wxT(""))
690 wxChar
*path
= WXSTRINGCAST path1
;
691 register wxChar
*tcp
;
693 tcp
= path
+ wxStrlen (path
);
694 while (--tcp
>= path
)
697 if (*tcp
== wxT(':') )
699 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
701 || *tcp
== wxT(':') || *tcp
== wxT(']'))
706 return wxString(tcp
+ 1);
708 #if defined(__WXMSW__) || defined(__WXPM__)
709 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
710 return wxString(path
+ 2);
713 // Yes, this should return the path, not an empty string, otherwise
714 // we get "thing.txt" -> "".
718 // Return just the directory, or NULL if no directory
720 wxPathOnly (wxChar
*path
)
724 static wxChar buf
[_MAXPATHLEN
];
727 wxStrcpy (buf
, path
);
729 int l
= wxStrlen(path
);
734 // Search backward for a backward or forward slash
735 while (!done
&& i
> -1)
739 if (path
[i
] == wxT(':') )
741 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
746 if ( path
[i
] == wxT(']') )
757 #if defined(__WXMSW__) || defined(__WXPM__)
758 // Try Drive specifier
759 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
761 // A:junk --> A:. (since A:.\junk Not A:\junk)
769 return (wxChar
*) NULL
;
772 // Return just the directory, or NULL if no directory
773 wxString
wxPathOnly (const wxString
& path
)
777 wxChar buf
[_MAXPATHLEN
];
780 wxStrcpy (buf
, WXSTRINGCAST path
);
782 int l
= path
.Length();
787 // Search backward for a backward or forward slash
788 while (!done
&& i
> -1)
792 if (path
[i
] == wxT(':') )
794 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
799 if ( path
[i
] == wxT(']') )
805 return wxString(buf
);
810 #if defined(__WXMSW__) || defined(__WXPM__)
811 // Try Drive specifier
812 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
814 // A:junk --> A:. (since A:.\junk Not A:\junk)
817 return wxString(buf
);
822 return wxString(wxT(""));
825 // Utility for converting delimiters in DOS filenames to UNIX style
826 // and back again - or we get nasty problems with delimiters.
827 // Also, convert to lower case, since case is significant in UNIX.
829 #if defined(__WXMAC__) && !defined(__UNIX__)
830 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
835 FSpGetFullPath( spec
, &length
, &myPath
) ;
836 ::SetHandleSize( myPath
, length
+ 1 ) ;
838 (*myPath
)[length
] = 0 ;
839 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
840 (*myPath
)[length
-1] = 0 ;
842 wxString
result( (char*) *myPath
) ;
843 ::HUnlock( myPath
) ;
844 ::DisposeHandle( myPath
) ;
848 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
850 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
853 static char sMacFileNameConversion
[ 1000 ] ;
855 wxString
wxMac2UnixFilename (const char *str
)
857 char *s
= sMacFileNameConversion
;
861 memmove( s
+1 , s
,strlen( s
) + 1) ;
872 *s
= wxTolower (*s
); // Case INDEPENDENT
876 return wxString (sMacFileNameConversion
) ;
879 wxString
wxUnix2MacFilename (const char *str
)
881 char *s
= sMacFileNameConversion
;
887 // relative path , since it goes on with slash which is translated to a :
888 memmove( s
, s
+1 ,strlen( s
) ) ;
890 else if ( *s
== '/' )
892 // absolute path -> on mac just start with the drive name
893 memmove( s
, s
+1 ,strlen( s
) ) ;
897 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
901 if (*s
== '/' || *s
== '\\')
903 // convert any back-directory situations
904 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
907 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
916 return wxString (sMacFileNameConversion
) ;
919 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
921 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
924 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
926 wxString var
= wxUnix2MacFilename( path
) ;
927 wxMacFilename2FSSpec( var
, spec
) ;
932 wxDos2UnixFilename (char *s
)
941 *s
= wxTolower (*s
); // Case INDEPENDENT
948 #if defined(__WXMSW__) || defined(__WXPM__)
949 wxUnix2DosFilename (wxChar
*s
)
951 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
954 // Yes, I really mean this to happen under DOS only! JACS
955 #if defined(__WXMSW__) || defined(__WXPM__)
966 // Concatenate two files to form third
968 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
971 if ( !wxGetTempFileName("cat", outfile
) )
974 FILE *fp1
= (FILE *) NULL
;
975 FILE *fp2
= (FILE *) NULL
;
976 FILE *fp3
= (FILE *) NULL
;
977 // Open the inputs and outputs
978 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
979 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
980 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
992 while ((ch
= getc (fp1
)) != EOF
)
993 (void) putc (ch
, fp3
);
996 while ((ch
= getc (fp2
)) != EOF
)
997 (void) putc (ch
, fp3
);
1001 bool result
= wxRenameFile(outfile
, file3
);
1007 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1009 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1010 // CopyFile() copies file attributes and modification time too, so use it
1011 // instead of our code if available
1013 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1014 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1018 // get permissions of file1
1019 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1021 // the file probably doesn't exist or we haven't the rights to read
1023 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1028 // open file1 for reading
1029 wxFile
fileIn(file1
, wxFile::read
);
1030 if ( !fileIn
.IsOpened() )
1033 // remove file2, if it exists. This is needed for creating
1034 // file2 with the correct permissions in the next step
1035 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1037 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1043 // reset the umask as we want to create the file with exactly the same
1044 // permissions as the original one
1045 mode_t oldUmask
= umask( 0 );
1048 // create file2 with the same permissions than file1 and open it for
1051 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1055 /// restore the old umask
1059 // copy contents of file1 to file2
1064 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1065 if ( fileIn
.Error() )
1072 if ( fileOut
.Write(buf
, count
) < count
)
1076 // we can expect fileIn to be closed successfully, but we should ensure
1077 // that fileOut was closed as some write errors (disk full) might not be
1078 // detected before doing this
1079 if ( !fileIn
.Close() || !fileOut
.Close() )
1082 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1083 // no chmod in VA. Should be some permission API for HPFS386 partitions
1085 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1087 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1091 #endif // OS/2 || Mac
1094 #endif // __WXMSW__ && __WIN32__
1098 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1100 // Normal system call
1101 if ( wxRename (file1
, file2
) == 0 )
1105 if (wxCopyFile(file1
, file2
)) {
1106 wxRemoveFile(file1
);
1113 bool wxRemoveFile(const wxString
& file
)
1115 #if defined(__VISUALC__) \
1116 || defined(__BORLANDC__) \
1117 || defined(__WATCOMC__) \
1118 || defined(__GNUWIN32__)
1119 int res
= wxRemove(file
);
1121 int res
= unlink(OS_FILENAME(file
));
1127 bool wxMkdir(const wxString
& dir
, int perm
)
1129 #if defined(__WXMAC__) && !defined(__UNIX__)
1130 return (mkdir( dir
, 0 ) == 0);
1132 const wxChar
*dirname
= dir
.c_str();
1134 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1135 // for the GNU compiler
1136 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1137 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1138 #elif defined(__WXPM__)
1139 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1140 #else // !MSW and !OS/2 VAC++
1142 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1145 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1154 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1157 return FALSE
; //to be changed since rmdir exists in VMS7.x
1158 #elif defined(__WXPM__)
1159 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1163 return FALSE
; // What to do?
1165 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1171 // does the path exists? (may have or not '/' or '\\' at the end)
1172 bool wxPathExists(const wxChar
*pszPathName
)
1174 wxString
strPath(pszPathName
);
1176 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1177 // so remove all trailing backslashes from the path - but don't do this for
1178 // the pathes "d:\" (which are different from "d:") nor for just "\"
1179 while ( wxEndsWithPathSeparator(strPath
) )
1181 size_t len
= strPath
.length();
1182 if ( len
== 1 || strPath
[len
- 1] == _T(':') )
1185 strPath
.Truncate(len
- 1);
1187 #endif // __WINDOWS__
1190 #ifndef __VISAGECPP__
1191 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1192 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1194 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1195 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1196 (st
.st_mode
== S_IFDIR
);
1201 // Get a temporary filename, opening and closing the file.
1202 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1204 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1208 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1210 wxChar tmp
[MAX_PATH
];
1211 wxChar tmpPath
[MAX_PATH
];
1212 ::GetTempPath(MAX_PATH
, tmpPath
);
1213 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1215 if (buf
) wxStrcpy(buf
, tmp
);
1216 else buf
= copystring(tmp
);
1220 static short last_temp
= 0; // cache last to speed things a bit
1221 // At most 1000 temp files to a process! We use a ring count.
1222 wxChar tmp
[100]; // FIXME static buffer
1224 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1226 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1227 if (!wxFileExists( tmp
))
1229 // Touch the file to create it (reserve name)
1230 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1235 wxStrcpy( buf
, tmp
);
1237 buf
= copystring( tmp
);
1241 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1242 if (buf
) buf
[0] = 0;
1243 return (wxChar
*) NULL
;
1247 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1250 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1259 // Get first file name matching given wild card.
1263 // Get first file name matching given wild card.
1264 // Flags are reserved for future use.
1266 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1267 static DIR *gs_dirStream
= (DIR *) NULL
;
1268 static wxString gs_strFileSpec
;
1269 static int gs_findFlags
= 0;
1272 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1276 wxChar
*specvms
= NULL
;
1279 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1281 closedir(gs_dirStream
); // edz 941103: better housekeping
1283 gs_findFlags
= flags
;
1285 gs_strFileSpec
= spec
;
1287 // Find path only so we can concatenate
1288 // found file onto path
1289 wxString
path(wxPathOnly(gs_strFileSpec
));
1291 // special case: path is really "/"
1292 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1295 wxStrcpy( specvms
, wxT( "[000000]" ) );
1296 gs_strFileSpec
= specvms
;
1297 wxString
path_vms(wxPathOnly(gs_strFileSpec
));
1303 // path is empty => Local directory
1307 wxStrcpy( specvms
, wxT( "[]" ) );
1308 gs_strFileSpec
= specvms
;
1309 wxString
path_vms1(wxPathOnly(gs_strFileSpec
));
1316 gs_dirStream
= opendir(path
.fn_str());
1317 if ( !gs_dirStream
)
1319 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1324 result
= wxFindNextFile();
1326 #endif // !VMS6.x or earlier
1331 wxString
wxFindNextFile()
1335 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1336 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1338 // Find path only so we can concatenate
1339 // found file onto path
1340 wxString
path(wxPathOnly(gs_strFileSpec
));
1341 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1343 /* MATTHEW: special case: path is really "/" */
1344 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1348 struct dirent
*nextDir
;
1349 for ( nextDir
= readdir(gs_dirStream
);
1351 nextDir
= readdir(gs_dirStream
) )
1353 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1354 strcmp(nextDir
->d_name
, ".") &&
1355 strcmp(nextDir
->d_name
, "..") )
1358 if ( !path
.IsEmpty() )
1361 if ( path
!= wxT('/') )
1365 result
+= nextDir
->d_name
;
1367 // Only return "." and ".." when they match
1369 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1370 (strcmp(nextDir
->d_name
, "..") == 0))
1372 if ( (gs_findFlags
& wxDIR
) != 0 )
1378 isdir
= wxDirExists(result
);
1380 // and only return directories when flags & wxDIR
1381 if ( !gs_findFlags
||
1382 ((gs_findFlags
& wxDIR
) && isdir
) ||
1383 ((gs_findFlags
& wxFILE
) && !isdir
) )
1390 result
.Empty(); // not found
1392 closedir(gs_dirStream
);
1393 gs_dirStream
= (DIR *) NULL
;
1394 #endif // !VMS6.2 or earlier
1399 #elif defined(__WXMAC__)
1401 struct MacDirectoryIterator
1409 static int g_iter_flags
;
1411 static MacDirectoryIterator g_iter
;
1413 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1417 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1419 // Find path only so we can concatenate found file onto path
1420 wxString
path(wxPathOnly(spec
));
1421 if ( !path
.IsEmpty() )
1422 result
<< path
<< wxT('\\');
1426 wxMacFilename2FSSpec( result
, &fsspec
) ;
1427 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1428 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1429 g_iter
.m_index
= 0 ;
1432 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1434 return wxEmptyString
;
1436 return wxFindNextFile( ) ;
1439 wxString
wxFindNextFile()
1445 while ( err
== noErr
)
1448 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1449 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1450 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1454 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1457 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1465 return wxEmptyString
;
1469 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1474 return wxMacFSSpec2MacFilename( &spec
) ;
1477 #elif defined(__WXMSW__)
1480 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1481 static WIN32_FIND_DATA gs_findDataStruct
;
1484 static struct ffblk gs_findDataStruct
;
1486 static struct _find_t gs_findDataStruct
;
1490 static wxString gs_strFileSpec
;
1491 static int gs_findFlags
= 0;
1493 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1497 gs_strFileSpec
= spec
;
1498 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1500 // Find path only so we can concatenate found file onto path
1501 wxString
path(wxPathOnly(gs_strFileSpec
));
1502 if ( !path
.IsEmpty() )
1503 result
<< path
<< wxT('\\');
1506 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1507 FindClose(gs_hFileStruct
);
1509 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1511 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1518 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1520 if (isdir
&& !(flags
& wxDIR
))
1521 return wxFindNextFile();
1522 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1523 return wxFindNextFile();
1525 result
+= gs_findDataStruct
.cFileName
;
1529 int flag
= _A_NORMAL
;
1534 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1536 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1542 attrib
= gs_findDataStruct
.ff_attrib
;
1544 attrib
= gs_findDataStruct
.attrib
;
1547 if (attrib
& _A_SUBDIR
) {
1548 if (!(gs_findFlags
& wxDIR
))
1549 return wxFindNextFile();
1550 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1551 return wxFindNextFile();
1555 gs_findDataStruct
.ff_name
1557 gs_findDataStruct
.name
1567 wxString
wxFindNextFile()
1571 // Find path only so we can concatenate found file onto path
1572 wxString
path(wxPathOnly(gs_strFileSpec
));
1577 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1580 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1583 FindClose(gs_hFileStruct
);
1584 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1588 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1590 if (isdir
&& !(gs_findFlags
& wxDIR
))
1592 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1595 if ( !path
.IsEmpty() )
1596 result
<< path
<< wxT('\\');
1597 result
<< gs_findDataStruct
.cFileName
;
1604 if (findnext(&gs_findDataStruct
) == 0)
1606 if (_dos_findnext(&gs_findDataStruct
) == 0)
1609 /* MATTHEW: [5] Check directory flag */
1613 attrib
= gs_findDataStruct
.ff_attrib
;
1615 attrib
= gs_findDataStruct
.attrib
;
1618 if (attrib
& _A_SUBDIR
) {
1619 if (!(gs_findFlags
& wxDIR
))
1621 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1627 gs_findDataStruct
.ff_name
1629 gs_findDataStruct
.name
1638 #elif defined(__WXPM__)
1640 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1645 // TODO: figure something out here for OS/2
1646 gs_strFileSpec = spec;
1647 gs_findFlags = flags;
1649 // Find path only so we can concatenate found file onto path
1650 wxString path(wxPathOnly(gs_strFileSpec));
1651 if ( !path.IsEmpty() )
1652 result << path << wxT('\\');
1654 int flag = _A_NORMAL;
1658 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1661 attrib = gs_findDataStruct.attrib;
1663 if (attrib & _A_SUBDIR) {
1664 if (!(gs_findFlags & wxDIR))
1665 return wxFindNextFile();
1666 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1667 return wxFindNextFile();
1669 result += gs_findDataStruct.name;
1675 wxString
wxFindNextFile()
1682 #endif // Unix/Windows/OS/2
1684 // Get current working directory.
1685 // If buf is NULL, allocates space using new, else
1687 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1690 buf
= new wxChar
[sz
+1];
1692 char *cbuf
= new char[sz
+1];
1694 if (_getcwd(cbuf
, sz
) == NULL
) {
1695 #elif defined(__WXMAC__) && !defined(__UNIX__)
1698 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1702 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1703 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1704 strcpy( buf
, res
) ;
1707 if (getcwd(cbuf
, sz
) == NULL
) {
1712 if (_getcwd(buf
, sz
) == NULL
) {
1713 #elif defined(__WXMAC__) && !defined(__UNIX__)
1718 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1720 pb
.ioRefNum
= LMGetCurApRefNum();
1722 error
= PBGetFCBInfoSync(&pb
);
1723 if ( error
== noErr
)
1725 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1726 cwdSpec
.parID
= pb
.ioFCBParID
;
1727 cwdSpec
.name
[0] = 0 ;
1728 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1730 strcpy( buf
, res
) ;
1731 buf
[res
.length()-1]=0 ;
1736 this version will not always give back the application directory on mac
1739 SFSaveDisk = 0x214, CurDirStore = 0x398
1743 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1744 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1745 strcpy( buf , res ) ;
1748 #elif(__VISAGECPP__)
1750 rc
= ::DosQueryCurrentDir( 0 // current drive
1756 if (getcwd(buf
, sz
) == NULL
) {
1764 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1773 static const size_t maxPathLen
= 1024;
1776 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1777 str
.UngetWriteBuf();
1782 bool wxSetWorkingDirectory(const wxString
& d
)
1784 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1785 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1786 #elif defined(__WXPM__)
1787 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1788 #elif defined(__WINDOWS__)
1791 return (bool)(SetCurrentDirectory(d
) != 0);
1793 // Must change drive, too.
1794 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1797 wxChar firstChar
= d
[0];
1801 firstChar
= firstChar
- 32;
1803 // To a drive number
1804 unsigned int driveNo
= firstChar
- 64;
1807 unsigned int noDrives
;
1808 _dos_setdrive(driveNo
, &noDrives
);
1811 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1819 // Get the OS directory if appropriate (such as the Windows directory).
1820 // On non-Windows platform, probably just return the empty string.
1821 wxString
wxGetOSDirectory()
1823 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1825 GetWindowsDirectory(buf
, 256);
1826 return wxString(buf
);
1828 return wxEmptyString
;
1832 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1834 size_t len
= wxStrlen(pszFileName
);
1838 return wxIsPathSeparator(pszFileName
[len
- 1]);
1841 // find a file in a list of directories, returns false if not found
1842 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1844 // we assume that it's not empty
1845 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1846 _T("empty file name in wxFindFileInPath"));
1848 // skip path separator in the beginning of the file name if present
1849 if ( wxIsPathSeparator(*pszFile
) )
1852 // copy the path (strtok will modify it)
1853 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1854 wxStrcpy(szPath
, pszPath
);
1857 wxChar
*pc
, *save_ptr
;
1858 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1860 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1862 // search for the file in this directory
1864 if ( !wxEndsWithPathSeparator(pc
) )
1865 strFile
+= wxFILE_SEP_PATH
;
1868 if ( FileExists(strFile
) ) {
1874 // suppress warning about unused variable save_ptr when wxStrtok() is a
1875 // macro which throws away its third argument
1880 return pc
!= NULL
; // if true => we breaked from the loop
1883 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1888 // it can be empty, but it shouldn't be NULL
1889 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1891 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1894 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1898 wxStat(filename
.fn_str(), &buf
);
1899 return buf
.st_mtime
;
1903 //------------------------------------------------------------------------
1904 // wild character routines
1905 //------------------------------------------------------------------------
1907 bool wxIsWild( const wxString
& pattern
)
1909 wxString tmp
= pattern
;
1910 wxChar
*pat
= WXSTRINGCAST(tmp
);
1913 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1923 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1925 #if defined(HAVE_FNMATCH_H)
1927 // this probably won't work well for multibyte chars in Unicode mode?
1929 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1931 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1935 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1938 * WARNING: this code is broken!
1941 wxString tmp1
= pat
;
1942 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1943 wxString tmp2
= text
;
1944 wxChar
*str
= WXSTRINGCAST(tmp2
);
1947 bool done
= FALSE
, ret_code
, ok
;
1948 // Below is for vi fans
1949 const wxChar OB
= wxT('{'), CB
= wxT('}');
1951 // dot_special means '.' only matches '.'
1952 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1955 while ((*pattern
!= wxT('\0')) && (!done
)
1956 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1960 if (*pattern
!= wxT('\0'))
1966 while ((*str
!=wxT('\0'))
1967 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1970 while (*str
!= wxT('\0'))
1972 while (*pattern
!= wxT('\0'))
1979 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1983 if (*pattern
== wxT('\\')) {
1985 if (*pattern
== wxT('\0')) {
1990 if (*(pattern
+ 1) == wxT('-')) {
1993 if (*pattern
== wxT(']')) {
1997 if (*pattern
== wxT('\\')) {
1999 if (*pattern
== wxT('\0')) {
2004 if ((*str
< c
) || (*str
> *pattern
)) {
2008 } else if (*pattern
!= *str
) {
2013 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
2014 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
2018 if (*pattern
!= wxT('\0')) {
2028 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2031 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
2032 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
2033 if (*pattern
== wxT('\\'))
2035 ok
= (*pattern
++ == *cp
++);
2037 if (*pattern
== wxT('\0')) {
2043 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2044 if (*++pattern
== wxT('\\')) {
2045 if (*++pattern
== CB
)
2050 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2051 if (*++pattern
== wxT('\\')) {
2052 if (*++pattern
== CB
|| *pattern
== wxT(','))
2057 if (*pattern
!= wxT('\0'))
2062 if (*str
== *pattern
) {
2069 while (*pattern
== wxT('*'))
2071 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2077 #pragma warning(default:4706) // assignment within conditional expression