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 char *wxBuffer
;
119 #include "morefile.h"
120 #include "moreextr.h"
121 #include "fullpath.h"
122 #include "fspcompa.h"
125 #if !USE_SHARED_LIBRARIES
126 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
129 // ----------------------------------------------------------------------------
131 // ----------------------------------------------------------------------------
133 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
135 // ============================================================================
137 // ============================================================================
139 void wxPathList::Add (const wxString
& path
)
141 wxStringList::Add (WXSTRINGCAST path
);
144 // Add paths e.g. from the PATH environment variable
145 void wxPathList::AddEnvList (const wxString
& envVariable
)
147 static const wxChar PATH_TOKS
[] =
149 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
154 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
157 wxChar
*s
= copystring (val
);
158 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
162 Add (copystring (token
));
165 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
166 Add (wxString(token
));
170 // suppress warning about unused variable save_ptr when wxStrtok() is a
171 // macro which throws away its third argument
178 // Given a full filename (with path), ensure that that file can
179 // be accessed again USING FILENAME ONLY by adding the path
180 // to the list if not already there.
181 void wxPathList::EnsureFileAccessible (const wxString
& path
)
183 wxString
path_only(wxPathOnly(path
));
184 if ( !path_only
.IsEmpty() )
186 if ( !Member(path_only
) )
191 bool wxPathList::Member (const wxString
& path
)
193 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
195 wxString
path2((wxChar
*) node
->Data ());
197 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
199 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
201 // Case sensitive File System
202 path
.CompareTo (path2
) == 0
210 wxString
wxPathList::FindValidPath (const wxString
& file
)
212 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
213 return wxString(wxFileFunctionsBuffer
);
215 wxChar buf
[_MAXPATHLEN
];
216 wxStrcpy(buf
, wxFileFunctionsBuffer
);
218 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
219 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
221 for (wxNode
* node
= First (); node
; node
= node
->Next ())
223 wxChar
*path
= (wxChar
*) node
->Data ();
224 wxStrcpy (wxFileFunctionsBuffer
, path
);
225 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
226 if (ch
!= wxT('\\') && ch
!= wxT('/'))
227 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
228 wxStrcat (wxFileFunctionsBuffer
, filename
);
230 Unix2DosFilename (wxFileFunctionsBuffer
);
232 if (wxFileExists (wxFileFunctionsBuffer
))
234 return wxString(wxFileFunctionsBuffer
); // Found!
238 return wxString(wxT("")); // Not found
241 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
243 wxString f
= FindValidPath(file
);
244 if ( wxIsAbsolutePath(f
) )
248 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
250 if ( !wxEndsWithPathSeparator(buf
) )
252 buf
+= wxFILE_SEP_PATH
;
260 wxFileExists (const wxString
& filename
)
262 #ifdef __GNUWIN32__ // (fix a B20 bug)
263 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
267 #elif defined(__WXMAC__)
269 if (filename
&& stat (wxUnix2MacFilename(filename
), &stbuf
) == 0 )
280 if ((filename
!= wxT("")) && stat (wxFNSTRINGCAST filename
.fn_str(), &stbuf
) == 0)
286 /* Vadim's alternative implementation
288 // does the file exist?
289 bool wxFileExists(const char *pszFileName)
292 return !access(pszFileName, 0) &&
293 !stat(pszFileName, &st) &&
294 (st.st_mode & S_IFREG);
299 wxIsAbsolutePath (const wxString
& filename
)
301 if (filename
!= wxT(""))
303 if (filename
[0] == wxT('/')
305 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
309 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
318 * Strip off any extension (dot something) from end of file,
319 * IF one exists. Inserts zero into buffer.
323 void wxStripExtension(wxChar
*buffer
)
325 int len
= wxStrlen(buffer
);
329 if (buffer
[i
] == wxT('.'))
338 void wxStripExtension(wxString
& buffer
)
340 size_t len
= buffer
.Length();
344 if (buffer
.GetChar(i
) == wxT('.'))
346 buffer
= buffer
.Left(i
);
353 // Destructive removal of /./ and /../ stuff
354 wxChar
*wxRealPath (wxChar
*path
)
357 static const wxChar SEP
= wxT('\\');
358 Unix2DosFilename(path
);
360 static const wxChar SEP
= wxT('/');
362 if (path
[0] && path
[1]) {
363 /* MATTHEW: special case "/./x" */
365 if (path
[2] == SEP
&& path
[1] == wxT('.'))
373 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
376 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
377 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
378 && (q
- 1 <= path
|| q
[-1] != SEP
))
381 if (path
[0] == wxT('\0'))
387 /* Check that path[2] is NULL! */
388 else if (path
[1] == wxT(':') && !path
[2])
397 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
406 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
408 if (filename
== wxT(""))
409 return (wxChar
*) NULL
;
411 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
412 wxChar buf
[_MAXPATHLEN
];
414 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
415 wxChar ch
= buf
[wxStrlen(buf
) - 1];
417 if (ch
!= wxT('\\') && ch
!= wxT('/'))
418 wxStrcat(buf
, wxT("\\"));
421 wxStrcat(buf
, wxT("/"));
423 wxStrcat(buf
, wxFileFunctionsBuffer
);
424 return copystring( wxRealPath(buf
) );
426 return copystring( wxFileFunctionsBuffer
);
432 ~user/ => user's home dir
433 If the environment variable a = "foo" and b = "bar" then:
450 /* input name in name, pathname output to buf. */
452 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
454 register wxChar
*d
, *s
, *nm
;
455 wxChar lnm
[_MAXPATHLEN
];
458 // Some compilers don't like this line.
459 // const wxChar trimchars[] = wxT("\n \t");
462 trimchars
[0] = wxT('\n');
463 trimchars
[1] = wxT(' ');
464 trimchars
[2] = wxT('\t');
468 const wxChar SEP
= wxT('\\');
470 const wxChar SEP
= wxT('/');
473 if (name
== NULL
|| *name
== wxT('\0'))
475 nm
= copystring(name
); // Make a scratch copy
478 /* Skip leading whitespace and cr */
479 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
481 /* And strip off trailing whitespace and cr */
482 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
483 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
491 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
494 /* Expand inline environment variables */
512 while ((*d
++ = *s
)) {
514 if (*s
== wxT('\\')) {
515 if ((*(d
- 1) = *++s
)) {
524 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
526 if (*s
++ == wxT('$'))
529 register wxChar
*start
= d
;
530 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
531 register wxChar
*value
;
533 // VA gives assignment in logical expr warning
539 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
544 value
= wxGetenv(braces
? start
+ 1 : start
);
547 // VA gives assignment in logical expr warning
548 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
550 for ((d
= start
- 1); (*d
++ = *value
++););
559 /* Expand ~ and ~user */
562 if (nm
[0] == wxT('~') && !q
)
565 if (nm
[1] == SEP
|| nm
[1] == 0)
567 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
568 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
573 { /* ~user/filename */
574 register wxChar
*nnm
;
575 register wxChar
*home
;
576 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
577 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
578 was_sep
= (*s
== SEP
);
579 nnm
= *s
? s
+ 1 : s
;
581 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
582 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
583 if (was_sep
) /* replace only if it was there: */
594 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
596 while (wxT('\0') != (*d
++ = *s
++))
599 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
604 // VA gives assignment in logical expr warning
608 while ((*d
++ = *s
++));
610 delete[] nm_tmp
; // clean up alloc
611 /* Now clean up the buffer */
612 return wxRealPath(buf
);
616 /* Contract Paths to be build upon an environment variable
619 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
621 The call wxExpandPath can convert these back!
624 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
626 static wxChar dest
[_MAXPATHLEN
];
628 if (filename
== wxT(""))
629 return (wxChar
*) NULL
;
631 wxStrcpy (dest
, WXSTRINGCAST filename
);
633 Unix2DosFilename(dest
);
636 // Handle environment
637 const wxChar
*val
= (const wxChar
*) NULL
;
638 wxChar
*tcp
= (wxChar
*) NULL
;
639 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
640 (tcp
= wxStrstr (dest
, val
)) != NULL
)
642 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
645 wxStrcpy (tcp
, WXSTRINGCAST envname
);
646 wxStrcat (tcp
, wxT("}"));
647 wxStrcat (tcp
, wxFileFunctionsBuffer
);
650 // Handle User's home (ignore root homes!)
652 if ((val
= wxGetUserHome (user
)) != NULL
&&
653 (len
= wxStrlen(val
)) > 2 &&
654 wxStrncmp(dest
, val
, len
) == 0)
656 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
658 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
660 // strcat(wxFileFunctionsBuffer, "\\");
662 // strcat(wxFileFunctionsBuffer, "/");
664 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
665 wxStrcpy (dest
, wxFileFunctionsBuffer
);
671 // Return just the filename, not the path
673 wxChar
*wxFileNameFromPath (wxChar
*path
)
677 register wxChar
*tcp
;
679 tcp
= path
+ wxStrlen (path
);
680 while (--tcp
>= path
)
682 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
684 || *tcp
== wxT(':') || *tcp
== wxT(']'))
690 #if defined(__WXMSW__) || defined(__WXPM__)
691 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
698 wxString
wxFileNameFromPath (const wxString
& path1
)
700 if (path1
!= wxT(""))
703 wxChar
*path
= WXSTRINGCAST path1
;
704 register wxChar
*tcp
;
706 tcp
= path
+ wxStrlen (path
);
707 while (--tcp
>= path
)
709 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
711 || *tcp
== wxT(':') || *tcp
== wxT(']'))
715 return wxString(tcp
+ 1);
717 #if defined(__WXMSW__) || defined(__WXPM__)
718 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
719 return wxString(path
+ 2);
722 // Yes, this should return the path, not an empty string, otherwise
723 // we get "thing.txt" -> "".
727 // Return just the directory, or NULL if no directory
729 wxPathOnly (wxChar
*path
)
733 static wxChar buf
[_MAXPATHLEN
];
736 wxStrcpy (buf
, path
);
738 int l
= wxStrlen(path
);
743 // Search backward for a backward or forward slash
744 while (!done
&& i
> -1)
747 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
761 #if defined(__WXMSW__) || defined(__WXPM__)
762 // Try Drive specifier
763 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
765 // A:junk --> A:. (since A:.\junk Not A:\junk)
773 return (wxChar
*) NULL
;
776 // Return just the directory, or NULL if no directory
777 wxString
wxPathOnly (const wxString
& path
)
781 wxChar buf
[_MAXPATHLEN
];
784 wxStrcpy (buf
, WXSTRINGCAST path
);
786 int l
= path
.Length();
791 // Search backward for a backward or forward slash
792 while (!done
&& i
> -1)
795 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
804 return wxString(buf
);
809 #if defined(__WXMSW__) || defined(__WXPM__)
810 // Try Drive specifier
811 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
813 // A:junk --> A:. (since A:.\junk Not A:\junk)
816 return wxString(buf
);
821 return wxString(wxT(""));
824 // Utility for converting delimiters in DOS filenames to UNIX style
825 // and back again - or we get nasty problems with delimiters.
826 // Also, convert to lower case, since case is significant in UNIX.
830 static char sMacFileNameConversion
[ 1000 ] ;
832 wxString
wxMac2UnixFilename (const char *str
)
834 char *s
= sMacFileNameConversion
;
838 memmove( s
+1 , s
,strlen( s
) + 1) ;
849 *s
= wxTolower (*s
); // Case INDEPENDENT
853 return wxString (sMacFileNameConversion
) ;
856 wxString
wxUnix2MacFilename (const char *str
)
858 char *s
= sMacFileNameConversion
;
864 // relative path , since it goes on with slash which is translated to a :
865 memmove( s
, s
+1 ,strlen( s
) ) ;
867 else if ( *s
== '/' )
869 // absolute path -> on mac just start with the drive name
870 memmove( s
, s
+1 ,strlen( s
) ) ;
874 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
878 if (*s
== '/' || *s
== '\\')
880 // convert any back-directory situations
881 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
884 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
893 return wxString (sMacFileNameConversion
) ;
896 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
901 FSpGetFullPath( spec
, &length
, &myPath
) ;
902 ::SetHandleSize( myPath
, length
+ 1 ) ;
904 (*myPath
)[length
] = 0 ;
905 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
906 (*myPath
)[length
-1] = 0 ;
908 wxString
result( (char*) *myPath
) ;
909 ::HUnlock( myPath
) ;
910 ::DisposeHandle( myPath
) ;
914 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
916 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
919 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
921 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
924 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
926 wxString var
= wxUnix2MacFilename( path
) ;
927 wxMacFilename2FSSpec( var
, spec
) ;
932 wxDos2UnixFilename (char *s
)
941 *s
= wxTolower (*s
); // Case INDEPENDENT
948 #if defined(__WXMSW__) || defined(__WXPM__)
949 wxUnix2DosFilename (char *s
)
951 wxUnix2DosFilename (char *WXUNUSED(s
) )
954 // Yes, I really mean this to happen under DOS only! JACS
955 #if defined(__WXMSW__) || defined(__WXPM__)
966 // Concatenate two files to form third
968 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
970 wxChar
*outfile
= wxGetTempFileName("cat");
972 FILE *fp1
= (FILE *) NULL
;
973 FILE *fp2
= (FILE *) NULL
;
974 FILE *fp3
= (FILE *) NULL
;
975 // Open the inputs and outputs
977 if ((fp1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
||
978 (fp2
= fopen (wxUnix2MacFilename( file2
), "rb")) == NULL
||
979 (fp3
= fopen (wxUnix2MacFilename( outfile
), "wb")) == NULL
)
981 if ((fp1
= fopen (WXSTRINGCAST file1
, "rb")) == NULL
||
982 (fp2
= fopen (WXSTRINGCAST file2
, "rb")) == NULL
||
983 (fp3
= fopen (outfile
, "wb")) == NULL
)
996 while ((ch
= getc (fp1
)) != EOF
)
997 (void) putc (ch
, fp3
);
1000 while ((ch
= getc (fp2
)) != EOF
)
1001 (void) putc (ch
, fp3
);
1005 bool result
= wxRenameFile(outfile
, file3
);
1012 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
1019 if ((fd1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
)
1021 if ((fd2
= fopen (wxUnix2MacFilename( file2
), "wb")) == NULL
)
1023 if ((fd1
= fopen (WXSTRINGCAST file1
, "rb")) == NULL
)
1025 if ((fd2
= fopen (WXSTRINGCAST file2
, "wb")) == NULL
)
1032 while ((ch
= getc (fd1
)) != EOF
)
1033 (void) putc (ch
, fd2
);
1041 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1044 if (0 == rename (wxUnix2MacFilename( file1
), wxUnix2MacFilename( file2
)))
1047 // Normal system call
1048 if (0 == rename (wxFNSTRINGCAST file1
.fn_str(), wxFNSTRINGCAST file2
.fn_str()))
1052 if (wxCopyFile(file1
, file2
)) {
1053 wxRemoveFile(file1
);
1060 bool wxRemoveFile(const wxString
& file
)
1062 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1063 int flag
= remove(wxFNSTRINGCAST file
.fn_str());
1064 #elif defined( __WXMAC__ )
1065 int flag
= unlink(wxUnix2MacFilename( file
));
1067 int flag
= unlink(wxFNSTRINGCAST file
.fn_str());
1069 return (flag
== 0) ;
1072 bool wxMkdir(const wxString
& dir
, int perm
)
1074 #if defined( __WXMAC__ )
1075 return (mkdir(wxUnix2MacFilename( dir
) , 0 ) == 0);
1077 const wxChar
*dirname
= dir
.c_str();
1079 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1080 // for the GNU compiler
1081 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1082 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1083 #else // MSW and OS/2
1084 if ( mkdir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1087 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1096 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1099 return FALSE
; //to be changed since rmdir exists in VMS7.x
1100 #elif defined( __WXMAC__ )
1101 return (rmdir(wxUnix2MacFilename( dir
)) == 0);
1105 return FALSE
; // What to do?
1107 return (rmdir(wxFNSTRINGCAST dir
.fn_str()) == 0);
1114 bool wxDirExists(const wxString
& dir
)
1117 return FALSE
; //To be changed since stat exists in VMS7.x
1118 #elif !defined(__WXMSW__)
1120 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1123 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1124 #if defined(__WIN32__)
1125 WIN32_FIND_DATA fileInfo
;
1128 struct ffblk fileInfo
;
1130 struct find_t fileInfo
;
1134 #if defined(__WIN32__)
1135 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1137 if (h
==INVALID_HANDLE_VALUE
)
1141 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1144 // In Borland findfirst has a different argument
1145 // ordering from _dos_findfirst. But _dos_findfirst
1146 // _should_ be ok in both MS and Borland... why not?
1148 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1150 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1159 // does the path exists? (may have or not '/' or '\\' at the end)
1160 bool wxPathExists(const wxChar
*pszPathName
)
1162 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1163 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1164 wxString
strPath(pszPathName
);
1165 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != wxT('\0') )
1166 strPath
.Last() = wxT('\0');
1174 return stat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1177 // Get a temporary filename, opening and closing the file.
1178 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1184 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1186 wxChar tmp
[MAX_PATH
];
1187 wxChar tmpPath
[MAX_PATH
];
1188 ::GetTempPath(MAX_PATH
, tmpPath
);
1189 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1191 if (buf
) wxStrcpy(buf
, tmp
);
1192 else buf
= copystring(tmp
);
1196 static short last_temp
= 0; // cache last to speed things a bit
1197 // At most 1000 temp files to a process! We use a ring count.
1198 wxChar tmp
[100]; // FIXME static buffer
1200 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1202 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1203 if (!wxFileExists( tmp
))
1205 // Touch the file to create it (reserve name)
1206 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1211 wxStrcpy( buf
, tmp
);
1213 buf
= copystring( tmp
);
1217 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1218 if (buf
) buf
[0] = 0;
1219 return (wxChar
*) NULL
;
1223 // Get first file name matching given wild card.
1227 // Get first file name matching given wild card.
1228 // Flags are reserved for future use.
1230 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1231 static DIR *gs_dirStream
= (DIR *) NULL
;
1232 static wxString gs_strFileSpec
;
1233 static int gs_findFlags
= 0;
1236 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1240 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1242 closedir(gs_dirStream
); // edz 941103: better housekeping
1244 gs_findFlags
= flags
;
1246 gs_strFileSpec
= spec
;
1248 // Find path only so we can concatenate
1249 // found file onto path
1250 wxString
path(wxPathOnly(gs_strFileSpec
));
1252 // special case: path is really "/"
1253 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1255 // path is empty => Local directory
1259 gs_dirStream
= opendir(path
.fn_str());
1260 if ( !gs_dirStream
)
1262 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1267 result
= wxFindNextFile();
1269 #endif // !VMS6.x or earlier
1274 wxString
wxFindNextFile()
1278 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1279 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1281 // Find path only so we can concatenate
1282 // found file onto path
1283 wxString
path(wxPathOnly(gs_strFileSpec
));
1284 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1286 /* MATTHEW: special case: path is really "/" */
1287 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1291 struct dirent
*nextDir
;
1292 for ( nextDir
= readdir(gs_dirStream
);
1294 nextDir
= readdir(gs_dirStream
) )
1296 if (wxMatchWild(name
, nextDir
->d_name
))
1299 if ( !path
.IsEmpty() )
1302 if ( path
!= wxT('/') )
1306 result
+= nextDir
->d_name
;
1308 // Only return "." and ".." when they match
1310 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1311 (strcmp(nextDir
->d_name
, "..") == 0))
1313 if ( (gs_findFlags
& wxDIR
) != 0 )
1319 isdir
= wxDirExists(result
);
1321 // and only return directories when flags & wxDIR
1322 if ( !gs_findFlags
||
1323 ((gs_findFlags
& wxDIR
) && isdir
) ||
1324 ((gs_findFlags
& wxFILE
) && !isdir
) )
1331 result
.Empty(); // not found
1333 closedir(gs_dirStream
);
1334 gs_dirStream
= (DIR *) NULL
;
1335 #endif // !VMS6.2 or earlier
1340 #elif defined(__WXMAC__)
1342 struct MacDirectoryIterator
1350 static int g_iter_flags
;
1352 static MacDirectoryIterator g_iter
;
1354 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1358 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1360 // Find path only so we can concatenate found file onto path
1361 wxString
path(wxPathOnly(spec
));
1362 if ( !path
.IsEmpty() )
1363 result
<< path
<< wxT('\\');
1367 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1368 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1369 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1370 g_iter
.m_index
= 0 ;
1373 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1375 return wxEmptyString
;
1377 return wxFindNextFile( ) ;
1380 wxString
wxFindNextFile()
1386 while ( err
== noErr
)
1389 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1390 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1391 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1395 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1398 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1406 return wxEmptyString
;
1410 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1415 return wxMacFSSpec2UnixFilename( &spec
) ;
1418 #elif defined(__WXMSW__)
1421 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1422 static WIN32_FIND_DATA gs_findDataStruct
;
1425 static struct ffblk gs_findDataStruct
;
1427 static struct _find_t gs_findDataStruct
;
1431 static wxString gs_strFileSpec
;
1432 static int gs_findFlags
= 0;
1434 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1438 gs_strFileSpec
= spec
;
1439 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1441 // Find path only so we can concatenate found file onto path
1442 wxString
path(wxPathOnly(gs_strFileSpec
));
1443 if ( !path
.IsEmpty() )
1444 result
<< path
<< wxT('\\');
1447 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1448 FindClose(gs_hFileStruct
);
1450 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1452 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1459 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1461 if (isdir
&& !(flags
& wxDIR
))
1462 return wxFindNextFile();
1463 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1464 return wxFindNextFile();
1466 result
+= gs_findDataStruct
.cFileName
;
1470 int flag
= _A_NORMAL
;
1471 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1475 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1477 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1480 /* MATTHEW: [5] Check directory flag */
1484 attrib
= gs_findDataStruct
.ff_attrib
;
1486 attrib
= gs_findDataStruct
.attrib
;
1489 if (attrib
& _A_SUBDIR
) {
1490 if (!(gs_findFlags
& wxDIR
))
1491 return wxFindNextFile();
1492 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1493 return wxFindNextFile();
1497 gs_findDataStruct
.ff_name
1499 gs_findDataStruct
.name
1508 wxString
wxFindNextFile()
1512 // Find path only so we can concatenate found file onto path
1513 wxString
path(wxPathOnly(gs_strFileSpec
));
1518 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1521 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1524 FindClose(gs_hFileStruct
);
1525 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1529 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1531 if (isdir
&& !(gs_findFlags
& wxDIR
))
1533 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1536 if ( !path
.IsEmpty() )
1537 result
<< path
<< wxT('\\');
1538 result
<< gs_findDataStruct
.cFileName
;
1545 if (findnext(&gs_findDataStruct
) == 0)
1547 if (_dos_findnext(&gs_findDataStruct
) == 0)
1550 /* MATTHEW: [5] Check directory flag */
1554 attrib
= gs_findDataStruct
.ff_attrib
;
1556 attrib
= gs_findDataStruct
.attrib
;
1559 if (attrib
& _A_SUBDIR
) {
1560 if (!(gs_findFlags
& wxDIR
))
1562 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1568 gs_findDataStruct
.ff_name
1570 gs_findDataStruct
.name
1579 #endif // Unix/Windows
1581 // Get current working directory.
1582 // If buf is NULL, allocates space using new, else
1584 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1587 buf
= new wxChar
[sz
+1];
1589 char *cbuf
= new char[sz
+1];
1591 if (_getcwd(cbuf
, sz
) == NULL
) {
1592 #elif defined( __WXMAC__)
1595 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1599 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1600 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1601 strcpy( buf
, res
) ;
1604 if (getcwd(cbuf
, sz
) == NULL
) {
1609 if (_getcwd(buf
, sz
) == NULL
) {
1610 #elif defined( __WXMAC__)
1613 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1617 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1618 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1619 strcpy( buf
, res
) ;
1622 if (getcwd(buf
, sz
) == NULL
) {
1630 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1639 static const size_t maxPathLen
= 1024;
1642 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1643 str
.UngetWriteBuf();
1648 bool wxSetWorkingDirectory(const wxString
& d
)
1650 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1651 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1652 #elif defined(__WINDOWS__)
1655 return (bool)(SetCurrentDirectory(d
) != 0);
1657 // Must change drive, too.
1658 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1661 wxChar firstChar
= d
[0];
1665 firstChar
= firstChar
- 32;
1667 // To a drive number
1668 unsigned int driveNo
= firstChar
- 64;
1671 unsigned int noDrives
;
1672 _dos_setdrive(driveNo
, &noDrives
);
1675 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1683 // Get the OS directory if appropriate (such as the Windows directory).
1684 // On non-Windows platform, probably just return the empty string.
1685 wxString
wxGetOSDirectory()
1689 GetWindowsDirectory(buf
, 256);
1690 return wxString(buf
);
1692 return wxEmptyString
;
1696 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1698 size_t len
= wxStrlen(pszFileName
);
1702 return wxIsPathSeparator(pszFileName
[len
- 1]);
1705 // find a file in a list of directories, returns false if not found
1706 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1708 // we assume that it's not empty
1709 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1710 _("empty file name in wxFindFileInPath"));
1712 // skip path separator in the beginning of the file name if present
1713 if ( wxIsPathSeparator(*pszFile
) )
1716 // copy the path (strtok will modify it)
1717 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1718 wxStrcpy(szPath
, pszPath
);
1721 wxChar
*pc
, *save_ptr
;
1722 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1724 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1726 // search for the file in this directory
1728 if ( !wxEndsWithPathSeparator(pc
) )
1729 strFile
+= wxFILE_SEP_PATH
;
1732 if ( FileExists(strFile
) ) {
1738 // suppress warning about unused variable save_ptr when wxStrtok() is a
1739 // macro which throws away its third argument
1744 return pc
!= NULL
; // if true => we breaked from the loop
1747 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1752 // it can be empty, but it shouldn't be NULL
1753 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1755 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1758 // under Windows we understand both separators
1759 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1760 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1761 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1762 #else // assume Unix
1763 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1765 if ( pDot
== pszFileName
)
1767 // under Unix files like .profile are treated in a special way
1772 if ( pDot
< pLastSeparator
)
1774 // the dot is part of the path, not the start of the extension
1780 if ( pLastSeparator
)
1781 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1788 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1789 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1791 *pstrName
= wxString(start
, end
- start
);
1797 *pstrExt
= wxString(pDot
+ 1);
1803 //------------------------------------------------------------------------
1804 // wild character routines
1805 //------------------------------------------------------------------------
1807 bool wxIsWild( const wxString
& pattern
)
1809 wxString tmp
= pattern
;
1810 wxChar
*pat
= WXSTRINGCAST(tmp
);
1813 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1823 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1825 #if defined(HAVE_FNMATCH_H)
1827 // this probably won't work well for multibyte chars in Unicode mode?
1829 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1831 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1835 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1838 * WARNING: this code is broken!
1841 wxString tmp1
= pat
;
1842 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1843 wxString tmp2
= text
;
1844 wxChar
*str
= WXSTRINGCAST(tmp2
);
1847 bool done
= FALSE
, ret_code
, ok
;
1848 // Below is for vi fans
1849 const wxChar OB
= wxT('{'), CB
= wxT('}');
1851 // dot_special means '.' only matches '.'
1852 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1855 while ((*pattern
!= wxT('\0')) && (!done
)
1856 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1860 if (*pattern
!= wxT('\0'))
1866 while ((*str
!=wxT('\0'))
1867 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1870 while (*str
!= wxT('\0'))
1872 while (*pattern
!= wxT('\0'))
1879 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1883 if (*pattern
== wxT('\\')) {
1885 if (*pattern
== wxT('\0')) {
1890 if (*(pattern
+ 1) == wxT('-')) {
1893 if (*pattern
== wxT(']')) {
1897 if (*pattern
== wxT('\\')) {
1899 if (*pattern
== wxT('\0')) {
1904 if ((*str
< c
) || (*str
> *pattern
)) {
1908 } else if (*pattern
!= *str
) {
1913 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1914 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1918 if (*pattern
!= wxT('\0')) {
1928 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1931 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1932 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1933 if (*pattern
== wxT('\\'))
1935 ok
= (*pattern
++ == *cp
++);
1937 if (*pattern
== wxT('\0')) {
1943 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1944 if (*++pattern
== wxT('\\')) {
1945 if (*++pattern
== CB
)
1950 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1951 if (*++pattern
== wxT('\\')) {
1952 if (*++pattern
== CB
|| *pattern
== wxT(','))
1957 if (*pattern
!= wxT('\0'))
1962 if (*str
== *pattern
) {
1969 while (*pattern
== wxT('*'))
1971 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1977 #pragma warning(default:4706) // assignment within conditional expression