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"
39 // there are just too many of those...
41 #pragma warning(disable:4706) // assignment within conditional expression
48 #if !defined(__WATCOMC__)
49 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
57 #include <sys/types.h>
74 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
78 #endif // native Win compiler
82 #include <sys/unistd.h>
86 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
87 // this (3.1 I believe) and how to test for it.
88 // If this works for Borland 4.0 as well, then no worries.
100 // No, Cygwin doesn't appear to have fnmatch.h after all.
101 #if defined(HAVE_FNMATCH_H)
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 #define _MAXPATHLEN 500
115 extern wxChar
*wxBuffer
;
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 void wxPathList::Add (const wxString
& path
)
147 wxStringList::Add (WXSTRINGCAST path
);
150 // Add paths e.g. from the PATH environment variable
151 void wxPathList::AddEnvList (const wxString
& envVariable
)
153 static const wxChar PATH_TOKS
[] =
155 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
160 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
163 wxChar
*s
= copystring (val
);
164 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
168 Add (copystring (token
));
171 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
172 Add (wxString(token
));
176 // suppress warning about unused variable save_ptr when wxStrtok() is a
177 // macro which throws away its third argument
184 // Given a full filename (with path), ensure that that file can
185 // be accessed again USING FILENAME ONLY by adding the path
186 // to the list if not already there.
187 void wxPathList::EnsureFileAccessible (const wxString
& path
)
189 wxString
path_only(wxPathOnly(path
));
190 if ( !path_only
.IsEmpty() )
192 if ( !Member(path_only
) )
197 bool wxPathList::Member (const wxString
& path
)
199 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
201 wxString
path2((wxChar
*) node
->Data ());
203 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
205 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
207 // Case sensitive File System
208 path
.CompareTo (path2
) == 0
216 wxString
wxPathList::FindValidPath (const wxString
& file
)
218 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
219 return wxString(wxFileFunctionsBuffer
);
221 wxChar buf
[_MAXPATHLEN
];
222 wxStrcpy(buf
, wxFileFunctionsBuffer
);
224 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
225 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
227 for (wxNode
* node
= First (); node
; node
= node
->Next ())
229 wxChar
*path
= (wxChar
*) node
->Data ();
230 wxStrcpy (wxFileFunctionsBuffer
, path
);
231 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
232 if (ch
!= wxT('\\') && ch
!= wxT('/'))
233 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
234 wxStrcat (wxFileFunctionsBuffer
, filename
);
236 Unix2DosFilename (wxFileFunctionsBuffer
);
238 if (wxFileExists (wxFileFunctionsBuffer
))
240 return wxString(wxFileFunctionsBuffer
); // Found!
244 return wxString(wxT("")); // Not found
247 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
249 wxString f
= FindValidPath(file
);
250 if ( wxIsAbsolutePath(f
) )
254 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
256 if ( !wxEndsWithPathSeparator(buf
) )
258 buf
+= wxFILE_SEP_PATH
;
266 wxFileExists (const wxString
& filename
)
268 #ifdef __GNUWIN32__ // (fix a B20 bug)
269 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
273 #elif defined(__WXMAC__)
275 if (filename
&& stat (wxUnix2MacFilename(filename
), &stbuf
) == 0 )
286 if ((filename
!= wxT("")) && stat (wxFNSTRINGCAST filename
.fn_str(), &stbuf
) == 0)
292 /* Vadim's alternative implementation
294 // does the file exist?
295 bool wxFileExists(const char *pszFileName)
298 return !access(pszFileName, 0) &&
299 !stat(pszFileName, &st) &&
300 (st.st_mode & S_IFREG);
305 wxIsAbsolutePath (const wxString
& filename
)
307 if (filename
!= wxT(""))
309 if (filename
[0] == wxT('/')
311 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
315 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
324 * Strip off any extension (dot something) from end of file,
325 * IF one exists. Inserts zero into buffer.
329 void wxStripExtension(wxChar
*buffer
)
331 int len
= wxStrlen(buffer
);
335 if (buffer
[i
] == wxT('.'))
344 void wxStripExtension(wxString
& buffer
)
346 size_t len
= buffer
.Length();
350 if (buffer
.GetChar(i
) == wxT('.'))
352 buffer
= buffer
.Left(i
);
359 // Destructive removal of /./ and /../ stuff
360 wxChar
*wxRealPath (wxChar
*path
)
363 static const wxChar SEP
= wxT('\\');
364 Unix2DosFilename(path
);
366 static const wxChar SEP
= wxT('/');
368 if (path
[0] && path
[1]) {
369 /* MATTHEW: special case "/./x" */
371 if (path
[2] == SEP
&& path
[1] == wxT('.'))
379 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
382 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
383 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
384 && (q
- 1 <= path
|| q
[-1] != SEP
))
387 if (path
[0] == wxT('\0'))
393 /* Check that path[2] is NULL! */
394 else if (path
[1] == wxT(':') && !path
[2])
403 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
412 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
414 if (filename
== wxT(""))
415 return (wxChar
*) NULL
;
417 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
418 wxChar buf
[_MAXPATHLEN
];
420 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
421 wxChar ch
= buf
[wxStrlen(buf
) - 1];
423 if (ch
!= wxT('\\') && ch
!= wxT('/'))
424 wxStrcat(buf
, wxT("\\"));
427 wxStrcat(buf
, wxT("/"));
429 wxStrcat(buf
, wxFileFunctionsBuffer
);
430 return copystring( wxRealPath(buf
) );
432 return copystring( wxFileFunctionsBuffer
);
438 ~user/ => user's home dir
439 If the environment variable a = "foo" and b = "bar" then:
456 /* input name in name, pathname output to buf. */
458 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
460 register wxChar
*d
, *s
, *nm
;
461 wxChar lnm
[_MAXPATHLEN
];
464 // Some compilers don't like this line.
465 // const wxChar trimchars[] = wxT("\n \t");
468 trimchars
[0] = wxT('\n');
469 trimchars
[1] = wxT(' ');
470 trimchars
[2] = wxT('\t');
474 const wxChar SEP
= wxT('\\');
476 const wxChar SEP
= wxT('/');
479 if (name
== NULL
|| *name
== wxT('\0'))
481 nm
= copystring(name
); // Make a scratch copy
484 /* Skip leading whitespace and cr */
485 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
487 /* And strip off trailing whitespace and cr */
488 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
489 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
497 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
500 /* Expand inline environment variables */
518 while ((*d
++ = *s
)) {
520 if (*s
== wxT('\\')) {
521 if ((*(d
- 1) = *++s
)) {
530 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
532 if (*s
++ == wxT('$'))
535 register wxChar
*start
= d
;
536 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
537 register wxChar
*value
;
539 // VA gives assignment in logical expr warning
545 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
550 value
= wxGetenv(braces
? start
+ 1 : start
);
553 // VA gives assignment in logical expr warning
554 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
556 for ((d
= start
- 1); (*d
++ = *value
++););
565 /* Expand ~ and ~user */
568 if (nm
[0] == wxT('~') && !q
)
571 if (nm
[1] == SEP
|| nm
[1] == 0)
573 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
574 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
579 { /* ~user/filename */
580 register wxChar
*nnm
;
581 register wxChar
*home
;
582 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
583 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
584 was_sep
= (*s
== SEP
);
585 nnm
= *s
? s
+ 1 : s
;
587 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
588 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
589 if (was_sep
) /* replace only if it was there: */
600 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
602 while (wxT('\0') != (*d
++ = *s
++))
605 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
610 // VA gives assignment in logical expr warning
614 while ((*d
++ = *s
++));
616 delete[] nm_tmp
; // clean up alloc
617 /* Now clean up the buffer */
618 return wxRealPath(buf
);
621 /* Contract Paths to be build upon an environment variable
624 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
626 The call wxExpandPath can convert these back!
629 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
631 static wxChar dest
[_MAXPATHLEN
];
633 if (filename
== wxT(""))
634 return (wxChar
*) NULL
;
636 wxStrcpy (dest
, WXSTRINGCAST filename
);
638 Unix2DosFilename(dest
);
641 // Handle environment
642 const wxChar
*val
= (const wxChar
*) NULL
;
643 wxChar
*tcp
= (wxChar
*) NULL
;
644 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
645 (tcp
= wxStrstr (dest
, val
)) != NULL
)
647 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
650 wxStrcpy (tcp
, WXSTRINGCAST envname
);
651 wxStrcat (tcp
, wxT("}"));
652 wxStrcat (tcp
, wxFileFunctionsBuffer
);
655 // Handle User's home (ignore root homes!)
657 if ((val
= wxGetUserHome (user
)) != NULL
&&
658 (len
= wxStrlen(val
)) > 2 &&
659 wxStrncmp(dest
, val
, len
) == 0)
661 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
663 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
665 // strcat(wxFileFunctionsBuffer, "\\");
667 // strcat(wxFileFunctionsBuffer, "/");
669 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
670 wxStrcpy (dest
, wxFileFunctionsBuffer
);
676 // Return just the filename, not the path
678 wxChar
*wxFileNameFromPath (wxChar
*path
)
682 register wxChar
*tcp
;
684 tcp
= path
+ wxStrlen (path
);
685 while (--tcp
>= path
)
687 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
689 || *tcp
== wxT(':') || *tcp
== wxT(']'))
695 #if defined(__WXMSW__) || defined(__WXPM__)
696 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
703 wxString
wxFileNameFromPath (const wxString
& path1
)
705 if (path1
!= wxT(""))
708 wxChar
*path
= WXSTRINGCAST path1
;
709 register wxChar
*tcp
;
711 tcp
= path
+ wxStrlen (path
);
712 while (--tcp
>= path
)
714 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
716 || *tcp
== wxT(':') || *tcp
== wxT(']'))
720 return wxString(tcp
+ 1);
722 #if defined(__WXMSW__) || defined(__WXPM__)
723 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
724 return wxString(path
+ 2);
727 // Yes, this should return the path, not an empty string, otherwise
728 // we get "thing.txt" -> "".
732 // Return just the directory, or NULL if no directory
734 wxPathOnly (wxChar
*path
)
738 static wxChar buf
[_MAXPATHLEN
];
741 wxStrcpy (buf
, path
);
743 int l
= wxStrlen(path
);
748 // Search backward for a backward or forward slash
749 while (!done
&& i
> -1)
752 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
766 #if defined(__WXMSW__) || defined(__WXPM__)
767 // Try Drive specifier
768 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
770 // A:junk --> A:. (since A:.\junk Not A:\junk)
778 return (wxChar
*) NULL
;
781 // Return just the directory, or NULL if no directory
782 wxString
wxPathOnly (const wxString
& path
)
786 wxChar buf
[_MAXPATHLEN
];
789 wxStrcpy (buf
, WXSTRINGCAST path
);
791 int l
= path
.Length();
796 // Search backward for a backward or forward slash
797 while (!done
&& i
> -1)
800 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
809 return wxString(buf
);
814 #if defined(__WXMSW__) || defined(__WXPM__)
815 // Try Drive specifier
816 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
818 // A:junk --> A:. (since A:.\junk Not A:\junk)
821 return wxString(buf
);
826 return wxString(wxT(""));
829 // Utility for converting delimiters in DOS filenames to UNIX style
830 // and back again - or we get nasty problems with delimiters.
831 // Also, convert to lower case, since case is significant in UNIX.
835 static char sMacFileNameConversion
[ 1000 ] ;
837 wxString
wxMac2UnixFilename (const char *str
)
839 char *s
= sMacFileNameConversion
;
843 memmove( s
+1 , s
,strlen( s
) + 1) ;
854 *s
= wxTolower (*s
); // Case INDEPENDENT
858 return wxString (sMacFileNameConversion
) ;
861 wxString
wxUnix2MacFilename (const char *str
)
863 char *s
= sMacFileNameConversion
;
869 // relative path , since it goes on with slash which is translated to a :
870 memmove( s
, s
+1 ,strlen( s
) ) ;
872 else if ( *s
== '/' )
874 // absolute path -> on mac just start with the drive name
875 memmove( s
, s
+1 ,strlen( s
) ) ;
879 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
883 if (*s
== '/' || *s
== '\\')
885 // convert any back-directory situations
886 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
889 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
898 return wxString (sMacFileNameConversion
) ;
901 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
906 FSpGetFullPath( spec
, &length
, &myPath
) ;
907 ::SetHandleSize( myPath
, length
+ 1 ) ;
909 (*myPath
)[length
] = 0 ;
910 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
911 (*myPath
)[length
-1] = 0 ;
913 wxString
result( (char*) *myPath
) ;
914 ::HUnlock( myPath
) ;
915 ::DisposeHandle( myPath
) ;
919 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
921 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
924 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
926 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
929 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
931 wxString var
= wxUnix2MacFilename( path
) ;
932 wxMacFilename2FSSpec( var
, spec
) ;
937 wxDos2UnixFilename (char *s
)
946 *s
= wxTolower (*s
); // Case INDEPENDENT
953 #if defined(__WXMSW__) || defined(__WXPM__)
954 wxUnix2DosFilename (wxChar
*s
)
956 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
959 // Yes, I really mean this to happen under DOS only! JACS
960 #if defined(__WXMSW__) || defined(__WXPM__)
971 // Concatenate two files to form third
973 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
975 wxChar
*outfile
= wxGetTempFileName("cat");
977 FILE *fp1
= (FILE *) NULL
;
978 FILE *fp2
= (FILE *) NULL
;
979 FILE *fp3
= (FILE *) NULL
;
980 // Open the inputs and outputs
982 if ((fp1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
||
983 (fp2
= fopen (wxUnix2MacFilename( file2
), "rb")) == NULL
||
984 (fp3
= fopen (wxUnix2MacFilename( outfile
), "wb")) == NULL
)
986 if ((fp1
= wxFopen (WXSTRINGCAST file1
, wxT("rb"))) == NULL
||
987 (fp2
= wxFopen (WXSTRINGCAST file2
, wxT("rb"))) == NULL
||
988 (fp3
= wxFopen (outfile
, wxT("wb"))) == NULL
)
1001 while ((ch
= getc (fp1
)) != EOF
)
1002 (void) putc (ch
, fp3
);
1005 while ((ch
= getc (fp2
)) != EOF
)
1006 (void) putc (ch
, fp3
);
1010 bool result
= wxRenameFile(outfile
, file3
);
1017 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
1024 if ((fd1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
)
1026 if ((fd2
= fopen (wxUnix2MacFilename( file2
), "wb")) == NULL
)
1028 if ((fd1
= wxFopen (WXSTRINGCAST file1
, wxT("rb"))) == NULL
)
1030 if ((fd2
= wxFopen (WXSTRINGCAST file2
, wxT("wb"))) == NULL
)
1037 while ((ch
= getc (fd1
)) != EOF
)
1038 (void) putc (ch
, fd2
);
1046 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1049 if (0 == rename (wxUnix2MacFilename( file1
), wxUnix2MacFilename( file2
)))
1052 // Normal system call
1053 if (0 == rename (wxFNSTRINGCAST file1
.fn_str(), wxFNSTRINGCAST file2
.fn_str()))
1057 if (wxCopyFile(file1
, file2
)) {
1058 wxRemoveFile(file1
);
1065 bool wxRemoveFile(const wxString
& file
)
1067 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1068 int flag
= remove(wxFNSTRINGCAST file
.fn_str());
1069 #elif defined( __WXMAC__ )
1070 int flag
= unlink(wxUnix2MacFilename( file
));
1072 int flag
= unlink(wxFNSTRINGCAST file
.fn_str());
1074 return (flag
== 0) ;
1077 bool wxMkdir(const wxString
& dir
, int perm
)
1079 #if defined( __WXMAC__ )
1080 return (mkdir(wxUnix2MacFilename( dir
) , 0 ) == 0);
1082 const wxChar
*dirname
= dir
.c_str();
1084 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1085 // for the GNU compiler
1086 #if (!(defined(__WXMSW__) || defined(__OS2__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1087 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1088 #else // !MSW and !OS/2 VAC++
1089 if ( mkdir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1092 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1101 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1104 return FALSE
; //to be changed since rmdir exists in VMS7.x
1105 #elif defined( __WXMAC__ )
1106 return (rmdir(wxUnix2MacFilename( dir
)) == 0);
1110 return FALSE
; // What to do?
1112 return (rmdir(wxFNSTRINGCAST dir
.fn_str()) == 0);
1119 bool wxDirExists(const wxString
& dir
)
1122 return FALSE
; //To be changed since stat exists in VMS7.x
1123 #elif !defined(__WXMSW__)
1125 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1128 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1129 #if defined(__WIN32__)
1130 WIN32_FIND_DATA fileInfo
;
1133 struct ffblk fileInfo
;
1135 struct find_t fileInfo
;
1139 #if defined(__WIN32__)
1140 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1142 if (h
==INVALID_HANDLE_VALUE
)
1146 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1149 // In Borland findfirst has a different argument
1150 // ordering from _dos_findfirst. But _dos_findfirst
1151 // _should_ be ok in both MS and Borland... why not?
1153 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1155 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1164 // does the path exists? (may have or not '/' or '\\' at the end)
1165 bool wxPathExists(const wxChar
*pszPathName
)
1167 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1168 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1169 wxString
strPath(pszPathName
);
1170 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != wxT('\0') )
1171 strPath
.Last() = wxT('\0');
1179 return stat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1182 // Get a temporary filename, opening and closing the file.
1183 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1189 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1191 wxChar tmp
[MAX_PATH
];
1192 wxChar tmpPath
[MAX_PATH
];
1193 ::GetTempPath(MAX_PATH
, tmpPath
);
1194 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1196 if (buf
) wxStrcpy(buf
, tmp
);
1197 else buf
= copystring(tmp
);
1201 static short last_temp
= 0; // cache last to speed things a bit
1202 // At most 1000 temp files to a process! We use a ring count.
1203 wxChar tmp
[100]; // FIXME static buffer
1205 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1207 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1208 if (!wxFileExists( tmp
))
1210 // Touch the file to create it (reserve name)
1211 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1216 wxStrcpy( buf
, tmp
);
1218 buf
= copystring( tmp
);
1222 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1223 if (buf
) buf
[0] = 0;
1224 return (wxChar
*) NULL
;
1228 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1231 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1240 // Get first file name matching given wild card.
1244 // Get first file name matching given wild card.
1245 // Flags are reserved for future use.
1247 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1248 static DIR *gs_dirStream
= (DIR *) NULL
;
1249 static wxString gs_strFileSpec
;
1250 static int gs_findFlags
= 0;
1253 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1257 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1259 closedir(gs_dirStream
); // edz 941103: better housekeping
1261 gs_findFlags
= flags
;
1263 gs_strFileSpec
= spec
;
1265 // Find path only so we can concatenate
1266 // found file onto path
1267 wxString
path(wxPathOnly(gs_strFileSpec
));
1269 // special case: path is really "/"
1270 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1272 // path is empty => Local directory
1276 gs_dirStream
= opendir(path
.fn_str());
1277 if ( !gs_dirStream
)
1279 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1284 result
= wxFindNextFile();
1286 #endif // !VMS6.x or earlier
1291 wxString
wxFindNextFile()
1295 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1296 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1298 // Find path only so we can concatenate
1299 // found file onto path
1300 wxString
path(wxPathOnly(gs_strFileSpec
));
1301 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1303 /* MATTHEW: special case: path is really "/" */
1304 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1308 struct dirent
*nextDir
;
1309 for ( nextDir
= readdir(gs_dirStream
);
1311 nextDir
= readdir(gs_dirStream
) )
1313 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1314 strcmp(nextDir
->d_name
, ".") &&
1315 strcmp(nextDir
->d_name
, "..") )
1318 if ( !path
.IsEmpty() )
1321 if ( path
!= wxT('/') )
1325 result
+= nextDir
->d_name
;
1327 // Only return "." and ".." when they match
1329 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1330 (strcmp(nextDir
->d_name
, "..") == 0))
1332 if ( (gs_findFlags
& wxDIR
) != 0 )
1338 isdir
= wxDirExists(result
);
1340 // and only return directories when flags & wxDIR
1341 if ( !gs_findFlags
||
1342 ((gs_findFlags
& wxDIR
) && isdir
) ||
1343 ((gs_findFlags
& wxFILE
) && !isdir
) )
1350 result
.Empty(); // not found
1352 closedir(gs_dirStream
);
1353 gs_dirStream
= (DIR *) NULL
;
1354 #endif // !VMS6.2 or earlier
1359 #elif defined(__WXMAC__)
1361 struct MacDirectoryIterator
1369 static int g_iter_flags
;
1371 static MacDirectoryIterator g_iter
;
1373 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1377 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1379 // Find path only so we can concatenate found file onto path
1380 wxString
path(wxPathOnly(spec
));
1381 if ( !path
.IsEmpty() )
1382 result
<< path
<< wxT('\\');
1386 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1387 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1388 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1389 g_iter
.m_index
= 0 ;
1392 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1394 return wxEmptyString
;
1396 return wxFindNextFile( ) ;
1399 wxString
wxFindNextFile()
1405 while ( err
== noErr
)
1408 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1409 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1410 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1414 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1417 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1425 return wxEmptyString
;
1429 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1434 return wxMacFSSpec2UnixFilename( &spec
) ;
1437 #elif defined(__WXMSW__)
1440 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1441 static WIN32_FIND_DATA gs_findDataStruct
;
1444 static struct ffblk gs_findDataStruct
;
1446 static struct _find_t gs_findDataStruct
;
1450 static wxString gs_strFileSpec
;
1451 static int gs_findFlags
= 0;
1453 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1457 gs_strFileSpec
= spec
;
1458 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1460 // Find path only so we can concatenate found file onto path
1461 wxString
path(wxPathOnly(gs_strFileSpec
));
1462 if ( !path
.IsEmpty() )
1463 result
<< path
<< wxT('\\');
1466 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1467 FindClose(gs_hFileStruct
);
1469 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1471 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1478 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1480 if (isdir
&& !(flags
& wxDIR
))
1481 return wxFindNextFile();
1482 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1483 return wxFindNextFile();
1485 result
+= gs_findDataStruct
.cFileName
;
1489 int flag
= _A_NORMAL
;
1490 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1494 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1496 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1499 /* MATTHEW: [5] Check directory flag */
1503 attrib
= gs_findDataStruct
.ff_attrib
;
1505 attrib
= gs_findDataStruct
.attrib
;
1508 if (attrib
& _A_SUBDIR
) {
1509 if (!(gs_findFlags
& wxDIR
))
1510 return wxFindNextFile();
1511 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1512 return wxFindNextFile();
1516 gs_findDataStruct
.ff_name
1518 gs_findDataStruct
.name
1528 wxString
wxFindNextFile()
1532 // Find path only so we can concatenate found file onto path
1533 wxString
path(wxPathOnly(gs_strFileSpec
));
1538 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1541 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1544 FindClose(gs_hFileStruct
);
1545 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1549 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1551 if (isdir
&& !(gs_findFlags
& wxDIR
))
1553 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1556 if ( !path
.IsEmpty() )
1557 result
<< path
<< wxT('\\');
1558 result
<< gs_findDataStruct
.cFileName
;
1565 if (findnext(&gs_findDataStruct
) == 0)
1567 if (_dos_findnext(&gs_findDataStruct
) == 0)
1570 /* MATTHEW: [5] Check directory flag */
1574 attrib
= gs_findDataStruct
.ff_attrib
;
1576 attrib
= gs_findDataStruct
.attrib
;
1579 if (attrib
& _A_SUBDIR
) {
1580 if (!(gs_findFlags
& wxDIR
))
1582 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1588 gs_findDataStruct
.ff_name
1590 gs_findDataStruct
.name
1599 #elif defined(__WXPM__)
1601 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1606 // TODO: figure something out here for OS/2
1607 gs_strFileSpec = spec;
1608 gs_findFlags = flags;
1610 // Find path only so we can concatenate found file onto path
1611 wxString path(wxPathOnly(gs_strFileSpec));
1612 if ( !path.IsEmpty() )
1613 result << path << wxT('\\');
1615 int flag = _A_NORMAL;
1619 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1622 attrib = gs_findDataStruct.attrib;
1624 if (attrib & _A_SUBDIR) {
1625 if (!(gs_findFlags & wxDIR))
1626 return wxFindNextFile();
1627 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1628 return wxFindNextFile();
1630 result += gs_findDataStruct.name;
1636 wxString
wxFindNextFile()
1643 #endif // Unix/Windows/OS/2
1645 // Get current working directory.
1646 // If buf is NULL, allocates space using new, else
1648 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1651 buf
= new wxChar
[sz
+1];
1653 char *cbuf
= new char[sz
+1];
1655 if (_getcwd(cbuf
, sz
) == NULL
) {
1656 #elif defined( __WXMAC__)
1659 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1663 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1664 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1665 strcpy( buf
, res
) ;
1668 if (getcwd(cbuf
, sz
) == NULL
) {
1673 if (_getcwd(buf
, sz
) == NULL
) {
1674 #elif defined( __WXMAC__)
1677 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1681 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1682 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1683 strcpy( buf
, res
) ;
1686 if (getcwd(buf
, sz
) == NULL
) {
1694 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1703 static const size_t maxPathLen
= 1024;
1706 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1707 str
.UngetWriteBuf();
1712 bool wxSetWorkingDirectory(const wxString
& d
)
1714 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1715 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1716 #elif defined(__WINDOWS__)
1719 return (bool)(SetCurrentDirectory(d
) != 0);
1721 // Must change drive, too.
1722 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1725 wxChar firstChar
= d
[0];
1729 firstChar
= firstChar
- 32;
1731 // To a drive number
1732 unsigned int driveNo
= firstChar
- 64;
1735 unsigned int noDrives
;
1736 _dos_setdrive(driveNo
, &noDrives
);
1739 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1747 // Get the OS directory if appropriate (such as the Windows directory).
1748 // On non-Windows platform, probably just return the empty string.
1749 wxString
wxGetOSDirectory()
1753 GetWindowsDirectory(buf
, 256);
1754 return wxString(buf
);
1756 return wxEmptyString
;
1760 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1762 size_t len
= wxStrlen(pszFileName
);
1766 return wxIsPathSeparator(pszFileName
[len
- 1]);
1769 // find a file in a list of directories, returns false if not found
1770 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1772 // we assume that it's not empty
1773 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1774 _("empty file name in wxFindFileInPath"));
1776 // skip path separator in the beginning of the file name if present
1777 if ( wxIsPathSeparator(*pszFile
) )
1780 // copy the path (strtok will modify it)
1781 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1782 wxStrcpy(szPath
, pszPath
);
1785 wxChar
*pc
, *save_ptr
;
1786 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1788 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1790 // search for the file in this directory
1792 if ( !wxEndsWithPathSeparator(pc
) )
1793 strFile
+= wxFILE_SEP_PATH
;
1796 if ( FileExists(strFile
) ) {
1802 // suppress warning about unused variable save_ptr when wxStrtok() is a
1803 // macro which throws away its third argument
1808 return pc
!= NULL
; // if true => we breaked from the loop
1811 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1816 // it can be empty, but it shouldn't be NULL
1817 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1819 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1822 // under Windows we understand both separators
1823 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1824 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1825 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1826 #else // assume Unix
1827 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1831 if ( (pDot
== pszFileName
) || (*(pDot
- 1) == wxFILE_SEP_PATH_UNIX
) )
1833 // under Unix, dot may be (and commonly is) the first character of the
1834 // filename, don't treat the entire filename as extension in this case
1840 if ( pDot
&& (pDot
< pLastSeparator
) )
1842 // the dot is part of the path, not the start of the extension
1848 if ( pLastSeparator
)
1849 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1856 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1857 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1859 *pstrName
= wxString(start
, end
- start
);
1865 *pstrExt
= wxString(pDot
+ 1);
1873 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1877 stat(filename
.fn_str(), &buf
);
1878 return buf
.st_mtime
;
1882 //------------------------------------------------------------------------
1883 // wild character routines
1884 //------------------------------------------------------------------------
1886 bool wxIsWild( const wxString
& pattern
)
1888 wxString tmp
= pattern
;
1889 wxChar
*pat
= WXSTRINGCAST(tmp
);
1892 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1902 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1904 #if defined(HAVE_FNMATCH_H)
1906 // this probably won't work well for multibyte chars in Unicode mode?
1908 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1910 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1914 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1917 * WARNING: this code is broken!
1920 wxString tmp1
= pat
;
1921 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1922 wxString tmp2
= text
;
1923 wxChar
*str
= WXSTRINGCAST(tmp2
);
1926 bool done
= FALSE
, ret_code
, ok
;
1927 // Below is for vi fans
1928 const wxChar OB
= wxT('{'), CB
= wxT('}');
1930 // dot_special means '.' only matches '.'
1931 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1934 while ((*pattern
!= wxT('\0')) && (!done
)
1935 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1939 if (*pattern
!= wxT('\0'))
1945 while ((*str
!=wxT('\0'))
1946 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1949 while (*str
!= wxT('\0'))
1951 while (*pattern
!= wxT('\0'))
1958 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1962 if (*pattern
== wxT('\\')) {
1964 if (*pattern
== wxT('\0')) {
1969 if (*(pattern
+ 1) == wxT('-')) {
1972 if (*pattern
== wxT(']')) {
1976 if (*pattern
== wxT('\\')) {
1978 if (*pattern
== wxT('\0')) {
1983 if ((*str
< c
) || (*str
> *pattern
)) {
1987 } else if (*pattern
!= *str
) {
1992 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1993 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1997 if (*pattern
!= wxT('\0')) {
2007 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2010 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
2011 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
2012 if (*pattern
== wxT('\\'))
2014 ok
= (*pattern
++ == *cp
++);
2016 if (*pattern
== wxT('\0')) {
2022 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2023 if (*++pattern
== wxT('\\')) {
2024 if (*++pattern
== CB
)
2029 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2030 if (*++pattern
== wxT('\\')) {
2031 if (*++pattern
== CB
|| *pattern
== wxT(','))
2036 if (*pattern
!= wxT('\0'))
2041 if (*str
== *pattern
) {
2048 while (*pattern
== wxT('*'))
2050 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2056 #pragma warning(default:4706) // assignment within conditional expression