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 if( filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':' )
297 if (filename
!= wxT(""))
299 if (filename
[0] == wxT('/')
301 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
305 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
315 * Strip off any extension (dot something) from end of file,
316 * IF one exists. Inserts zero into buffer.
320 void wxStripExtension(wxChar
*buffer
)
322 int len
= wxStrlen(buffer
);
326 if (buffer
[i
] == wxT('.'))
335 void wxStripExtension(wxString
& buffer
)
337 size_t len
= buffer
.Length();
341 if (buffer
.GetChar(i
) == wxT('.'))
343 buffer
= buffer
.Left(i
);
350 // Destructive removal of /./ and /../ stuff
351 wxChar
*wxRealPath (wxChar
*path
)
354 static const wxChar SEP
= wxT('\\');
355 Unix2DosFilename(path
);
357 static const wxChar SEP
= wxT('/');
359 if (path
[0] && path
[1]) {
360 /* MATTHEW: special case "/./x" */
362 if (path
[2] == SEP
&& path
[1] == wxT('.'))
370 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
373 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
374 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
375 && (q
- 1 <= path
|| q
[-1] != SEP
))
378 if (path
[0] == wxT('\0'))
384 /* Check that path[2] is NULL! */
385 else if (path
[1] == wxT(':') && !path
[2])
394 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
403 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
405 if (filename
== wxT(""))
406 return (wxChar
*) NULL
;
408 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
409 wxChar buf
[_MAXPATHLEN
];
411 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
412 wxChar ch
= buf
[wxStrlen(buf
) - 1];
414 if (ch
!= wxT('\\') && ch
!= wxT('/'))
415 wxStrcat(buf
, wxT("\\"));
418 wxStrcat(buf
, wxT("/"));
420 wxStrcat(buf
, wxFileFunctionsBuffer
);
421 return copystring( wxRealPath(buf
) );
423 return copystring( wxFileFunctionsBuffer
);
429 ~user/ => user's home dir
430 If the environment variable a = "foo" and b = "bar" then:
447 /* input name in name, pathname output to buf. */
449 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
451 register wxChar
*d
, *s
, *nm
;
452 wxChar lnm
[_MAXPATHLEN
];
455 // Some compilers don't like this line.
456 // const wxChar trimchars[] = wxT("\n \t");
459 trimchars
[0] = wxT('\n');
460 trimchars
[1] = wxT(' ');
461 trimchars
[2] = wxT('\t');
465 const wxChar SEP
= wxT('\\');
467 const wxChar SEP
= wxT('/');
470 if (name
== NULL
|| *name
== wxT('\0'))
472 nm
= copystring(name
); // Make a scratch copy
475 /* Skip leading whitespace and cr */
476 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
478 /* And strip off trailing whitespace and cr */
479 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
480 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
488 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
491 /* Expand inline environment variables */
509 while ((*d
++ = *s
) != 0) {
511 if (*s
== wxT('\\')) {
512 if ((*(d
- 1) = *++s
)) {
521 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
523 if (*s
++ == wxT('$'))
526 register wxChar
*start
= d
;
527 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
528 register wxChar
*value
;
529 while ((*d
++ = *s
) != 0)
530 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
535 value
= wxGetenv(braces
? start
+ 1 : start
);
537 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
545 /* Expand ~ and ~user */
548 if (nm
[0] == wxT('~') && !q
)
551 if (nm
[1] == SEP
|| nm
[1] == 0)
553 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
554 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
559 { /* ~user/filename */
560 register wxChar
*nnm
;
561 register wxChar
*home
;
562 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
563 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
564 was_sep
= (*s
== SEP
);
565 nnm
= *s
? s
+ 1 : s
;
567 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
568 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
569 if (was_sep
) /* replace only if it was there: */
580 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
582 while (wxT('\0') != (*d
++ = *s
++))
585 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
589 while ((*d
++ = *s
++) != 0);
590 delete[] nm_tmp
; // clean up alloc
591 /* Now clean up the buffer */
592 return wxRealPath(buf
);
595 /* Contract Paths to be build upon an environment variable
598 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
600 The call wxExpandPath can convert these back!
603 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
605 static wxChar dest
[_MAXPATHLEN
];
607 if (filename
== wxT(""))
608 return (wxChar
*) NULL
;
610 wxStrcpy (dest
, WXSTRINGCAST filename
);
612 Unix2DosFilename(dest
);
615 // Handle environment
616 const wxChar
*val
= (const wxChar
*) NULL
;
617 wxChar
*tcp
= (wxChar
*) NULL
;
618 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
619 (tcp
= wxStrstr (dest
, val
)) != NULL
)
621 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
624 wxStrcpy (tcp
, WXSTRINGCAST envname
);
625 wxStrcat (tcp
, wxT("}"));
626 wxStrcat (tcp
, wxFileFunctionsBuffer
);
629 // Handle User's home (ignore root homes!)
631 if ((val
= wxGetUserHome (user
)) != NULL
&&
632 (len
= wxStrlen(val
)) > 2 &&
633 wxStrncmp(dest
, val
, len
) == 0)
635 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
637 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
639 // strcat(wxFileFunctionsBuffer, "\\");
641 // strcat(wxFileFunctionsBuffer, "/");
643 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
644 wxStrcpy (dest
, wxFileFunctionsBuffer
);
650 // Return just the filename, not the path
652 wxChar
*wxFileNameFromPath (wxChar
*path
)
656 register wxChar
*tcp
;
658 tcp
= path
+ wxStrlen (path
);
659 while (--tcp
>= path
)
662 if (*tcp
== wxT(':') )
664 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
666 || *tcp
== wxT(':') || *tcp
== wxT(']'))
673 #if defined(__WXMSW__) || defined(__WXPM__)
674 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
681 wxString
wxFileNameFromPath (const wxString
& path1
)
683 if (path1
!= wxT(""))
686 wxChar
*path
= WXSTRINGCAST path1
;
687 register wxChar
*tcp
;
689 tcp
= path
+ wxStrlen (path
);
690 while (--tcp
>= path
)
693 if (*tcp
== wxT(':') )
695 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
697 || *tcp
== wxT(':') || *tcp
== wxT(']'))
702 return wxString(tcp
+ 1);
704 #if defined(__WXMSW__) || defined(__WXPM__)
705 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
706 return wxString(path
+ 2);
709 // Yes, this should return the path, not an empty string, otherwise
710 // we get "thing.txt" -> "".
714 // Return just the directory, or NULL if no directory
716 wxPathOnly (wxChar
*path
)
720 static wxChar buf
[_MAXPATHLEN
];
723 wxStrcpy (buf
, path
);
725 int l
= wxStrlen(path
);
730 // Search backward for a backward or forward slash
731 while (!done
&& i
> -1)
735 if (path
[i
] == wxT(':') )
737 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
742 if ( path
[i
] == wxT(']') )
753 #if defined(__WXMSW__) || defined(__WXPM__)
754 // Try Drive specifier
755 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
757 // A:junk --> A:. (since A:.\junk Not A:\junk)
765 return (wxChar
*) NULL
;
768 // Return just the directory, or NULL if no directory
769 wxString
wxPathOnly (const wxString
& path
)
773 wxChar buf
[_MAXPATHLEN
];
776 wxStrcpy (buf
, WXSTRINGCAST path
);
778 int l
= path
.Length();
783 // Search backward for a backward or forward slash
784 while (!done
&& i
> -1)
788 if (path
[i
] == wxT(':') )
790 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
795 if ( path
[i
] == wxT(']') )
801 return wxString(buf
);
806 #if defined(__WXMSW__) || defined(__WXPM__)
807 // Try Drive specifier
808 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
810 // A:junk --> A:. (since A:.\junk Not A:\junk)
813 return wxString(buf
);
818 return wxString(wxT(""));
821 // Utility for converting delimiters in DOS filenames to UNIX style
822 // and back again - or we get nasty problems with delimiters.
823 // Also, convert to lower case, since case is significant in UNIX.
825 #if defined(__WXMAC__) && !defined(__UNIX__)
826 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
831 FSpGetFullPath( spec
, &length
, &myPath
) ;
832 ::SetHandleSize( myPath
, length
+ 1 ) ;
834 (*myPath
)[length
] = 0 ;
835 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
836 (*myPath
)[length
-1] = 0 ;
838 wxString
result( (char*) *myPath
) ;
839 ::HUnlock( myPath
) ;
840 ::DisposeHandle( myPath
) ;
844 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
846 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
850 static char sMacFileNameConversion[ 1000 ] ;
852 wxString wxMac2UnixFilename (const char *str)
854 char *s = sMacFileNameConversion ;
858 memmove( s+1 , s ,strlen( s ) + 1) ;
869 *s = wxTolower (*s); // Case INDEPENDENT
873 return wxString (sMacFileNameConversion) ;
876 wxString wxUnix2MacFilename (const char *str)
878 char *s = sMacFileNameConversion ;
884 // relative path , since it goes on with slash which is translated to a :
885 memmove( s , s+1 ,strlen( s ) ) ;
887 else if ( *s == '/' )
889 // absolute path -> on mac just start with the drive name
890 memmove( s , s+1 ,strlen( s ) ) ;
894 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
898 if (*s == '/' || *s == '\\')
900 // convert any back-directory situations
901 if ( *(s+1) == '.' && *(s+2) == '.' && ( (*(s+3) == '/' || *(s+3) == '\\') ) )
904 memmove( s+1 , s+3 ,strlen( s+3 ) + 1 ) ;
913 return wxString (sMacFileNameConversion) ;
916 wxString wxMacFSSpec2UnixFilename( const FSSpec *spec )
918 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec) ) ;
921 void wxMacFilename2FSSpec( const char *path , FSSpec *spec )
923 FSpLocationFromFullPath( strlen(path ) , path , spec ) ;
926 void wxUnixFilename2FSSpec( const char *path , FSSpec *spec )
928 wxString var = wxUnix2MacFilename( path ) ;
929 wxMacFilename2FSSpec( var , spec ) ;
934 wxDos2UnixFilename (char *s
)
943 *s
= wxTolower (*s
); // Case INDEPENDENT
950 #if defined(__WXMSW__) || defined(__WXPM__)
951 wxUnix2DosFilename (wxChar
*s
)
953 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
956 // Yes, I really mean this to happen under DOS only! JACS
957 #if defined(__WXMSW__) || defined(__WXPM__)
968 // Concatenate two files to form third
970 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
973 if ( !wxGetTempFileName("cat", outfile
) )
976 FILE *fp1
= (FILE *) NULL
;
977 FILE *fp2
= (FILE *) NULL
;
978 FILE *fp3
= (FILE *) NULL
;
979 // Open the inputs and outputs
980 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
981 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
982 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
994 while ((ch
= getc (fp1
)) != EOF
)
995 (void) putc (ch
, fp3
);
998 while ((ch
= getc (fp2
)) != EOF
)
999 (void) putc (ch
, fp3
);
1003 bool result
= wxRenameFile(outfile
, file3
);
1009 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1011 #if defined(__WIN32__)
1012 // CopyFile() copies file attributes and modification time too, so use it
1013 // instead of our code if available
1015 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1016 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1020 // get permissions of file1
1021 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1023 // the file probably doesn't exist or we haven't the rights to read
1025 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1030 // open file1 for reading
1031 wxFile
fileIn(file1
, wxFile::read
);
1032 if ( !fileIn
.IsOpened() )
1035 // remove file2, if it exists. This is needed for creating
1036 // file2 with the correct permissions in the next step
1037 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1039 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1045 // reset the umask as we want to create the file with exactly the same
1046 // permissions as the original one
1047 mode_t oldUmask
= umask( 0 );
1050 // create file2 with the same permissions than file1 and open it for
1053 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1057 /// restore the old umask
1061 // copy contents of file1 to file2
1066 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1067 if ( fileIn
.Error() )
1074 if ( fileOut
.Write(buf
, count
) < count
)
1078 // we can expect fileIn to be closed successfully, but we should ensure
1079 // that fileOut was closed as some write errors (disk full) might not be
1080 // detected before doing this
1081 if ( !fileIn
.Close() || !fileOut
.Close() )
1084 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1085 // no chmod in VA. Should be some permission API for HPFS386 partitions
1087 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1089 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1093 #endif // OS/2 || Mac
1096 #endif // __WXMSW__ && __WIN32__
1100 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1102 // Normal system call
1103 if ( wxRename (file1
, file2
) == 0 )
1107 if (wxCopyFile(file1
, file2
)) {
1108 wxRemoveFile(file1
);
1115 bool wxRemoveFile(const wxString
& file
)
1117 #if defined(__VISUALC__) \
1118 || defined(__BORLANDC__) \
1119 || defined(__WATCOMC__) \
1120 || defined(__GNUWIN32__)
1121 int res
= wxRemove(file
);
1123 int res
= unlink(OS_FILENAME(file
));
1129 bool wxMkdir(const wxString
& dir
, int perm
)
1131 #if defined(__WXMAC__) && !defined(__UNIX__)
1132 return (mkdir( dir
, 0 ) == 0);
1134 const wxChar
*dirname
= dir
.c_str();
1136 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1137 // for the GNU compiler
1138 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1139 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1140 #elif defined(__WXPM__)
1141 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1142 #else // !MSW and !OS/2 VAC++
1144 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1147 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1156 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1159 return FALSE
; //to be changed since rmdir exists in VMS7.x
1160 #elif defined(__WXPM__)
1161 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1165 return FALSE
; // What to do?
1167 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1173 // does the path exists? (may have or not '/' or '\\' at the end)
1174 bool wxPathExists(const wxChar
*pszPathName
)
1176 wxString
strPath(pszPathName
);
1178 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1179 // so remove all trailing backslashes from the path - but don't do this for
1180 // the pathes "d:\" (which are different from "d:") nor for just "\"
1181 while ( wxEndsWithPathSeparator(strPath
) )
1183 size_t len
= strPath
.length();
1184 if ( len
== 1 || strPath
[len
- 1] == _T(':') )
1187 strPath
.Truncate(len
- 1);
1189 #endif // __WINDOWS__
1192 #ifndef __VISAGECPP__
1193 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1194 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1196 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1197 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1198 (st
.st_mode
== S_IFDIR
);
1203 // Get a temporary filename, opening and closing the file.
1204 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1210 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1212 wxChar tmp
[MAX_PATH
];
1213 wxChar tmpPath
[MAX_PATH
];
1214 ::GetTempPath(MAX_PATH
, tmpPath
);
1215 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1217 if (buf
) wxStrcpy(buf
, tmp
);
1218 else buf
= copystring(tmp
);
1222 static short last_temp
= 0; // cache last to speed things a bit
1223 // At most 1000 temp files to a process! We use a ring count.
1224 wxChar tmp
[100]; // FIXME static buffer
1226 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1228 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1229 if (!wxFileExists( tmp
))
1231 // Touch the file to create it (reserve name)
1232 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1237 wxStrcpy( buf
, tmp
);
1239 buf
= copystring( tmp
);
1243 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1244 if (buf
) buf
[0] = 0;
1245 return (wxChar
*) NULL
;
1249 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1252 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1261 // Get first file name matching given wild card.
1265 // Get first file name matching given wild card.
1266 // Flags are reserved for future use.
1268 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1269 static DIR *gs_dirStream
= (DIR *) NULL
;
1270 static wxString gs_strFileSpec
;
1271 static int gs_findFlags
= 0;
1274 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1278 wxChar
*specvms
= NULL
;
1281 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1283 closedir(gs_dirStream
); // edz 941103: better housekeping
1285 gs_findFlags
= flags
;
1287 gs_strFileSpec
= spec
;
1289 // Find path only so we can concatenate
1290 // found file onto path
1291 wxString
path(wxPathOnly(gs_strFileSpec
));
1293 // special case: path is really "/"
1294 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1297 wxStrcpy( specvms
, wxT( "[000000]" ) );
1298 gs_strFileSpec
= specvms
;
1299 wxString
path_vms(wxPathOnly(gs_strFileSpec
));
1305 // path is empty => Local directory
1309 wxStrcpy( specvms
, wxT( "[]" ) );
1310 gs_strFileSpec
= specvms
;
1311 wxString
path_vms1(wxPathOnly(gs_strFileSpec
));
1318 gs_dirStream
= opendir(path
.fn_str());
1319 if ( !gs_dirStream
)
1321 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1326 result
= wxFindNextFile();
1328 #endif // !VMS6.x or earlier
1333 wxString
wxFindNextFile()
1337 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1338 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1340 // Find path only so we can concatenate
1341 // found file onto path
1342 wxString
path(wxPathOnly(gs_strFileSpec
));
1343 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1345 /* MATTHEW: special case: path is really "/" */
1346 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1350 struct dirent
*nextDir
;
1351 for ( nextDir
= readdir(gs_dirStream
);
1353 nextDir
= readdir(gs_dirStream
) )
1355 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1356 strcmp(nextDir
->d_name
, ".") &&
1357 strcmp(nextDir
->d_name
, "..") )
1360 if ( !path
.IsEmpty() )
1363 if ( path
!= wxT('/') )
1367 result
+= nextDir
->d_name
;
1369 // Only return "." and ".." when they match
1371 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1372 (strcmp(nextDir
->d_name
, "..") == 0))
1374 if ( (gs_findFlags
& wxDIR
) != 0 )
1380 isdir
= wxDirExists(result
);
1382 // and only return directories when flags & wxDIR
1383 if ( !gs_findFlags
||
1384 ((gs_findFlags
& wxDIR
) && isdir
) ||
1385 ((gs_findFlags
& wxFILE
) && !isdir
) )
1392 result
.Empty(); // not found
1394 closedir(gs_dirStream
);
1395 gs_dirStream
= (DIR *) NULL
;
1396 #endif // !VMS6.2 or earlier
1401 #elif defined(__WXMAC__)
1403 struct MacDirectoryIterator
1411 static int g_iter_flags
;
1413 static MacDirectoryIterator g_iter
;
1415 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1419 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1421 // Find path only so we can concatenate found file onto path
1422 wxString
path(wxPathOnly(spec
));
1423 if ( !path
.IsEmpty() )
1424 result
<< path
<< wxT('\\');
1428 wxMacFilename2FSSpec( result
, &fsspec
) ;
1429 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1430 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1431 g_iter
.m_index
= 0 ;
1434 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1436 return wxEmptyString
;
1438 return wxFindNextFile( ) ;
1441 wxString
wxFindNextFile()
1447 while ( err
== noErr
)
1450 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1451 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1452 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1456 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1459 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1467 return wxEmptyString
;
1471 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1476 return wxMacFSSpec2MacFilename( &spec
) ;
1479 #elif defined(__WXMSW__)
1482 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1483 static WIN32_FIND_DATA gs_findDataStruct
;
1486 static struct ffblk gs_findDataStruct
;
1488 static struct _find_t gs_findDataStruct
;
1492 static wxString gs_strFileSpec
;
1493 static int gs_findFlags
= 0;
1495 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1499 gs_strFileSpec
= spec
;
1500 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1502 // Find path only so we can concatenate found file onto path
1503 wxString
path(wxPathOnly(gs_strFileSpec
));
1504 if ( !path
.IsEmpty() )
1505 result
<< path
<< wxT('\\');
1508 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1509 FindClose(gs_hFileStruct
);
1511 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1513 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1520 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1522 if (isdir
&& !(flags
& wxDIR
))
1523 return wxFindNextFile();
1524 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1525 return wxFindNextFile();
1527 result
+= gs_findDataStruct
.cFileName
;
1531 int flag
= _A_NORMAL
;
1536 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1538 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1544 attrib
= gs_findDataStruct
.ff_attrib
;
1546 attrib
= gs_findDataStruct
.attrib
;
1549 if (attrib
& _A_SUBDIR
) {
1550 if (!(gs_findFlags
& wxDIR
))
1551 return wxFindNextFile();
1552 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1553 return wxFindNextFile();
1557 gs_findDataStruct
.ff_name
1559 gs_findDataStruct
.name
1569 wxString
wxFindNextFile()
1573 // Find path only so we can concatenate found file onto path
1574 wxString
path(wxPathOnly(gs_strFileSpec
));
1579 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1582 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1585 FindClose(gs_hFileStruct
);
1586 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1590 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1592 if (isdir
&& !(gs_findFlags
& wxDIR
))
1594 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1597 if ( !path
.IsEmpty() )
1598 result
<< path
<< wxT('\\');
1599 result
<< gs_findDataStruct
.cFileName
;
1606 if (findnext(&gs_findDataStruct
) == 0)
1608 if (_dos_findnext(&gs_findDataStruct
) == 0)
1611 /* MATTHEW: [5] Check directory flag */
1615 attrib
= gs_findDataStruct
.ff_attrib
;
1617 attrib
= gs_findDataStruct
.attrib
;
1620 if (attrib
& _A_SUBDIR
) {
1621 if (!(gs_findFlags
& wxDIR
))
1623 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1629 gs_findDataStruct
.ff_name
1631 gs_findDataStruct
.name
1640 #elif defined(__WXPM__)
1642 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1647 // TODO: figure something out here for OS/2
1648 gs_strFileSpec = spec;
1649 gs_findFlags = flags;
1651 // Find path only so we can concatenate found file onto path
1652 wxString path(wxPathOnly(gs_strFileSpec));
1653 if ( !path.IsEmpty() )
1654 result << path << wxT('\\');
1656 int flag = _A_NORMAL;
1660 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1663 attrib = gs_findDataStruct.attrib;
1665 if (attrib & _A_SUBDIR) {
1666 if (!(gs_findFlags & wxDIR))
1667 return wxFindNextFile();
1668 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1669 return wxFindNextFile();
1671 result += gs_findDataStruct.name;
1677 wxString
wxFindNextFile()
1684 #endif // Unix/Windows/OS/2
1686 // Get current working directory.
1687 // If buf is NULL, allocates space using new, else
1689 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1692 buf
= new wxChar
[sz
+1];
1694 char *cbuf
= new char[sz
+1];
1696 if (_getcwd(cbuf
, sz
) == NULL
) {
1697 #elif defined(__WXMAC__) && !defined(__UNIX__)
1700 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1704 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1705 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1706 strcpy( buf
, res
) ;
1709 if (getcwd(cbuf
, sz
) == NULL
) {
1714 if (_getcwd(buf
, sz
) == NULL
) {
1715 #elif defined(__WXMAC__) && !defined(__UNIX__)
1720 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1722 pb
.ioRefNum
= LMGetCurApRefNum();
1724 error
= PBGetFCBInfoSync(&pb
);
1725 if ( error
== noErr
)
1727 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1728 cwdSpec
.parID
= pb
.ioFCBParID
;
1729 cwdSpec
.name
[0] = 0 ;
1730 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1732 strcpy( buf
, res
) ;
1733 buf
[res
.length()-1]=0 ;
1738 this version will not always give back the application directory on mac
1741 SFSaveDisk = 0x214, CurDirStore = 0x398
1745 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1746 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1747 strcpy( buf , res ) ;
1750 #elif(__VISAGECPP__)
1752 rc
= ::DosQueryCurrentDir( 0 // current drive
1758 if (getcwd(buf
, sz
) == NULL
) {
1766 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1775 static const size_t maxPathLen
= 1024;
1778 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1779 str
.UngetWriteBuf();
1784 bool wxSetWorkingDirectory(const wxString
& d
)
1786 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1787 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1788 #elif defined(__WXPM__)
1789 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1790 #elif defined(__WINDOWS__)
1793 return (bool)(SetCurrentDirectory(d
) != 0);
1795 // Must change drive, too.
1796 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1799 wxChar firstChar
= d
[0];
1803 firstChar
= firstChar
- 32;
1805 // To a drive number
1806 unsigned int driveNo
= firstChar
- 64;
1809 unsigned int noDrives
;
1810 _dos_setdrive(driveNo
, &noDrives
);
1813 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1821 // Get the OS directory if appropriate (such as the Windows directory).
1822 // On non-Windows platform, probably just return the empty string.
1823 wxString
wxGetOSDirectory()
1827 GetWindowsDirectory(buf
, 256);
1828 return wxString(buf
);
1830 return wxEmptyString
;
1834 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1836 size_t len
= wxStrlen(pszFileName
);
1840 return wxIsPathSeparator(pszFileName
[len
- 1]);
1843 // find a file in a list of directories, returns false if not found
1844 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1846 // we assume that it's not empty
1847 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1848 _T("empty file name in wxFindFileInPath"));
1850 // skip path separator in the beginning of the file name if present
1851 if ( wxIsPathSeparator(*pszFile
) )
1854 // copy the path (strtok will modify it)
1855 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1856 wxStrcpy(szPath
, pszPath
);
1859 wxChar
*pc
, *save_ptr
;
1860 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1862 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1864 // search for the file in this directory
1866 if ( !wxEndsWithPathSeparator(pc
) )
1867 strFile
+= wxFILE_SEP_PATH
;
1870 if ( FileExists(strFile
) ) {
1876 // suppress warning about unused variable save_ptr when wxStrtok() is a
1877 // macro which throws away its third argument
1882 return pc
!= NULL
; // if true => we breaked from the loop
1885 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1890 // it can be empty, but it shouldn't be NULL
1891 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1893 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1896 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1900 wxStat(filename
.fn_str(), &buf
);
1901 return buf
.st_mtime
;
1905 //------------------------------------------------------------------------
1906 // wild character routines
1907 //------------------------------------------------------------------------
1909 bool wxIsWild( const wxString
& pattern
)
1911 wxString tmp
= pattern
;
1912 wxChar
*pat
= WXSTRINGCAST(tmp
);
1915 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1925 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1927 #if defined(HAVE_FNMATCH_H)
1929 // this probably won't work well for multibyte chars in Unicode mode?
1931 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1933 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1937 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1940 * WARNING: this code is broken!
1943 wxString tmp1
= pat
;
1944 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1945 wxString tmp2
= text
;
1946 wxChar
*str
= WXSTRINGCAST(tmp2
);
1949 bool done
= FALSE
, ret_code
, ok
;
1950 // Below is for vi fans
1951 const wxChar OB
= wxT('{'), CB
= wxT('}');
1953 // dot_special means '.' only matches '.'
1954 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1957 while ((*pattern
!= wxT('\0')) && (!done
)
1958 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1962 if (*pattern
!= wxT('\0'))
1968 while ((*str
!=wxT('\0'))
1969 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1972 while (*str
!= wxT('\0'))
1974 while (*pattern
!= wxT('\0'))
1981 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1985 if (*pattern
== wxT('\\')) {
1987 if (*pattern
== wxT('\0')) {
1992 if (*(pattern
+ 1) == wxT('-')) {
1995 if (*pattern
== wxT(']')) {
1999 if (*pattern
== wxT('\\')) {
2001 if (*pattern
== wxT('\0')) {
2006 if ((*str
< c
) || (*str
> *pattern
)) {
2010 } else if (*pattern
!= *str
) {
2015 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
2016 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
2020 if (*pattern
!= wxT('\0')) {
2030 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2033 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
2034 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
2035 if (*pattern
== wxT('\\'))
2037 ok
= (*pattern
++ == *cp
++);
2039 if (*pattern
== wxT('\0')) {
2045 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2046 if (*++pattern
== wxT('\\')) {
2047 if (*++pattern
== CB
)
2052 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2053 if (*++pattern
== wxT('\\')) {
2054 if (*++pattern
== CB
|| *pattern
== wxT(','))
2059 if (*pattern
!= wxT('\0'))
2064 if (*str
== *pattern
) {
2071 while (*pattern
== wxT('*'))
2073 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2079 #pragma warning(default:4706) // assignment within conditional expression