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"
36 // there are just too many of those...
38 #pragma warning(disable:4706) // assignment within conditional expression
45 #if !defined(__WATCOMC__)
46 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
54 #include <sys/types.h>
68 #include "wx/os2/private.h"
71 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
75 #endif // native Win compiler
79 #include <sys/unistd.h>
83 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
84 // this (3.1 I believe) and how to test for it.
85 // If this works for Borland 4.0 as well, then no worries.
97 // No, Cygwin doesn't appear to have fnmatch.h after all.
98 #if defined(HAVE_FNMATCH_H)
106 // ----------------------------------------------------------------------------
108 // ----------------------------------------------------------------------------
110 #define _MAXPATHLEN 500
112 extern wxChar
*wxBuffer
;
115 #include "morefile.h"
116 #include "moreextr.h"
117 #include "fullpath.h"
118 #include "fspcompa.h"
121 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
129 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
131 // VisualAge C++ V4.0 cannot have any external linkage const decs
132 // in headers included by more than one primary source
134 const off_t wxInvalidOffset
= (off_t
)-1;
137 // ----------------------------------------------------------------------------
139 // ----------------------------------------------------------------------------
141 // we need to translate Mac filenames before passing them to OS functions
143 #define OS_FILENAME(s) (wxUnix2MacFilename(s))
145 #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
)
289 if (filename
!= wxT(""))
291 if (filename
[0] == wxT('/')
293 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
297 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
306 * Strip off any extension (dot something) from end of file,
307 * IF one exists. Inserts zero into buffer.
311 void wxStripExtension(wxChar
*buffer
)
313 int len
= wxStrlen(buffer
);
317 if (buffer
[i
] == wxT('.'))
326 void wxStripExtension(wxString
& buffer
)
328 size_t len
= buffer
.Length();
332 if (buffer
.GetChar(i
) == wxT('.'))
334 buffer
= buffer
.Left(i
);
341 // Destructive removal of /./ and /../ stuff
342 wxChar
*wxRealPath (wxChar
*path
)
345 static const wxChar SEP
= wxT('\\');
346 Unix2DosFilename(path
);
348 static const wxChar SEP
= wxT('/');
350 if (path
[0] && path
[1]) {
351 /* MATTHEW: special case "/./x" */
353 if (path
[2] == SEP
&& path
[1] == wxT('.'))
361 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
364 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
365 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
366 && (q
- 1 <= path
|| q
[-1] != SEP
))
369 if (path
[0] == wxT('\0'))
375 /* Check that path[2] is NULL! */
376 else if (path
[1] == wxT(':') && !path
[2])
385 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
394 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
396 if (filename
== wxT(""))
397 return (wxChar
*) NULL
;
399 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
400 wxChar buf
[_MAXPATHLEN
];
402 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
403 wxChar ch
= buf
[wxStrlen(buf
) - 1];
405 if (ch
!= wxT('\\') && ch
!= wxT('/'))
406 wxStrcat(buf
, wxT("\\"));
409 wxStrcat(buf
, wxT("/"));
411 wxStrcat(buf
, wxFileFunctionsBuffer
);
412 return copystring( wxRealPath(buf
) );
414 return copystring( wxFileFunctionsBuffer
);
420 ~user/ => user's home dir
421 If the environment variable a = "foo" and b = "bar" then:
438 /* input name in name, pathname output to buf. */
440 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
442 register wxChar
*d
, *s
, *nm
;
443 wxChar lnm
[_MAXPATHLEN
];
446 // Some compilers don't like this line.
447 // const wxChar trimchars[] = wxT("\n \t");
450 trimchars
[0] = wxT('\n');
451 trimchars
[1] = wxT(' ');
452 trimchars
[2] = wxT('\t');
456 const wxChar SEP
= wxT('\\');
458 const wxChar SEP
= wxT('/');
461 if (name
== NULL
|| *name
== wxT('\0'))
463 nm
= copystring(name
); // Make a scratch copy
466 /* Skip leading whitespace and cr */
467 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
469 /* And strip off trailing whitespace and cr */
470 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
471 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
479 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
482 /* Expand inline environment variables */
500 while ((*d
++ = *s
)) {
502 if (*s
== wxT('\\')) {
503 if ((*(d
- 1) = *++s
)) {
512 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
514 if (*s
++ == wxT('$'))
517 register wxChar
*start
= d
;
518 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
519 register wxChar
*value
;
521 // VA gives assignment in logical expr warning
527 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
532 value
= wxGetenv(braces
? start
+ 1 : start
);
535 // VA gives assignment in logical expr warning
536 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
538 for ((d
= start
- 1); (*d
++ = *value
++););
547 /* Expand ~ and ~user */
550 if (nm
[0] == wxT('~') && !q
)
553 if (nm
[1] == SEP
|| nm
[1] == 0)
555 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
556 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
561 { /* ~user/filename */
562 register wxChar
*nnm
;
563 register wxChar
*home
;
564 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
565 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
566 was_sep
= (*s
== SEP
);
567 nnm
= *s
? s
+ 1 : s
;
569 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
570 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
571 if (was_sep
) /* replace only if it was there: */
582 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
584 while (wxT('\0') != (*d
++ = *s
++))
587 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
592 // VA gives assignment in logical expr warning
596 while ((*d
++ = *s
++));
598 delete[] nm_tmp
; // clean up alloc
599 /* Now clean up the buffer */
600 return wxRealPath(buf
);
603 /* Contract Paths to be build upon an environment variable
606 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
608 The call wxExpandPath can convert these back!
611 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
613 static wxChar dest
[_MAXPATHLEN
];
615 if (filename
== wxT(""))
616 return (wxChar
*) NULL
;
618 wxStrcpy (dest
, WXSTRINGCAST filename
);
620 Unix2DosFilename(dest
);
623 // Handle environment
624 const wxChar
*val
= (const wxChar
*) NULL
;
625 wxChar
*tcp
= (wxChar
*) NULL
;
626 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
627 (tcp
= wxStrstr (dest
, val
)) != NULL
)
629 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
632 wxStrcpy (tcp
, WXSTRINGCAST envname
);
633 wxStrcat (tcp
, wxT("}"));
634 wxStrcat (tcp
, wxFileFunctionsBuffer
);
637 // Handle User's home (ignore root homes!)
639 if ((val
= wxGetUserHome (user
)) != NULL
&&
640 (len
= wxStrlen(val
)) > 2 &&
641 wxStrncmp(dest
, val
, len
) == 0)
643 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
645 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
647 // strcat(wxFileFunctionsBuffer, "\\");
649 // strcat(wxFileFunctionsBuffer, "/");
651 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
652 wxStrcpy (dest
, wxFileFunctionsBuffer
);
658 // Return just the filename, not the path
660 wxChar
*wxFileNameFromPath (wxChar
*path
)
664 register wxChar
*tcp
;
666 tcp
= path
+ wxStrlen (path
);
667 while (--tcp
>= path
)
669 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
671 || *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
)
696 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
698 || *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)
734 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
738 if ( path
[i
] == wxT(']') )
749 #if defined(__WXMSW__) || defined(__WXPM__)
750 // Try Drive specifier
751 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
753 // A:junk --> A:. (since A:.\junk Not A:\junk)
761 return (wxChar
*) NULL
;
764 // Return just the directory, or NULL if no directory
765 wxString
wxPathOnly (const wxString
& path
)
769 wxChar buf
[_MAXPATHLEN
];
772 wxStrcpy (buf
, WXSTRINGCAST path
);
774 int l
= path
.Length();
779 // Search backward for a backward or forward slash
780 while (!done
&& i
> -1)
783 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
787 if ( path
[i
] == wxT(']') )
793 return wxString(buf
);
798 #if defined(__WXMSW__) || defined(__WXPM__)
799 // Try Drive specifier
800 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
802 // A:junk --> A:. (since A:.\junk Not A:\junk)
805 return wxString(buf
);
810 return wxString(wxT(""));
813 // Utility for converting delimiters in DOS filenames to UNIX style
814 // and back again - or we get nasty problems with delimiters.
815 // Also, convert to lower case, since case is significant in UNIX.
819 static char sMacFileNameConversion
[ 1000 ] ;
821 wxString
wxMac2UnixFilename (const char *str
)
823 char *s
= sMacFileNameConversion
;
827 memmove( s
+1 , s
,strlen( s
) + 1) ;
838 *s
= wxTolower (*s
); // Case INDEPENDENT
842 return wxString (sMacFileNameConversion
) ;
845 wxString
wxUnix2MacFilename (const char *str
)
847 char *s
= sMacFileNameConversion
;
853 // relative path , since it goes on with slash which is translated to a :
854 memmove( s
, s
+1 ,strlen( s
) ) ;
856 else if ( *s
== '/' )
858 // absolute path -> on mac just start with the drive name
859 memmove( s
, s
+1 ,strlen( s
) ) ;
863 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
867 if (*s
== '/' || *s
== '\\')
869 // convert any back-directory situations
870 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
873 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
882 return wxString (sMacFileNameConversion
) ;
885 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
890 FSpGetFullPath( spec
, &length
, &myPath
) ;
891 ::SetHandleSize( myPath
, length
+ 1 ) ;
893 (*myPath
)[length
] = 0 ;
894 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
895 (*myPath
)[length
-1] = 0 ;
897 wxString
result( (char*) *myPath
) ;
898 ::HUnlock( myPath
) ;
899 ::DisposeHandle( myPath
) ;
903 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
905 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
908 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
910 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
913 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
915 wxString var
= wxUnix2MacFilename( path
) ;
916 wxMacFilename2FSSpec( var
, spec
) ;
921 wxDos2UnixFilename (char *s
)
930 *s
= wxTolower (*s
); // Case INDEPENDENT
937 #if defined(__WXMSW__) || defined(__WXPM__)
938 wxUnix2DosFilename (wxChar
*s
)
940 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
943 // Yes, I really mean this to happen under DOS only! JACS
944 #if defined(__WXMSW__) || defined(__WXPM__)
955 // Concatenate two files to form third
957 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
960 if ( !wxGetTempFileName("cat", outfile
) )
963 FILE *fp1
= (FILE *) NULL
;
964 FILE *fp2
= (FILE *) NULL
;
965 FILE *fp3
= (FILE *) NULL
;
966 // Open the inputs and outputs
967 if ((fp1
= fopen (OS_FILENAME( file1
), "rb")) == NULL
||
968 (fp2
= fopen (OS_FILENAME( file2
), "rb")) == NULL
||
969 (fp3
= fopen (OS_FILENAME( outfile
), "wb")) == NULL
)
981 while ((ch
= getc (fp1
)) != EOF
)
982 (void) putc (ch
, fp3
);
985 while ((ch
= getc (fp2
)) != EOF
)
986 (void) putc (ch
, fp3
);
990 bool result
= wxRenameFile(outfile
, file3
);
997 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
999 wxFFile
fileIn(file1
, "rb");
1000 if ( !fileIn
.IsOpened() )
1003 wxFFile
fileOut(file2
, "wb");
1004 if ( !fileOut
.IsOpened() )
1011 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1012 if ( fileIn
.Error() )
1019 if ( fileOut
.Write(buf
, count
) < count
)
1027 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1029 // Normal system call
1030 if ( wxRename (OS_FILENAME(file1
), OS_FILENAME(file2
)) == 0 )
1034 if (wxCopyFile(file1
, file2
)) {
1035 wxRemoveFile(file1
);
1042 bool wxRemoveFile(const wxString
& file
)
1044 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1045 int res
= wxRemove(file
);
1047 int res
= unlink(OS_FILENAME(file
));
1053 bool wxMkdir(const wxString
& dir
, int perm
)
1055 #if defined( __WXMAC__ )
1056 return (mkdir(wxUnix2MacFilename( dir
) , 0 ) == 0);
1058 const wxChar
*dirname
= dir
.c_str();
1060 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1061 // for the GNU compiler
1062 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1063 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1064 #elif defined(__WXPM__)
1065 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1066 #else // !MSW and !OS/2 VAC++
1067 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1070 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1079 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1082 return FALSE
; //to be changed since rmdir exists in VMS7.x
1083 #elif defined(__WXPM__)
1084 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1088 return FALSE
; // What to do?
1090 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1096 // does the path exists? (may have or not '/' or '\\' at the end)
1097 bool wxPathExists(const wxChar
*pszPathName
)
1099 wxString
strPath(pszPathName
);
1101 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1102 // so remove all trailing backslashes from the path - but don't do this for
1103 // the pathes "d:\" (which are different from "d:") nor for just "\"
1104 while ( wxEndsWithPathSeparator(strPath
) )
1106 size_t len
= strPath
.length();
1107 if ( len
== 1 || strPath
[len
- 1] == _T(':') )
1110 strPath
.Truncate(len
- 1);
1112 #endif // __WINDOWS__
1115 #ifndef __VISAGECPP__
1116 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1117 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1119 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1120 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1121 (st
.st_mode
== S_IFDIR
);
1126 // Get a temporary filename, opening and closing the file.
1127 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1133 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1135 wxChar tmp
[MAX_PATH
];
1136 wxChar tmpPath
[MAX_PATH
];
1137 ::GetTempPath(MAX_PATH
, tmpPath
);
1138 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1140 if (buf
) wxStrcpy(buf
, tmp
);
1141 else buf
= copystring(tmp
);
1145 static short last_temp
= 0; // cache last to speed things a bit
1146 // At most 1000 temp files to a process! We use a ring count.
1147 wxChar tmp
[100]; // FIXME static buffer
1149 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1151 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1152 if (!wxFileExists( tmp
))
1154 // Touch the file to create it (reserve name)
1155 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1160 wxStrcpy( buf
, tmp
);
1162 buf
= copystring( tmp
);
1166 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1167 if (buf
) buf
[0] = 0;
1168 return (wxChar
*) NULL
;
1172 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1175 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1184 // Get first file name matching given wild card.
1188 // Get first file name matching given wild card.
1189 // Flags are reserved for future use.
1191 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1192 static DIR *gs_dirStream
= (DIR *) NULL
;
1193 static wxString gs_strFileSpec
;
1194 static int gs_findFlags
= 0;
1197 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1201 wxChar
*specvms
= NULL
;
1204 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1206 closedir(gs_dirStream
); // edz 941103: better housekeping
1208 gs_findFlags
= flags
;
1210 gs_strFileSpec
= spec
;
1212 // Find path only so we can concatenate
1213 // found file onto path
1214 wxString
path(wxPathOnly(gs_strFileSpec
));
1216 // special case: path is really "/"
1217 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1220 wxStrcpy( specvms
, wxT( "[000000]" ) );
1221 gs_strFileSpec
= specvms
;
1222 wxString
path_vms(wxPathOnly(gs_strFileSpec
));
1228 // path is empty => Local directory
1232 wxStrcpy( specvms
, wxT( "[]" ) );
1233 gs_strFileSpec
= specvms
;
1234 wxString
path_vms1(wxPathOnly(gs_strFileSpec
));
1241 gs_dirStream
= opendir(path
.fn_str());
1242 if ( !gs_dirStream
)
1244 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1249 result
= wxFindNextFile();
1251 #endif // !VMS6.x or earlier
1256 wxString
wxFindNextFile()
1260 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1261 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1263 // Find path only so we can concatenate
1264 // found file onto path
1265 wxString
path(wxPathOnly(gs_strFileSpec
));
1266 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1268 /* MATTHEW: special case: path is really "/" */
1269 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1273 struct dirent
*nextDir
;
1274 for ( nextDir
= readdir(gs_dirStream
);
1276 nextDir
= readdir(gs_dirStream
) )
1278 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1279 strcmp(nextDir
->d_name
, ".") &&
1280 strcmp(nextDir
->d_name
, "..") )
1283 if ( !path
.IsEmpty() )
1286 if ( path
!= wxT('/') )
1290 result
+= nextDir
->d_name
;
1292 // Only return "." and ".." when they match
1294 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1295 (strcmp(nextDir
->d_name
, "..") == 0))
1297 if ( (gs_findFlags
& wxDIR
) != 0 )
1303 isdir
= wxDirExists(result
);
1305 // and only return directories when flags & wxDIR
1306 if ( !gs_findFlags
||
1307 ((gs_findFlags
& wxDIR
) && isdir
) ||
1308 ((gs_findFlags
& wxFILE
) && !isdir
) )
1315 result
.Empty(); // not found
1317 closedir(gs_dirStream
);
1318 gs_dirStream
= (DIR *) NULL
;
1319 #endif // !VMS6.2 or earlier
1324 #elif defined(__WXMAC__)
1326 struct MacDirectoryIterator
1334 static int g_iter_flags
;
1336 static MacDirectoryIterator g_iter
;
1338 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1342 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1344 // Find path only so we can concatenate found file onto path
1345 wxString
path(wxPathOnly(spec
));
1346 if ( !path
.IsEmpty() )
1347 result
<< path
<< wxT('\\');
1351 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1352 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1353 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1354 g_iter
.m_index
= 0 ;
1357 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1359 return wxEmptyString
;
1361 return wxFindNextFile( ) ;
1364 wxString
wxFindNextFile()
1370 while ( err
== noErr
)
1373 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1374 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1375 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1379 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1382 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1390 return wxEmptyString
;
1394 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1399 return wxMacFSSpec2UnixFilename( &spec
) ;
1402 #elif defined(__WXMSW__)
1405 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1406 static WIN32_FIND_DATA gs_findDataStruct
;
1409 static struct ffblk gs_findDataStruct
;
1411 static struct _find_t gs_findDataStruct
;
1415 static wxString gs_strFileSpec
;
1416 static int gs_findFlags
= 0;
1418 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1422 gs_strFileSpec
= spec
;
1423 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1425 // Find path only so we can concatenate found file onto path
1426 wxString
path(wxPathOnly(gs_strFileSpec
));
1427 if ( !path
.IsEmpty() )
1428 result
<< path
<< wxT('\\');
1431 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1432 FindClose(gs_hFileStruct
);
1434 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1436 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1443 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1445 if (isdir
&& !(flags
& wxDIR
))
1446 return wxFindNextFile();
1447 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1448 return wxFindNextFile();
1450 result
+= gs_findDataStruct
.cFileName
;
1454 int flag
= _A_NORMAL
;
1459 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1461 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1467 attrib
= gs_findDataStruct
.ff_attrib
;
1469 attrib
= gs_findDataStruct
.attrib
;
1472 if (attrib
& _A_SUBDIR
) {
1473 if (!(gs_findFlags
& wxDIR
))
1474 return wxFindNextFile();
1475 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1476 return wxFindNextFile();
1480 gs_findDataStruct
.ff_name
1482 gs_findDataStruct
.name
1492 wxString
wxFindNextFile()
1496 // Find path only so we can concatenate found file onto path
1497 wxString
path(wxPathOnly(gs_strFileSpec
));
1502 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1505 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1508 FindClose(gs_hFileStruct
);
1509 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1513 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1515 if (isdir
&& !(gs_findFlags
& wxDIR
))
1517 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1520 if ( !path
.IsEmpty() )
1521 result
<< path
<< wxT('\\');
1522 result
<< gs_findDataStruct
.cFileName
;
1529 if (findnext(&gs_findDataStruct
) == 0)
1531 if (_dos_findnext(&gs_findDataStruct
) == 0)
1534 /* MATTHEW: [5] Check directory flag */
1538 attrib
= gs_findDataStruct
.ff_attrib
;
1540 attrib
= gs_findDataStruct
.attrib
;
1543 if (attrib
& _A_SUBDIR
) {
1544 if (!(gs_findFlags
& wxDIR
))
1546 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1552 gs_findDataStruct
.ff_name
1554 gs_findDataStruct
.name
1563 #elif defined(__WXPM__)
1565 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1570 // TODO: figure something out here for OS/2
1571 gs_strFileSpec = spec;
1572 gs_findFlags = flags;
1574 // Find path only so we can concatenate found file onto path
1575 wxString path(wxPathOnly(gs_strFileSpec));
1576 if ( !path.IsEmpty() )
1577 result << path << wxT('\\');
1579 int flag = _A_NORMAL;
1583 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1586 attrib = gs_findDataStruct.attrib;
1588 if (attrib & _A_SUBDIR) {
1589 if (!(gs_findFlags & wxDIR))
1590 return wxFindNextFile();
1591 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1592 return wxFindNextFile();
1594 result += gs_findDataStruct.name;
1600 wxString
wxFindNextFile()
1607 #endif // Unix/Windows/OS/2
1609 // Get current working directory.
1610 // If buf is NULL, allocates space using new, else
1612 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1615 buf
= new wxChar
[sz
+1];
1617 char *cbuf
= new char[sz
+1];
1619 if (_getcwd(cbuf
, sz
) == NULL
) {
1620 #elif defined( __WXMAC__)
1623 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1627 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1628 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1629 strcpy( buf
, res
) ;
1632 if (getcwd(cbuf
, sz
) == NULL
) {
1637 if (_getcwd(buf
, sz
) == NULL
) {
1638 #elif defined( __WXMAC__)
1641 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1645 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1646 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1647 strcpy( buf
, res
) ;
1649 #elif(__VISAGECPP__)
1651 rc
= ::DosQueryCurrentDir( 0 // current drive
1657 if (getcwd(buf
, sz
) == NULL
) {
1665 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1674 static const size_t maxPathLen
= 1024;
1677 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1678 str
.UngetWriteBuf();
1683 bool wxSetWorkingDirectory(const wxString
& d
)
1685 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1686 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1687 #elif defined(__WXPM__)
1688 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1689 #elif defined(__WINDOWS__)
1692 return (bool)(SetCurrentDirectory(d
) != 0);
1694 // Must change drive, too.
1695 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1698 wxChar firstChar
= d
[0];
1702 firstChar
= firstChar
- 32;
1704 // To a drive number
1705 unsigned int driveNo
= firstChar
- 64;
1708 unsigned int noDrives
;
1709 _dos_setdrive(driveNo
, &noDrives
);
1712 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1720 // Get the OS directory if appropriate (such as the Windows directory).
1721 // On non-Windows platform, probably just return the empty string.
1722 wxString
wxGetOSDirectory()
1726 GetWindowsDirectory(buf
, 256);
1727 return wxString(buf
);
1729 return wxEmptyString
;
1733 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1735 size_t len
= wxStrlen(pszFileName
);
1739 return wxIsPathSeparator(pszFileName
[len
- 1]);
1742 // find a file in a list of directories, returns false if not found
1743 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1745 // we assume that it's not empty
1746 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1747 _T("empty file name in wxFindFileInPath"));
1749 // skip path separator in the beginning of the file name if present
1750 if ( wxIsPathSeparator(*pszFile
) )
1753 // copy the path (strtok will modify it)
1754 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1755 wxStrcpy(szPath
, pszPath
);
1758 wxChar
*pc
, *save_ptr
;
1759 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1761 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1763 // search for the file in this directory
1765 if ( !wxEndsWithPathSeparator(pc
) )
1766 strFile
+= wxFILE_SEP_PATH
;
1769 if ( FileExists(strFile
) ) {
1775 // suppress warning about unused variable save_ptr when wxStrtok() is a
1776 // macro which throws away its third argument
1781 return pc
!= NULL
; // if true => we breaked from the loop
1784 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1789 // it can be empty, but it shouldn't be NULL
1790 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1792 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1795 // under Windows we understand both separators
1796 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1797 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1798 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1799 #else // assume Unix
1800 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1804 if ( (pDot
== pszFileName
) || (*(pDot
- 1) == wxFILE_SEP_PATH_UNIX
) )
1806 // under Unix, dot may be (and commonly is) the first character of the
1807 // filename, don't treat the entire filename as extension in this case
1813 if ( pDot
&& (pDot
< pLastSeparator
) )
1815 // the dot is part of the path, not the start of the extension
1821 if ( pLastSeparator
)
1822 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1829 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1830 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1832 *pstrName
= wxString(start
, end
- start
);
1838 *pstrExt
= wxString(pDot
+ 1);
1844 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1848 wxStat(filename
.fn_str(), &buf
);
1849 return buf
.st_mtime
;
1853 //------------------------------------------------------------------------
1854 // wild character routines
1855 //------------------------------------------------------------------------
1857 bool wxIsWild( const wxString
& pattern
)
1859 wxString tmp
= pattern
;
1860 wxChar
*pat
= WXSTRINGCAST(tmp
);
1863 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1873 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1875 #if defined(HAVE_FNMATCH_H)
1877 // this probably won't work well for multibyte chars in Unicode mode?
1879 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1881 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1885 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1888 * WARNING: this code is broken!
1891 wxString tmp1
= pat
;
1892 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1893 wxString tmp2
= text
;
1894 wxChar
*str
= WXSTRINGCAST(tmp2
);
1897 bool done
= FALSE
, ret_code
, ok
;
1898 // Below is for vi fans
1899 const wxChar OB
= wxT('{'), CB
= wxT('}');
1901 // dot_special means '.' only matches '.'
1902 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1905 while ((*pattern
!= wxT('\0')) && (!done
)
1906 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1910 if (*pattern
!= wxT('\0'))
1916 while ((*str
!=wxT('\0'))
1917 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1920 while (*str
!= wxT('\0'))
1922 while (*pattern
!= wxT('\0'))
1929 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1933 if (*pattern
== wxT('\\')) {
1935 if (*pattern
== wxT('\0')) {
1940 if (*(pattern
+ 1) == wxT('-')) {
1943 if (*pattern
== wxT(']')) {
1947 if (*pattern
== wxT('\\')) {
1949 if (*pattern
== wxT('\0')) {
1954 if ((*str
< c
) || (*str
> *pattern
)) {
1958 } else if (*pattern
!= *str
) {
1963 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1964 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1968 if (*pattern
!= wxT('\0')) {
1978 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1981 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1982 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1983 if (*pattern
== wxT('\\'))
1985 ok
= (*pattern
++ == *cp
++);
1987 if (*pattern
== wxT('\0')) {
1993 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1994 if (*++pattern
== wxT('\\')) {
1995 if (*++pattern
== CB
)
2000 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2001 if (*++pattern
== wxT('\\')) {
2002 if (*++pattern
== CB
|| *pattern
== wxT(','))
2007 if (*pattern
!= wxT('\0'))
2012 if (*str
== *pattern
) {
2019 while (*pattern
== wxT('*'))
2021 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2027 #pragma warning(default:4706) // assignment within conditional expression