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
) ;
849 static char sMacFileNameConversion
[ 1000 ] ;
851 wxString
wxMac2UnixFilename (const char *str
)
853 char *s
= sMacFileNameConversion
;
857 memmove( s
+1 , s
,strlen( s
) + 1) ;
868 *s
= wxTolower (*s
); // Case INDEPENDENT
872 return wxString (sMacFileNameConversion
) ;
875 wxString
wxUnix2MacFilename (const char *str
)
877 char *s
= sMacFileNameConversion
;
883 // relative path , since it goes on with slash which is translated to a :
884 memmove( s
, s
+1 ,strlen( s
) ) ;
886 else if ( *s
== '/' )
888 // absolute path -> on mac just start with the drive name
889 memmove( s
, s
+1 ,strlen( s
) ) ;
893 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
897 if (*s
== '/' || *s
== '\\')
899 // convert any back-directory situations
900 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
903 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
912 return wxString (sMacFileNameConversion
) ;
915 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
917 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
920 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
922 wxString var
= wxUnix2MacFilename( path
) ;
923 wxMacFilename2FSSpec( var
, spec
) ;
928 wxDos2UnixFilename (char *s
)
937 *s
= wxTolower (*s
); // Case INDEPENDENT
944 #if defined(__WXMSW__) || defined(__WXPM__)
945 wxUnix2DosFilename (wxChar
*s
)
947 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
950 // Yes, I really mean this to happen under DOS only! JACS
951 #if defined(__WXMSW__) || defined(__WXPM__)
962 // Concatenate two files to form third
964 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
967 if ( !wxGetTempFileName("cat", outfile
) )
970 FILE *fp1
= (FILE *) NULL
;
971 FILE *fp2
= (FILE *) NULL
;
972 FILE *fp3
= (FILE *) NULL
;
973 // Open the inputs and outputs
974 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
975 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
976 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
988 while ((ch
= getc (fp1
)) != EOF
)
989 (void) putc (ch
, fp3
);
992 while ((ch
= getc (fp2
)) != EOF
)
993 (void) putc (ch
, fp3
);
997 bool result
= wxRenameFile(outfile
, file3
);
1003 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1005 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1006 // CopyFile() copies file attributes and modification time too, so use it
1007 // instead of our code if available
1009 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1010 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1014 // get permissions of file1
1015 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1017 // the file probably doesn't exist or we haven't the rights to read
1019 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1024 // open file1 for reading
1025 wxFile
fileIn(file1
, wxFile::read
);
1026 if ( !fileIn
.IsOpened() )
1029 // remove file2, if it exists. This is needed for creating
1030 // file2 with the correct permissions in the next step
1031 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1033 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1039 // reset the umask as we want to create the file with exactly the same
1040 // permissions as the original one
1041 mode_t oldUmask
= umask( 0 );
1044 // create file2 with the same permissions than file1 and open it for
1047 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1051 /// restore the old umask
1055 // copy contents of file1 to file2
1060 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1061 if ( fileIn
.Error() )
1068 if ( fileOut
.Write(buf
, count
) < count
)
1072 // we can expect fileIn to be closed successfully, but we should ensure
1073 // that fileOut was closed as some write errors (disk full) might not be
1074 // detected before doing this
1075 if ( !fileIn
.Close() || !fileOut
.Close() )
1078 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1079 // no chmod in VA. Should be some permission API for HPFS386 partitions
1081 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1083 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1087 #endif // OS/2 || Mac
1090 #endif // __WXMSW__ && __WIN32__
1094 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1096 // Normal system call
1097 if ( wxRename (file1
, file2
) == 0 )
1101 if (wxCopyFile(file1
, file2
)) {
1102 wxRemoveFile(file1
);
1109 bool wxRemoveFile(const wxString
& file
)
1111 #if defined(__VISUALC__) \
1112 || defined(__BORLANDC__) \
1113 || defined(__WATCOMC__) \
1114 || defined(__GNUWIN32__)
1115 int res
= wxRemove(file
);
1117 int res
= unlink(OS_FILENAME(file
));
1123 bool wxMkdir(const wxString
& dir
, int perm
)
1125 #if defined(__WXMAC__) && !defined(__UNIX__)
1126 return (mkdir( dir
, 0 ) == 0);
1128 const wxChar
*dirname
= dir
.c_str();
1130 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1131 // for the GNU compiler
1132 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
1133 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1134 #elif defined(__WXPM__)
1135 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1136 #else // !MSW and !OS/2 VAC++
1138 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1141 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1150 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1153 return FALSE
; //to be changed since rmdir exists in VMS7.x
1154 #elif defined(__WXPM__)
1155 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1159 return FALSE
; // What to do?
1161 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1167 // does the path exists? (may have or not '/' or '\\' at the end)
1168 bool wxPathExists(const wxChar
*pszPathName
)
1170 wxString
strPath(pszPathName
);
1172 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1173 // so remove all trailing backslashes from the path - but don't do this for
1174 // the pathes "d:\" (which are different from "d:") nor for just "\"
1175 while ( wxEndsWithPathSeparator(strPath
) )
1177 size_t len
= strPath
.length();
1178 if ( len
== 1 || strPath
[len
- 1] == _T(':') )
1181 strPath
.Truncate(len
- 1);
1183 #endif // __WINDOWS__
1186 #ifndef __VISAGECPP__
1187 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1188 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1190 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1191 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1192 (st
.st_mode
== S_IFDIR
);
1197 // Get a temporary filename, opening and closing the file.
1198 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1200 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1204 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1206 wxChar tmp
[MAX_PATH
];
1207 wxChar tmpPath
[MAX_PATH
];
1208 ::GetTempPath(MAX_PATH
, tmpPath
);
1209 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1211 if (buf
) wxStrcpy(buf
, tmp
);
1212 else buf
= copystring(tmp
);
1216 static short last_temp
= 0; // cache last to speed things a bit
1217 // At most 1000 temp files to a process! We use a ring count.
1218 wxChar tmp
[100]; // FIXME static buffer
1220 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1222 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1223 if (!wxFileExists( tmp
))
1225 // Touch the file to create it (reserve name)
1226 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1231 wxStrcpy( buf
, tmp
);
1233 buf
= copystring( tmp
);
1237 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1238 if (buf
) buf
[0] = 0;
1239 return (wxChar
*) NULL
;
1243 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1246 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1255 // Get first file name matching given wild card.
1259 // Get first file name matching given wild card.
1260 // Flags are reserved for future use.
1262 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1263 static DIR *gs_dirStream
= (DIR *) NULL
;
1264 static wxString gs_strFileSpec
;
1265 static int gs_findFlags
= 0;
1268 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1272 wxChar
*specvms
= NULL
;
1275 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1277 closedir(gs_dirStream
); // edz 941103: better housekeping
1279 gs_findFlags
= flags
;
1281 gs_strFileSpec
= spec
;
1283 // Find path only so we can concatenate
1284 // found file onto path
1285 wxString
path(wxPathOnly(gs_strFileSpec
));
1287 // special case: path is really "/"
1288 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1291 wxStrcpy( specvms
, wxT( "[000000]" ) );
1292 gs_strFileSpec
= specvms
;
1293 wxString
path_vms(wxPathOnly(gs_strFileSpec
));
1299 // path is empty => Local directory
1303 wxStrcpy( specvms
, wxT( "[]" ) );
1304 gs_strFileSpec
= specvms
;
1305 wxString
path_vms1(wxPathOnly(gs_strFileSpec
));
1312 gs_dirStream
= opendir(path
.fn_str());
1313 if ( !gs_dirStream
)
1315 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1320 result
= wxFindNextFile();
1322 #endif // !VMS6.x or earlier
1327 wxString
wxFindNextFile()
1331 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1332 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1334 // Find path only so we can concatenate
1335 // found file onto path
1336 wxString
path(wxPathOnly(gs_strFileSpec
));
1337 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1339 /* MATTHEW: special case: path is really "/" */
1340 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1344 struct dirent
*nextDir
;
1345 for ( nextDir
= readdir(gs_dirStream
);
1347 nextDir
= readdir(gs_dirStream
) )
1349 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1350 strcmp(nextDir
->d_name
, ".") &&
1351 strcmp(nextDir
->d_name
, "..") )
1354 if ( !path
.IsEmpty() )
1357 if ( path
!= wxT('/') )
1361 result
+= nextDir
->d_name
;
1363 // Only return "." and ".." when they match
1365 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1366 (strcmp(nextDir
->d_name
, "..") == 0))
1368 if ( (gs_findFlags
& wxDIR
) != 0 )
1374 isdir
= wxDirExists(result
);
1376 // and only return directories when flags & wxDIR
1377 if ( !gs_findFlags
||
1378 ((gs_findFlags
& wxDIR
) && isdir
) ||
1379 ((gs_findFlags
& wxFILE
) && !isdir
) )
1386 result
.Empty(); // not found
1388 closedir(gs_dirStream
);
1389 gs_dirStream
= (DIR *) NULL
;
1390 #endif // !VMS6.2 or earlier
1395 #elif defined(__WXMAC__)
1397 struct MacDirectoryIterator
1405 static int g_iter_flags
;
1407 static MacDirectoryIterator g_iter
;
1409 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1413 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1415 // Find path only so we can concatenate found file onto path
1416 wxString
path(wxPathOnly(spec
));
1417 if ( !path
.IsEmpty() )
1418 result
<< path
<< wxT('\\');
1422 wxMacFilename2FSSpec( result
, &fsspec
) ;
1423 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1424 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1425 g_iter
.m_index
= 0 ;
1428 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1430 return wxEmptyString
;
1432 return wxFindNextFile( ) ;
1435 wxString
wxFindNextFile()
1441 while ( err
== noErr
)
1444 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1445 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1446 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1450 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1453 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1461 return wxEmptyString
;
1465 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1470 return wxMacFSSpec2MacFilename( &spec
) ;
1473 #elif defined(__WXMSW__)
1476 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1477 static WIN32_FIND_DATA gs_findDataStruct
;
1480 static struct ffblk gs_findDataStruct
;
1482 static struct _find_t gs_findDataStruct
;
1486 static wxString gs_strFileSpec
;
1487 static int gs_findFlags
= 0;
1489 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1493 gs_strFileSpec
= spec
;
1494 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1496 // Find path only so we can concatenate found file onto path
1497 wxString
path(wxPathOnly(gs_strFileSpec
));
1498 if ( !path
.IsEmpty() )
1499 result
<< path
<< wxT('\\');
1502 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1503 FindClose(gs_hFileStruct
);
1505 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1507 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1514 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1516 if (isdir
&& !(flags
& wxDIR
))
1517 return wxFindNextFile();
1518 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1519 return wxFindNextFile();
1521 result
+= gs_findDataStruct
.cFileName
;
1525 int flag
= _A_NORMAL
;
1530 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1532 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1538 attrib
= gs_findDataStruct
.ff_attrib
;
1540 attrib
= gs_findDataStruct
.attrib
;
1543 if (attrib
& _A_SUBDIR
) {
1544 if (!(gs_findFlags
& wxDIR
))
1545 return wxFindNextFile();
1546 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1547 return wxFindNextFile();
1551 gs_findDataStruct
.ff_name
1553 gs_findDataStruct
.name
1563 wxString
wxFindNextFile()
1567 // Find path only so we can concatenate found file onto path
1568 wxString
path(wxPathOnly(gs_strFileSpec
));
1573 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1576 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1579 FindClose(gs_hFileStruct
);
1580 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1584 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1586 if (isdir
&& !(gs_findFlags
& wxDIR
))
1588 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1591 if ( !path
.IsEmpty() )
1592 result
<< path
<< wxT('\\');
1593 result
<< gs_findDataStruct
.cFileName
;
1600 if (findnext(&gs_findDataStruct
) == 0)
1602 if (_dos_findnext(&gs_findDataStruct
) == 0)
1605 /* MATTHEW: [5] Check directory flag */
1609 attrib
= gs_findDataStruct
.ff_attrib
;
1611 attrib
= gs_findDataStruct
.attrib
;
1614 if (attrib
& _A_SUBDIR
) {
1615 if (!(gs_findFlags
& wxDIR
))
1617 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1623 gs_findDataStruct
.ff_name
1625 gs_findDataStruct
.name
1634 #elif defined(__WXPM__)
1636 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1641 // TODO: figure something out here for OS/2
1642 gs_strFileSpec = spec;
1643 gs_findFlags = flags;
1645 // Find path only so we can concatenate found file onto path
1646 wxString path(wxPathOnly(gs_strFileSpec));
1647 if ( !path.IsEmpty() )
1648 result << path << wxT('\\');
1650 int flag = _A_NORMAL;
1654 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1657 attrib = gs_findDataStruct.attrib;
1659 if (attrib & _A_SUBDIR) {
1660 if (!(gs_findFlags & wxDIR))
1661 return wxFindNextFile();
1662 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1663 return wxFindNextFile();
1665 result += gs_findDataStruct.name;
1671 wxString
wxFindNextFile()
1678 #endif // Unix/Windows/OS/2
1680 // Get current working directory.
1681 // If buf is NULL, allocates space using new, else
1683 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1686 buf
= new wxChar
[sz
+1];
1688 char *cbuf
= new char[sz
+1];
1690 if (_getcwd(cbuf
, sz
) == NULL
) {
1691 #elif defined(__WXMAC__) && !defined(__UNIX__)
1694 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1698 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1699 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1700 strcpy( buf
, res
) ;
1703 if (getcwd(cbuf
, sz
) == NULL
) {
1708 if (_getcwd(buf
, sz
) == NULL
) {
1709 #elif defined(__WXMAC__) && !defined(__UNIX__)
1714 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1716 pb
.ioRefNum
= LMGetCurApRefNum();
1718 error
= PBGetFCBInfoSync(&pb
);
1719 if ( error
== noErr
)
1721 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1722 cwdSpec
.parID
= pb
.ioFCBParID
;
1723 cwdSpec
.name
[0] = 0 ;
1724 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1726 strcpy( buf
, res
) ;
1727 buf
[res
.length()-1]=0 ;
1732 this version will not always give back the application directory on mac
1735 SFSaveDisk = 0x214, CurDirStore = 0x398
1739 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1740 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1741 strcpy( buf , res ) ;
1744 #elif(__VISAGECPP__)
1746 rc
= ::DosQueryCurrentDir( 0 // current drive
1752 if (getcwd(buf
, sz
) == NULL
) {
1760 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1769 static const size_t maxPathLen
= 1024;
1772 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1773 str
.UngetWriteBuf();
1778 bool wxSetWorkingDirectory(const wxString
& d
)
1780 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1781 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1782 #elif defined(__WXPM__)
1783 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1784 #elif defined(__WINDOWS__)
1787 return (bool)(SetCurrentDirectory(d
) != 0);
1789 // Must change drive, too.
1790 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1793 wxChar firstChar
= d
[0];
1797 firstChar
= firstChar
- 32;
1799 // To a drive number
1800 unsigned int driveNo
= firstChar
- 64;
1803 unsigned int noDrives
;
1804 _dos_setdrive(driveNo
, &noDrives
);
1807 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1815 // Get the OS directory if appropriate (such as the Windows directory).
1816 // On non-Windows platform, probably just return the empty string.
1817 wxString
wxGetOSDirectory()
1819 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1821 GetWindowsDirectory(buf
, 256);
1822 return wxString(buf
);
1824 return wxEmptyString
;
1828 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1830 size_t len
= wxStrlen(pszFileName
);
1834 return wxIsPathSeparator(pszFileName
[len
- 1]);
1837 // find a file in a list of directories, returns false if not found
1838 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1840 // we assume that it's not empty
1841 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1842 _T("empty file name in wxFindFileInPath"));
1844 // skip path separator in the beginning of the file name if present
1845 if ( wxIsPathSeparator(*pszFile
) )
1848 // copy the path (strtok will modify it)
1849 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1850 wxStrcpy(szPath
, pszPath
);
1853 wxChar
*pc
, *save_ptr
;
1854 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1856 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1858 // search for the file in this directory
1860 if ( !wxEndsWithPathSeparator(pc
) )
1861 strFile
+= wxFILE_SEP_PATH
;
1864 if ( FileExists(strFile
) ) {
1870 // suppress warning about unused variable save_ptr when wxStrtok() is a
1871 // macro which throws away its third argument
1876 return pc
!= NULL
; // if true => we breaked from the loop
1879 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1884 // it can be empty, but it shouldn't be NULL
1885 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1887 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1890 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1894 wxStat(filename
.fn_str(), &buf
);
1895 return buf
.st_mtime
;
1899 //------------------------------------------------------------------------
1900 // wild character routines
1901 //------------------------------------------------------------------------
1903 bool wxIsWild( const wxString
& pattern
)
1905 wxString tmp
= pattern
;
1906 wxChar
*pat
= WXSTRINGCAST(tmp
);
1909 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1919 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1921 #if defined(HAVE_FNMATCH_H)
1923 // this probably won't work well for multibyte chars in Unicode mode?
1925 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1927 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1931 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1934 * WARNING: this code is broken!
1937 wxString tmp1
= pat
;
1938 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1939 wxString tmp2
= text
;
1940 wxChar
*str
= WXSTRINGCAST(tmp2
);
1943 bool done
= FALSE
, ret_code
, ok
;
1944 // Below is for vi fans
1945 const wxChar OB
= wxT('{'), CB
= wxT('}');
1947 // dot_special means '.' only matches '.'
1948 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1951 while ((*pattern
!= wxT('\0')) && (!done
)
1952 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1956 if (*pattern
!= wxT('\0'))
1962 while ((*str
!=wxT('\0'))
1963 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1966 while (*str
!= wxT('\0'))
1968 while (*pattern
!= wxT('\0'))
1975 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1979 if (*pattern
== wxT('\\')) {
1981 if (*pattern
== wxT('\0')) {
1986 if (*(pattern
+ 1) == wxT('-')) {
1989 if (*pattern
== wxT(']')) {
1993 if (*pattern
== wxT('\\')) {
1995 if (*pattern
== wxT('\0')) {
2000 if ((*str
< c
) || (*str
> *pattern
)) {
2004 } else if (*pattern
!= *str
) {
2009 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
2010 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
2014 if (*pattern
!= wxT('\0')) {
2024 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2027 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
2028 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
2029 if (*pattern
== wxT('\\'))
2031 ok
= (*pattern
++ == *cp
++);
2033 if (*pattern
== wxT('\0')) {
2039 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2040 if (*++pattern
== wxT('\\')) {
2041 if (*++pattern
== CB
)
2046 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2047 if (*++pattern
== wxT('\\')) {
2048 if (*++pattern
== CB
|| *pattern
== wxT(','))
2053 if (*pattern
!= wxT('\0'))
2058 if (*str
== *pattern
) {
2065 while (*pattern
== wxT('*'))
2067 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2073 #pragma warning(default:4706) // assignment within conditional expression