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 // ============================================================================
135 // ============================================================================
137 void wxPathList::Add (const wxString
& path
)
139 wxStringList::Add (WXSTRINGCAST path
);
142 // Add paths e.g. from the PATH environment variable
143 void wxPathList::AddEnvList (const wxString
& envVariable
)
145 static const wxChar PATH_TOKS
[] =
147 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
152 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
155 wxChar
*s
= copystring (val
);
156 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
160 Add (copystring (token
));
163 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
164 Add (wxString(token
));
168 // suppress warning about unused variable save_ptr when wxStrtok() is a
169 // macro which throws away its third argument
176 // Given a full filename (with path), ensure that that file can
177 // be accessed again USING FILENAME ONLY by adding the path
178 // to the list if not already there.
179 void wxPathList::EnsureFileAccessible (const wxString
& path
)
181 wxString
path_only(wxPathOnly(path
));
182 if ( !path_only
.IsEmpty() )
184 if ( !Member(path_only
) )
189 bool wxPathList::Member (const wxString
& path
)
191 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
193 wxString
path2((wxChar
*) node
->Data ());
195 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
197 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
199 // Case sensitive File System
200 path
.CompareTo (path2
) == 0
208 wxString
wxPathList::FindValidPath (const wxString
& file
)
210 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
211 return wxString(wxFileFunctionsBuffer
);
213 wxChar buf
[_MAXPATHLEN
];
214 wxStrcpy(buf
, wxFileFunctionsBuffer
);
216 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
217 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
219 for (wxNode
* node
= First (); node
; node
= node
->Next ())
221 wxChar
*path
= (wxChar
*) node
->Data ();
222 wxStrcpy (wxFileFunctionsBuffer
, path
);
223 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
224 if (ch
!= wxT('\\') && ch
!= wxT('/'))
225 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
226 wxStrcat (wxFileFunctionsBuffer
, filename
);
228 Unix2DosFilename (wxFileFunctionsBuffer
);
230 if (wxFileExists (wxFileFunctionsBuffer
))
232 return wxString(wxFileFunctionsBuffer
); // Found!
236 return wxString(wxT("")); // Not found
239 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
241 wxString f
= FindValidPath(file
);
242 if ( wxIsAbsolutePath(f
) )
246 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
248 if ( !wxEndsWithPathSeparator(buf
) )
250 buf
+= wxFILE_SEP_PATH
;
258 wxFileExists (const wxString
& filename
)
260 #ifdef __GNUWIN32__ // (fix a B20 bug)
261 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
265 #elif defined(__WXMAC__)
267 if (filename
&& stat (wxUnix2MacFilename(filename
), &stbuf
) == 0 )
278 if ((filename
!= wxT("")) && stat (wxFNSTRINGCAST filename
.fn_str(), &stbuf
) == 0)
284 /* Vadim's alternative implementation
286 // does the file exist?
287 bool wxFileExists(const char *pszFileName)
290 return !access(pszFileName, 0) &&
291 !stat(pszFileName, &st) &&
292 (st.st_mode & S_IFREG);
297 wxIsAbsolutePath (const wxString
& filename
)
299 if (filename
!= wxT(""))
301 if (filename
[0] == wxT('/')
303 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
307 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
316 * Strip off any extension (dot something) from end of file,
317 * IF one exists. Inserts zero into buffer.
321 void wxStripExtension(wxChar
*buffer
)
323 int len
= wxStrlen(buffer
);
327 if (buffer
[i
] == wxT('.'))
336 void wxStripExtension(wxString
& buffer
)
338 size_t len
= buffer
.Length();
342 if (buffer
.GetChar(i
) == wxT('.'))
344 buffer
= buffer
.Left(i
);
351 // Destructive removal of /./ and /../ stuff
352 wxChar
*wxRealPath (wxChar
*path
)
355 static const wxChar SEP
= wxT('\\');
356 Unix2DosFilename(path
);
358 static const wxChar SEP
= wxT('/');
360 if (path
[0] && path
[1]) {
361 /* MATTHEW: special case "/./x" */
363 if (path
[2] == SEP
&& path
[1] == wxT('.'))
371 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
374 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
375 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
376 && (q
- 1 <= path
|| q
[-1] != SEP
))
379 if (path
[0] == wxT('\0'))
385 /* Check that path[2] is NULL! */
386 else if (path
[1] == wxT(':') && !path
[2])
395 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
404 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
406 if (filename
== wxT(""))
407 return (wxChar
*) NULL
;
409 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
410 wxChar buf
[_MAXPATHLEN
];
412 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
413 wxChar ch
= buf
[wxStrlen(buf
) - 1];
415 if (ch
!= wxT('\\') && ch
!= wxT('/'))
416 wxStrcat(buf
, wxT("\\"));
419 wxStrcat(buf
, wxT("/"));
421 wxStrcat(buf
, wxFileFunctionsBuffer
);
422 return copystring( wxRealPath(buf
) );
424 return copystring( wxFileFunctionsBuffer
);
430 ~user/ => user's home dir
431 If the environment variable a = "foo" and b = "bar" then:
448 /* input name in name, pathname output to buf. */
450 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
452 register wxChar
*d
, *s
, *nm
;
453 wxChar lnm
[_MAXPATHLEN
];
456 // Some compilers don't like this line.
457 // const wxChar trimchars[] = wxT("\n \t");
460 trimchars
[0] = wxT('\n');
461 trimchars
[1] = wxT(' ');
462 trimchars
[2] = wxT('\t');
466 const wxChar SEP
= wxT('\\');
468 const wxChar SEP
= wxT('/');
471 if (name
== NULL
|| *name
== wxT('\0'))
473 nm
= copystring(name
); // Make a scratch copy
476 /* Skip leading whitespace and cr */
477 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
479 /* And strip off trailing whitespace and cr */
480 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
481 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
489 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
492 /* Expand inline environment variables */
510 while ((*d
++ = *s
)) {
512 if (*s
== wxT('\\')) {
513 if ((*(d
- 1) = *++s
)) {
522 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
524 if (*s
++ == wxT('$'))
527 register wxChar
*start
= d
;
528 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
529 register wxChar
*value
;
531 // VA gives assignment in logical expr warning
537 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
542 value
= wxGetenv(braces
? start
+ 1 : start
);
545 // VA gives assignment in logical expr warning
546 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
548 for ((d
= start
- 1); (*d
++ = *value
++););
557 /* Expand ~ and ~user */
560 if (nm
[0] == wxT('~') && !q
)
563 if (nm
[1] == SEP
|| nm
[1] == 0)
565 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
566 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
571 { /* ~user/filename */
572 register wxChar
*nnm
;
573 register wxChar
*home
;
574 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
575 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
576 was_sep
= (*s
== SEP
);
577 nnm
= *s
? s
+ 1 : s
;
579 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
580 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
581 if (was_sep
) /* replace only if it was there: */
592 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
594 while (wxT('\0') != (*d
++ = *s
++))
597 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
602 // VA gives assignment in logical expr warning
606 while ((*d
++ = *s
++));
608 delete[] nm_tmp
; // clean up alloc
609 /* Now clean up the buffer */
610 return wxRealPath(buf
);
613 /* Contract Paths to be build upon an environment variable
616 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
618 The call wxExpandPath can convert these back!
621 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
623 static wxChar dest
[_MAXPATHLEN
];
625 if (filename
== wxT(""))
626 return (wxChar
*) NULL
;
628 wxStrcpy (dest
, WXSTRINGCAST filename
);
630 Unix2DosFilename(dest
);
633 // Handle environment
634 const wxChar
*val
= (const wxChar
*) NULL
;
635 wxChar
*tcp
= (wxChar
*) NULL
;
636 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
637 (tcp
= wxStrstr (dest
, val
)) != NULL
)
639 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
642 wxStrcpy (tcp
, WXSTRINGCAST envname
);
643 wxStrcat (tcp
, wxT("}"));
644 wxStrcat (tcp
, wxFileFunctionsBuffer
);
647 // Handle User's home (ignore root homes!)
649 if ((val
= wxGetUserHome (user
)) != NULL
&&
650 (len
= wxStrlen(val
)) > 2 &&
651 wxStrncmp(dest
, val
, len
) == 0)
653 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
655 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
657 // strcat(wxFileFunctionsBuffer, "\\");
659 // strcat(wxFileFunctionsBuffer, "/");
661 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
662 wxStrcpy (dest
, wxFileFunctionsBuffer
);
668 // Return just the filename, not the path
670 wxChar
*wxFileNameFromPath (wxChar
*path
)
674 register wxChar
*tcp
;
676 tcp
= path
+ wxStrlen (path
);
677 while (--tcp
>= path
)
679 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
681 || *tcp
== wxT(':') || *tcp
== wxT(']'))
687 #if defined(__WXMSW__) || defined(__WXPM__)
688 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
695 wxString
wxFileNameFromPath (const wxString
& path1
)
697 if (path1
!= wxT(""))
700 wxChar
*path
= WXSTRINGCAST path1
;
701 register wxChar
*tcp
;
703 tcp
= path
+ wxStrlen (path
);
704 while (--tcp
>= path
)
706 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
708 || *tcp
== wxT(':') || *tcp
== wxT(']'))
712 return wxString(tcp
+ 1);
714 #if defined(__WXMSW__) || defined(__WXPM__)
715 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
716 return wxString(path
+ 2);
719 // Yes, this should return the path, not an empty string, otherwise
720 // we get "thing.txt" -> "".
724 // Return just the directory, or NULL if no directory
726 wxPathOnly (wxChar
*path
)
730 static wxChar buf
[_MAXPATHLEN
];
733 wxStrcpy (buf
, path
);
735 int l
= wxStrlen(path
);
740 // Search backward for a backward or forward slash
741 while (!done
&& i
> -1)
744 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
758 #if defined(__WXMSW__) || defined(__WXPM__)
759 // Try Drive specifier
760 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
762 // A:junk --> A:. (since A:.\junk Not A:\junk)
770 return (wxChar
*) NULL
;
773 // Return just the directory, or NULL if no directory
774 wxString
wxPathOnly (const wxString
& path
)
778 wxChar buf
[_MAXPATHLEN
];
781 wxStrcpy (buf
, WXSTRINGCAST path
);
783 int l
= path
.Length();
788 // Search backward for a backward or forward slash
789 while (!done
&& i
> -1)
792 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
801 return wxString(buf
);
806 #if defined(__WXMSW__) || defined(__WXPM__)
807 // Try Drive specifier
808 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
810 // A:junk --> A:. (since A:.\junk Not A:\junk)
813 return wxString(buf
);
818 return wxString(wxT(""));
821 // Utility for converting delimiters in DOS filenames to UNIX style
822 // and back again - or we get nasty problems with delimiters.
823 // Also, convert to lower case, since case is significant in UNIX.
827 static char sMacFileNameConversion
[ 1000 ] ;
829 wxString
wxMac2UnixFilename (const char *str
)
831 char *s
= sMacFileNameConversion
;
835 memmove( s
+1 , s
,strlen( s
) + 1) ;
846 *s
= wxTolower (*s
); // Case INDEPENDENT
850 return wxString (sMacFileNameConversion
) ;
853 wxString
wxUnix2MacFilename (const char *str
)
855 char *s
= sMacFileNameConversion
;
861 // relative path , since it goes on with slash which is translated to a :
862 memmove( s
, s
+1 ,strlen( s
) ) ;
864 else if ( *s
== '/' )
866 // absolute path -> on mac just start with the drive name
867 memmove( s
, s
+1 ,strlen( s
) ) ;
871 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
875 if (*s
== '/' || *s
== '\\')
877 // convert any back-directory situations
878 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
881 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
890 return wxString (sMacFileNameConversion
) ;
893 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
898 FSpGetFullPath( spec
, &length
, &myPath
) ;
899 ::SetHandleSize( myPath
, length
+ 1 ) ;
901 (*myPath
)[length
] = 0 ;
902 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
903 (*myPath
)[length
-1] = 0 ;
905 wxString
result( (char*) *myPath
) ;
906 ::HUnlock( myPath
) ;
907 ::DisposeHandle( myPath
) ;
911 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
913 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
916 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
918 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
921 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
923 wxString var
= wxUnix2MacFilename( path
) ;
924 wxMacFilename2FSSpec( var
, spec
) ;
929 wxDos2UnixFilename (char *s
)
938 *s
= wxTolower (*s
); // Case INDEPENDENT
945 #if defined(__WXMSW__) || defined(__WXPM__)
946 wxUnix2DosFilename (wxChar
*s
)
948 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
951 // Yes, I really mean this to happen under DOS only! JACS
952 #if defined(__WXMSW__) || defined(__WXPM__)
963 // Concatenate two files to form third
965 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
967 wxChar
*outfile
= wxGetTempFileName("cat");
969 FILE *fp1
= (FILE *) NULL
;
970 FILE *fp2
= (FILE *) NULL
;
971 FILE *fp3
= (FILE *) NULL
;
972 // Open the inputs and outputs
974 if ((fp1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
||
975 (fp2
= fopen (wxUnix2MacFilename( file2
), "rb")) == NULL
||
976 (fp3
= fopen (wxUnix2MacFilename( outfile
), "wb")) == NULL
)
978 if ((fp1
= wxFopen (WXSTRINGCAST file1
, wxT("rb"))) == NULL
||
979 (fp2
= wxFopen (WXSTRINGCAST file2
, wxT("rb"))) == NULL
||
980 (fp3
= wxFopen (outfile
, wxT("wb"))) == NULL
)
993 while ((ch
= getc (fp1
)) != EOF
)
994 (void) putc (ch
, fp3
);
997 while ((ch
= getc (fp2
)) != EOF
)
998 (void) putc (ch
, fp3
);
1002 bool result
= wxRenameFile(outfile
, file3
);
1009 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
1016 if ((fd1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
)
1018 if ((fd2
= fopen (wxUnix2MacFilename( file2
), "wb")) == NULL
)
1020 if ((fd1
= wxFopen (WXSTRINGCAST file1
, wxT("rb"))) == NULL
)
1022 if ((fd2
= wxFopen (WXSTRINGCAST file2
, wxT("wb"))) == NULL
)
1029 while ((ch
= getc (fd1
)) != EOF
)
1030 (void) putc (ch
, fd2
);
1038 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1041 if (0 == rename (wxUnix2MacFilename( file1
), wxUnix2MacFilename( file2
)))
1044 // Normal system call
1045 if (0 == rename (wxFNSTRINGCAST file1
.fn_str(), wxFNSTRINGCAST file2
.fn_str()))
1049 if (wxCopyFile(file1
, file2
)) {
1050 wxRemoveFile(file1
);
1057 bool wxRemoveFile(const wxString
& file
)
1059 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1060 int flag
= remove(wxFNSTRINGCAST file
.fn_str());
1061 #elif defined( __WXMAC__ )
1062 int flag
= unlink(wxUnix2MacFilename( file
));
1064 int flag
= unlink(wxFNSTRINGCAST file
.fn_str());
1066 return (flag
== 0) ;
1069 bool wxMkdir(const wxString
& dir
, int perm
)
1071 #if defined( __WXMAC__ )
1072 return (mkdir(wxUnix2MacFilename( dir
) , 0 ) == 0);
1074 const wxChar
*dirname
= dir
.c_str();
1076 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1077 // for the GNU compiler
1078 #if (!(defined(__WXMSW__) || defined(__OS2__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1079 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1080 #else // !MSW and !OS/2 VAC++
1081 if ( mkdir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1084 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1093 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1096 return FALSE
; //to be changed since rmdir exists in VMS7.x
1097 #elif defined( __WXMAC__ )
1098 return (rmdir(wxUnix2MacFilename( dir
)) == 0);
1102 return FALSE
; // What to do?
1104 return (rmdir(wxFNSTRINGCAST dir
.fn_str()) == 0);
1111 bool wxDirExists(const wxString
& dir
)
1114 return FALSE
; //To be changed since stat exists in VMS7.x
1115 #elif !defined(__WXMSW__)
1117 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1120 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1121 #if defined(__WIN32__)
1122 WIN32_FIND_DATA fileInfo
;
1125 struct ffblk fileInfo
;
1127 struct find_t fileInfo
;
1131 #if defined(__WIN32__)
1132 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1134 if (h
==INVALID_HANDLE_VALUE
)
1138 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1141 // In Borland findfirst has a different argument
1142 // ordering from _dos_findfirst. But _dos_findfirst
1143 // _should_ be ok in both MS and Borland... why not?
1145 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1147 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1156 // does the path exists? (may have or not '/' or '\\' at the end)
1157 bool wxPathExists(const wxChar
*pszPathName
)
1159 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1160 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1161 wxString
strPath(pszPathName
);
1162 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != wxT('\0') )
1163 strPath
.Last() = wxT('\0');
1171 return stat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1174 // Get a temporary filename, opening and closing the file.
1175 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1181 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1183 wxChar tmp
[MAX_PATH
];
1184 wxChar tmpPath
[MAX_PATH
];
1185 ::GetTempPath(MAX_PATH
, tmpPath
);
1186 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1188 if (buf
) wxStrcpy(buf
, tmp
);
1189 else buf
= copystring(tmp
);
1193 static short last_temp
= 0; // cache last to speed things a bit
1194 // At most 1000 temp files to a process! We use a ring count.
1195 wxChar tmp
[100]; // FIXME static buffer
1197 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1199 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1200 if (!wxFileExists( tmp
))
1202 // Touch the file to create it (reserve name)
1203 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1208 wxStrcpy( buf
, tmp
);
1210 buf
= copystring( tmp
);
1214 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1215 if (buf
) buf
[0] = 0;
1216 return (wxChar
*) NULL
;
1220 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1223 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1232 // Get first file name matching given wild card.
1236 // Get first file name matching given wild card.
1237 // Flags are reserved for future use.
1239 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1240 static DIR *gs_dirStream
= (DIR *) NULL
;
1241 static wxString gs_strFileSpec
;
1242 static int gs_findFlags
= 0;
1245 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1249 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1251 closedir(gs_dirStream
); // edz 941103: better housekeping
1253 gs_findFlags
= flags
;
1255 gs_strFileSpec
= spec
;
1257 // Find path only so we can concatenate
1258 // found file onto path
1259 wxString
path(wxPathOnly(gs_strFileSpec
));
1261 // special case: path is really "/"
1262 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1264 // path is empty => Local directory
1268 gs_dirStream
= opendir(path
.fn_str());
1269 if ( !gs_dirStream
)
1271 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1276 result
= wxFindNextFile();
1278 #endif // !VMS6.x or earlier
1283 wxString
wxFindNextFile()
1287 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1288 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1290 // Find path only so we can concatenate
1291 // found file onto path
1292 wxString
path(wxPathOnly(gs_strFileSpec
));
1293 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1295 /* MATTHEW: special case: path is really "/" */
1296 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1300 struct dirent
*nextDir
;
1301 for ( nextDir
= readdir(gs_dirStream
);
1303 nextDir
= readdir(gs_dirStream
) )
1305 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1306 strcmp(nextDir
->d_name
, ".") &&
1307 strcmp(nextDir
->d_name
, "..") )
1310 if ( !path
.IsEmpty() )
1313 if ( path
!= wxT('/') )
1317 result
+= nextDir
->d_name
;
1319 // Only return "." and ".." when they match
1321 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1322 (strcmp(nextDir
->d_name
, "..") == 0))
1324 if ( (gs_findFlags
& wxDIR
) != 0 )
1330 isdir
= wxDirExists(result
);
1332 // and only return directories when flags & wxDIR
1333 if ( !gs_findFlags
||
1334 ((gs_findFlags
& wxDIR
) && isdir
) ||
1335 ((gs_findFlags
& wxFILE
) && !isdir
) )
1342 result
.Empty(); // not found
1344 closedir(gs_dirStream
);
1345 gs_dirStream
= (DIR *) NULL
;
1346 #endif // !VMS6.2 or earlier
1351 #elif defined(__WXMAC__)
1353 struct MacDirectoryIterator
1361 static int g_iter_flags
;
1363 static MacDirectoryIterator g_iter
;
1365 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1369 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1371 // Find path only so we can concatenate found file onto path
1372 wxString
path(wxPathOnly(spec
));
1373 if ( !path
.IsEmpty() )
1374 result
<< path
<< wxT('\\');
1378 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1379 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1380 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1381 g_iter
.m_index
= 0 ;
1384 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1386 return wxEmptyString
;
1388 return wxFindNextFile( ) ;
1391 wxString
wxFindNextFile()
1397 while ( err
== noErr
)
1400 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1401 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1402 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1406 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1409 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1417 return wxEmptyString
;
1421 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1426 return wxMacFSSpec2UnixFilename( &spec
) ;
1429 #elif defined(__WXMSW__)
1432 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1433 static WIN32_FIND_DATA gs_findDataStruct
;
1436 static struct ffblk gs_findDataStruct
;
1438 static struct _find_t gs_findDataStruct
;
1442 static wxString gs_strFileSpec
;
1443 static int gs_findFlags
= 0;
1445 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1449 gs_strFileSpec
= spec
;
1450 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1452 // Find path only so we can concatenate found file onto path
1453 wxString
path(wxPathOnly(gs_strFileSpec
));
1454 if ( !path
.IsEmpty() )
1455 result
<< path
<< wxT('\\');
1458 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1459 FindClose(gs_hFileStruct
);
1461 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1463 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1470 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1472 if (isdir
&& !(flags
& wxDIR
))
1473 return wxFindNextFile();
1474 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1475 return wxFindNextFile();
1477 result
+= gs_findDataStruct
.cFileName
;
1481 int flag
= _A_NORMAL
;
1482 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1486 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1488 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1491 /* MATTHEW: [5] Check directory flag */
1495 attrib
= gs_findDataStruct
.ff_attrib
;
1497 attrib
= gs_findDataStruct
.attrib
;
1500 if (attrib
& _A_SUBDIR
) {
1501 if (!(gs_findFlags
& wxDIR
))
1502 return wxFindNextFile();
1503 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1504 return wxFindNextFile();
1508 gs_findDataStruct
.ff_name
1510 gs_findDataStruct
.name
1519 wxString
wxFindNextFile()
1523 // Find path only so we can concatenate found file onto path
1524 wxString
path(wxPathOnly(gs_strFileSpec
));
1529 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1532 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1535 FindClose(gs_hFileStruct
);
1536 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1540 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1542 if (isdir
&& !(gs_findFlags
& wxDIR
))
1544 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1547 if ( !path
.IsEmpty() )
1548 result
<< path
<< wxT('\\');
1549 result
<< gs_findDataStruct
.cFileName
;
1556 if (findnext(&gs_findDataStruct
) == 0)
1558 if (_dos_findnext(&gs_findDataStruct
) == 0)
1561 /* MATTHEW: [5] Check directory flag */
1565 attrib
= gs_findDataStruct
.ff_attrib
;
1567 attrib
= gs_findDataStruct
.attrib
;
1570 if (attrib
& _A_SUBDIR
) {
1571 if (!(gs_findFlags
& wxDIR
))
1573 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1579 gs_findDataStruct
.ff_name
1581 gs_findDataStruct
.name
1590 #endif // Unix/Windows
1592 // Get current working directory.
1593 // If buf is NULL, allocates space using new, else
1595 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1598 buf
= new wxChar
[sz
+1];
1600 char *cbuf
= new char[sz
+1];
1602 if (_getcwd(cbuf
, sz
) == NULL
) {
1603 #elif defined( __WXMAC__)
1606 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1610 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1611 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1612 strcpy( buf
, res
) ;
1615 if (getcwd(cbuf
, sz
) == NULL
) {
1620 if (_getcwd(buf
, sz
) == NULL
) {
1621 #elif defined( __WXMAC__)
1624 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1628 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1629 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1630 strcpy( buf
, res
) ;
1633 if (getcwd(buf
, sz
) == NULL
) {
1641 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1650 static const size_t maxPathLen
= 1024;
1653 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1654 str
.UngetWriteBuf();
1659 bool wxSetWorkingDirectory(const wxString
& d
)
1661 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1662 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1663 #elif defined(__WINDOWS__)
1666 return (bool)(SetCurrentDirectory(d
) != 0);
1668 // Must change drive, too.
1669 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1672 wxChar firstChar
= d
[0];
1676 firstChar
= firstChar
- 32;
1678 // To a drive number
1679 unsigned int driveNo
= firstChar
- 64;
1682 unsigned int noDrives
;
1683 _dos_setdrive(driveNo
, &noDrives
);
1686 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1694 // Get the OS directory if appropriate (such as the Windows directory).
1695 // On non-Windows platform, probably just return the empty string.
1696 wxString
wxGetOSDirectory()
1700 GetWindowsDirectory(buf
, 256);
1701 return wxString(buf
);
1703 return wxEmptyString
;
1707 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1709 size_t len
= wxStrlen(pszFileName
);
1713 return wxIsPathSeparator(pszFileName
[len
- 1]);
1716 // find a file in a list of directories, returns false if not found
1717 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1719 // we assume that it's not empty
1720 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1721 _("empty file name in wxFindFileInPath"));
1723 // skip path separator in the beginning of the file name if present
1724 if ( wxIsPathSeparator(*pszFile
) )
1727 // copy the path (strtok will modify it)
1728 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1729 wxStrcpy(szPath
, pszPath
);
1732 wxChar
*pc
, *save_ptr
;
1733 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1735 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1737 // search for the file in this directory
1739 if ( !wxEndsWithPathSeparator(pc
) )
1740 strFile
+= wxFILE_SEP_PATH
;
1743 if ( FileExists(strFile
) ) {
1749 // suppress warning about unused variable save_ptr when wxStrtok() is a
1750 // macro which throws away its third argument
1755 return pc
!= NULL
; // if true => we breaked from the loop
1758 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1763 // it can be empty, but it shouldn't be NULL
1764 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1766 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1769 // under Windows we understand both separators
1770 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1771 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1772 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1773 #else // assume Unix
1774 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1776 if ( pDot
== pszFileName
)
1778 // under Unix files like .profile are treated in a special way
1783 if ( pDot
< pLastSeparator
)
1785 // the dot is part of the path, not the start of the extension
1791 if ( pLastSeparator
)
1792 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1799 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1800 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1802 *pstrName
= wxString(start
, end
- start
);
1808 *pstrExt
= wxString(pDot
+ 1);
1816 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1820 stat(filename
.fn_str(), &buf
);
1821 return buf
.st_mtime
;
1825 //------------------------------------------------------------------------
1826 // wild character routines
1827 //------------------------------------------------------------------------
1829 bool wxIsWild( const wxString
& pattern
)
1831 wxString tmp
= pattern
;
1832 wxChar
*pat
= WXSTRINGCAST(tmp
);
1835 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1845 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1847 #if defined(HAVE_FNMATCH_H)
1849 // this probably won't work well for multibyte chars in Unicode mode?
1851 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1853 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1857 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1860 * WARNING: this code is broken!
1863 wxString tmp1
= pat
;
1864 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1865 wxString tmp2
= text
;
1866 wxChar
*str
= WXSTRINGCAST(tmp2
);
1869 bool done
= FALSE
, ret_code
, ok
;
1870 // Below is for vi fans
1871 const wxChar OB
= wxT('{'), CB
= wxT('}');
1873 // dot_special means '.' only matches '.'
1874 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1877 while ((*pattern
!= wxT('\0')) && (!done
)
1878 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1882 if (*pattern
!= wxT('\0'))
1888 while ((*str
!=wxT('\0'))
1889 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1892 while (*str
!= wxT('\0'))
1894 while (*pattern
!= wxT('\0'))
1901 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1905 if (*pattern
== wxT('\\')) {
1907 if (*pattern
== wxT('\0')) {
1912 if (*(pattern
+ 1) == wxT('-')) {
1915 if (*pattern
== wxT(']')) {
1919 if (*pattern
== wxT('\\')) {
1921 if (*pattern
== wxT('\0')) {
1926 if ((*str
< c
) || (*str
> *pattern
)) {
1930 } else if (*pattern
!= *str
) {
1935 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1936 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1940 if (*pattern
!= wxT('\0')) {
1950 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1953 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1954 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1955 if (*pattern
== wxT('\\'))
1957 ok
= (*pattern
++ == *cp
++);
1959 if (*pattern
== wxT('\0')) {
1965 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1966 if (*++pattern
== wxT('\\')) {
1967 if (*++pattern
== CB
)
1972 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1973 if (*++pattern
== wxT('\\')) {
1974 if (*++pattern
== CB
|| *pattern
== wxT(','))
1979 if (*pattern
!= wxT('\0'))
1984 if (*str
== *pattern
) {
1991 while (*pattern
== wxT('*'))
1993 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1999 #pragma warning(default:4706) // assignment within conditional expression