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 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
114 const off_t wxInvalidOffset
= (off_t
)-1;
117 #define _MAXPATHLEN 500
119 extern wxChar
*wxBuffer
;
123 #include "morefile.h"
124 #include "moreextr.h"
125 #include "fullpath.h"
126 #include "fspcompa.h"
129 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
131 // ----------------------------------------------------------------------------
133 // ----------------------------------------------------------------------------
135 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
137 // ============================================================================
139 // ============================================================================
141 void wxPathList::Add (const wxString
& path
)
143 wxStringList::Add (WXSTRINGCAST path
);
146 // Add paths e.g. from the PATH environment variable
147 void wxPathList::AddEnvList (const wxString
& envVariable
)
149 static const wxChar PATH_TOKS
[] =
151 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
156 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
159 wxChar
*s
= copystring (val
);
160 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
164 Add (copystring (token
));
167 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
168 Add (wxString(token
));
172 // suppress warning about unused variable save_ptr when wxStrtok() is a
173 // macro which throws away its third argument
180 // Given a full filename (with path), ensure that that file can
181 // be accessed again USING FILENAME ONLY by adding the path
182 // to the list if not already there.
183 void wxPathList::EnsureFileAccessible (const wxString
& path
)
185 wxString
path_only(wxPathOnly(path
));
186 if ( !path_only
.IsEmpty() )
188 if ( !Member(path_only
) )
193 bool wxPathList::Member (const wxString
& path
)
195 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
197 wxString
path2((wxChar
*) node
->Data ());
199 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
201 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
203 // Case sensitive File System
204 path
.CompareTo (path2
) == 0
212 wxString
wxPathList::FindValidPath (const wxString
& file
)
214 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
215 return wxString(wxFileFunctionsBuffer
);
217 wxChar buf
[_MAXPATHLEN
];
218 wxStrcpy(buf
, wxFileFunctionsBuffer
);
220 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
221 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
223 for (wxNode
* node
= First (); node
; node
= node
->Next ())
225 wxChar
*path
= (wxChar
*) node
->Data ();
226 wxStrcpy (wxFileFunctionsBuffer
, path
);
227 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
228 if (ch
!= wxT('\\') && ch
!= wxT('/'))
229 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
230 wxStrcat (wxFileFunctionsBuffer
, filename
);
232 Unix2DosFilename (wxFileFunctionsBuffer
);
234 if (wxFileExists (wxFileFunctionsBuffer
))
236 return wxString(wxFileFunctionsBuffer
); // Found!
240 return wxString(wxT("")); // Not found
243 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
245 wxString f
= FindValidPath(file
);
246 if ( wxIsAbsolutePath(f
) )
250 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
252 if ( !wxEndsWithPathSeparator(buf
) )
254 buf
+= wxFILE_SEP_PATH
;
262 wxFileExists (const wxString
& filename
)
264 #ifdef __GNUWIN32__ // (fix a B20 bug)
265 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
269 #elif defined(__WXMAC__)
271 if (filename
&& stat (wxUnix2MacFilename(filename
), &stbuf
) == 0 )
282 if ((filename
!= wxT("")) && stat (wxFNSTRINGCAST filename
.fn_str(), &stbuf
) == 0)
288 /* Vadim's alternative implementation
290 // does the file exist?
291 bool wxFileExists(const char *pszFileName)
294 return !access(pszFileName, 0) &&
295 !stat(pszFileName, &st) &&
296 (st.st_mode & S_IFREG);
301 wxIsAbsolutePath (const wxString
& filename
)
303 if (filename
!= wxT(""))
305 if (filename
[0] == wxT('/')
307 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
311 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
320 * Strip off any extension (dot something) from end of file,
321 * IF one exists. Inserts zero into buffer.
325 void wxStripExtension(wxChar
*buffer
)
327 int len
= wxStrlen(buffer
);
331 if (buffer
[i
] == wxT('.'))
340 void wxStripExtension(wxString
& buffer
)
342 size_t len
= buffer
.Length();
346 if (buffer
.GetChar(i
) == wxT('.'))
348 buffer
= buffer
.Left(i
);
355 // Destructive removal of /./ and /../ stuff
356 wxChar
*wxRealPath (wxChar
*path
)
359 static const wxChar SEP
= wxT('\\');
360 Unix2DosFilename(path
);
362 static const wxChar SEP
= wxT('/');
364 if (path
[0] && path
[1]) {
365 /* MATTHEW: special case "/./x" */
367 if (path
[2] == SEP
&& path
[1] == wxT('.'))
375 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
378 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
379 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
380 && (q
- 1 <= path
|| q
[-1] != SEP
))
383 if (path
[0] == wxT('\0'))
389 /* Check that path[2] is NULL! */
390 else if (path
[1] == wxT(':') && !path
[2])
399 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
408 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
410 if (filename
== wxT(""))
411 return (wxChar
*) NULL
;
413 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
414 wxChar buf
[_MAXPATHLEN
];
416 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
417 wxChar ch
= buf
[wxStrlen(buf
) - 1];
419 if (ch
!= wxT('\\') && ch
!= wxT('/'))
420 wxStrcat(buf
, wxT("\\"));
423 wxStrcat(buf
, wxT("/"));
425 wxStrcat(buf
, wxFileFunctionsBuffer
);
426 return copystring( wxRealPath(buf
) );
428 return copystring( wxFileFunctionsBuffer
);
434 ~user/ => user's home dir
435 If the environment variable a = "foo" and b = "bar" then:
452 /* input name in name, pathname output to buf. */
454 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
456 register wxChar
*d
, *s
, *nm
;
457 wxChar lnm
[_MAXPATHLEN
];
460 // Some compilers don't like this line.
461 // const wxChar trimchars[] = wxT("\n \t");
464 trimchars
[0] = wxT('\n');
465 trimchars
[1] = wxT(' ');
466 trimchars
[2] = wxT('\t');
470 const wxChar SEP
= wxT('\\');
472 const wxChar SEP
= wxT('/');
475 if (name
== NULL
|| *name
== wxT('\0'))
477 nm
= copystring(name
); // Make a scratch copy
480 /* Skip leading whitespace and cr */
481 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
483 /* And strip off trailing whitespace and cr */
484 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
485 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
493 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
496 /* Expand inline environment variables */
514 while ((*d
++ = *s
)) {
516 if (*s
== wxT('\\')) {
517 if ((*(d
- 1) = *++s
)) {
526 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
528 if (*s
++ == wxT('$'))
531 register wxChar
*start
= d
;
532 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
533 register wxChar
*value
;
535 // VA gives assignment in logical expr warning
541 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
546 value
= wxGetenv(braces
? start
+ 1 : start
);
549 // VA gives assignment in logical expr warning
550 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
552 for ((d
= start
- 1); (*d
++ = *value
++););
561 /* Expand ~ and ~user */
564 if (nm
[0] == wxT('~') && !q
)
567 if (nm
[1] == SEP
|| nm
[1] == 0)
569 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
570 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
575 { /* ~user/filename */
576 register wxChar
*nnm
;
577 register wxChar
*home
;
578 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
579 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
580 was_sep
= (*s
== SEP
);
581 nnm
= *s
? s
+ 1 : s
;
583 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
584 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
585 if (was_sep
) /* replace only if it was there: */
596 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
598 while (wxT('\0') != (*d
++ = *s
++))
601 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
606 // VA gives assignment in logical expr warning
610 while ((*d
++ = *s
++));
612 delete[] nm_tmp
; // clean up alloc
613 /* Now clean up the buffer */
614 return wxRealPath(buf
);
617 /* Contract Paths to be build upon an environment variable
620 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
622 The call wxExpandPath can convert these back!
625 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
627 static wxChar dest
[_MAXPATHLEN
];
629 if (filename
== wxT(""))
630 return (wxChar
*) NULL
;
632 wxStrcpy (dest
, WXSTRINGCAST filename
);
634 Unix2DosFilename(dest
);
637 // Handle environment
638 const wxChar
*val
= (const wxChar
*) NULL
;
639 wxChar
*tcp
= (wxChar
*) NULL
;
640 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
641 (tcp
= wxStrstr (dest
, val
)) != NULL
)
643 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
646 wxStrcpy (tcp
, WXSTRINGCAST envname
);
647 wxStrcat (tcp
, wxT("}"));
648 wxStrcat (tcp
, wxFileFunctionsBuffer
);
651 // Handle User's home (ignore root homes!)
653 if ((val
= wxGetUserHome (user
)) != NULL
&&
654 (len
= wxStrlen(val
)) > 2 &&
655 wxStrncmp(dest
, val
, len
) == 0)
657 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
659 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
661 // strcat(wxFileFunctionsBuffer, "\\");
663 // strcat(wxFileFunctionsBuffer, "/");
665 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
666 wxStrcpy (dest
, wxFileFunctionsBuffer
);
672 // Return just the filename, not the path
674 wxChar
*wxFileNameFromPath (wxChar
*path
)
678 register wxChar
*tcp
;
680 tcp
= path
+ wxStrlen (path
);
681 while (--tcp
>= path
)
683 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
685 || *tcp
== wxT(':') || *tcp
== wxT(']'))
691 #if defined(__WXMSW__) || defined(__WXPM__)
692 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
699 wxString
wxFileNameFromPath (const wxString
& path1
)
701 if (path1
!= wxT(""))
704 wxChar
*path
= WXSTRINGCAST path1
;
705 register wxChar
*tcp
;
707 tcp
= path
+ wxStrlen (path
);
708 while (--tcp
>= path
)
710 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
712 || *tcp
== wxT(':') || *tcp
== wxT(']'))
716 return wxString(tcp
+ 1);
718 #if defined(__WXMSW__) || defined(__WXPM__)
719 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
720 return wxString(path
+ 2);
723 // Yes, this should return the path, not an empty string, otherwise
724 // we get "thing.txt" -> "".
728 // Return just the directory, or NULL if no directory
730 wxPathOnly (wxChar
*path
)
734 static wxChar buf
[_MAXPATHLEN
];
737 wxStrcpy (buf
, path
);
739 int l
= wxStrlen(path
);
744 // Search backward for a backward or forward slash
745 while (!done
&& i
> -1)
748 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
762 #if defined(__WXMSW__) || defined(__WXPM__)
763 // Try Drive specifier
764 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
766 // A:junk --> A:. (since A:.\junk Not A:\junk)
774 return (wxChar
*) NULL
;
777 // Return just the directory, or NULL if no directory
778 wxString
wxPathOnly (const wxString
& path
)
782 wxChar buf
[_MAXPATHLEN
];
785 wxStrcpy (buf
, WXSTRINGCAST path
);
787 int l
= path
.Length();
792 // Search backward for a backward or forward slash
793 while (!done
&& i
> -1)
796 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
805 return wxString(buf
);
810 #if defined(__WXMSW__) || defined(__WXPM__)
811 // Try Drive specifier
812 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
814 // A:junk --> A:. (since A:.\junk Not A:\junk)
817 return wxString(buf
);
822 return wxString(wxT(""));
825 // Utility for converting delimiters in DOS filenames to UNIX style
826 // and back again - or we get nasty problems with delimiters.
827 // Also, convert to lower case, since case is significant in UNIX.
831 static char sMacFileNameConversion
[ 1000 ] ;
833 wxString
wxMac2UnixFilename (const char *str
)
835 char *s
= sMacFileNameConversion
;
839 memmove( s
+1 , s
,strlen( s
) + 1) ;
850 *s
= wxTolower (*s
); // Case INDEPENDENT
854 return wxString (sMacFileNameConversion
) ;
857 wxString
wxUnix2MacFilename (const char *str
)
859 char *s
= sMacFileNameConversion
;
865 // relative path , since it goes on with slash which is translated to a :
866 memmove( s
, s
+1 ,strlen( s
) ) ;
868 else if ( *s
== '/' )
870 // absolute path -> on mac just start with the drive name
871 memmove( s
, s
+1 ,strlen( s
) ) ;
875 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
879 if (*s
== '/' || *s
== '\\')
881 // convert any back-directory situations
882 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
885 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
894 return wxString (sMacFileNameConversion
) ;
897 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
902 FSpGetFullPath( spec
, &length
, &myPath
) ;
903 ::SetHandleSize( myPath
, length
+ 1 ) ;
905 (*myPath
)[length
] = 0 ;
906 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
907 (*myPath
)[length
-1] = 0 ;
909 wxString
result( (char*) *myPath
) ;
910 ::HUnlock( myPath
) ;
911 ::DisposeHandle( myPath
) ;
915 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
917 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
920 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
922 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
925 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
927 wxString var
= wxUnix2MacFilename( path
) ;
928 wxMacFilename2FSSpec( var
, spec
) ;
933 wxDos2UnixFilename (char *s
)
942 *s
= wxTolower (*s
); // Case INDEPENDENT
949 #if defined(__WXMSW__) || defined(__WXPM__)
950 wxUnix2DosFilename (wxChar
*s
)
952 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
955 // Yes, I really mean this to happen under DOS only! JACS
956 #if defined(__WXMSW__) || defined(__WXPM__)
967 // Concatenate two files to form third
969 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
971 wxChar
*outfile
= wxGetTempFileName("cat");
973 FILE *fp1
= (FILE *) NULL
;
974 FILE *fp2
= (FILE *) NULL
;
975 FILE *fp3
= (FILE *) NULL
;
976 // Open the inputs and outputs
978 if ((fp1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
||
979 (fp2
= fopen (wxUnix2MacFilename( file2
), "rb")) == NULL
||
980 (fp3
= fopen (wxUnix2MacFilename( outfile
), "wb")) == NULL
)
982 if ((fp1
= wxFopen (WXSTRINGCAST file1
, wxT("rb"))) == NULL
||
983 (fp2
= wxFopen (WXSTRINGCAST file2
, wxT("rb"))) == NULL
||
984 (fp3
= wxFopen (outfile
, wxT("wb"))) == NULL
)
997 while ((ch
= getc (fp1
)) != EOF
)
998 (void) putc (ch
, fp3
);
1001 while ((ch
= getc (fp2
)) != EOF
)
1002 (void) putc (ch
, fp3
);
1006 bool result
= wxRenameFile(outfile
, file3
);
1013 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
1020 if ((fd1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
)
1022 if ((fd2
= fopen (wxUnix2MacFilename( file2
), "wb")) == NULL
)
1024 if ((fd1
= wxFopen (WXSTRINGCAST file1
, wxT("rb"))) == NULL
)
1026 if ((fd2
= wxFopen (WXSTRINGCAST file2
, wxT("wb"))) == NULL
)
1033 while ((ch
= getc (fd1
)) != EOF
)
1034 (void) putc (ch
, fd2
);
1042 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1045 if (0 == rename (wxUnix2MacFilename( file1
), wxUnix2MacFilename( file2
)))
1048 // Normal system call
1049 if (0 == rename (wxFNSTRINGCAST file1
.fn_str(), wxFNSTRINGCAST file2
.fn_str()))
1053 if (wxCopyFile(file1
, file2
)) {
1054 wxRemoveFile(file1
);
1061 bool wxRemoveFile(const wxString
& file
)
1063 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1064 int flag
= remove(wxFNSTRINGCAST file
.fn_str());
1065 #elif defined( __WXMAC__ )
1066 int flag
= unlink(wxUnix2MacFilename( file
));
1068 int flag
= unlink(wxFNSTRINGCAST file
.fn_str());
1070 return (flag
== 0) ;
1073 bool wxMkdir(const wxString
& dir
, int perm
)
1075 #if defined( __WXMAC__ )
1076 return (mkdir(wxUnix2MacFilename( dir
) , 0 ) == 0);
1078 const wxChar
*dirname
= dir
.c_str();
1080 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1081 // for the GNU compiler
1082 #if (!(defined(__WXMSW__) || defined(__OS2__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1083 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1084 #else // !MSW and !OS/2 VAC++
1085 if ( mkdir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1088 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1097 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1100 return FALSE
; //to be changed since rmdir exists in VMS7.x
1101 #elif defined( __WXMAC__ )
1102 return (rmdir(wxUnix2MacFilename( dir
)) == 0);
1106 return FALSE
; // What to do?
1108 return (rmdir(wxFNSTRINGCAST dir
.fn_str()) == 0);
1115 bool wxDirExists(const wxString
& dir
)
1118 return FALSE
; //To be changed since stat exists in VMS7.x
1119 #elif !defined(__WXMSW__)
1121 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1124 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1125 #if defined(__WIN32__)
1126 WIN32_FIND_DATA fileInfo
;
1129 struct ffblk fileInfo
;
1131 struct find_t fileInfo
;
1135 #if defined(__WIN32__)
1136 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1138 if (h
==INVALID_HANDLE_VALUE
)
1142 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1145 // In Borland findfirst has a different argument
1146 // ordering from _dos_findfirst. But _dos_findfirst
1147 // _should_ be ok in both MS and Borland... why not?
1149 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1151 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1160 // does the path exists? (may have or not '/' or '\\' at the end)
1161 bool wxPathExists(const wxChar
*pszPathName
)
1163 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1164 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1165 wxString
strPath(pszPathName
);
1166 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != wxT('\0') )
1167 strPath
.Last() = wxT('\0');
1175 return stat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1178 // Get a temporary filename, opening and closing the file.
1179 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1185 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1187 wxChar tmp
[MAX_PATH
];
1188 wxChar tmpPath
[MAX_PATH
];
1189 ::GetTempPath(MAX_PATH
, tmpPath
);
1190 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1192 if (buf
) wxStrcpy(buf
, tmp
);
1193 else buf
= copystring(tmp
);
1197 static short last_temp
= 0; // cache last to speed things a bit
1198 // At most 1000 temp files to a process! We use a ring count.
1199 wxChar tmp
[100]; // FIXME static buffer
1201 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1203 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1204 if (!wxFileExists( tmp
))
1206 // Touch the file to create it (reserve name)
1207 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1212 wxStrcpy( buf
, tmp
);
1214 buf
= copystring( tmp
);
1218 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1219 if (buf
) buf
[0] = 0;
1220 return (wxChar
*) NULL
;
1224 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1227 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1236 // Get first file name matching given wild card.
1240 // Get first file name matching given wild card.
1241 // Flags are reserved for future use.
1243 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1244 static DIR *gs_dirStream
= (DIR *) NULL
;
1245 static wxString gs_strFileSpec
;
1246 static int gs_findFlags
= 0;
1249 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1253 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1255 closedir(gs_dirStream
); // edz 941103: better housekeping
1257 gs_findFlags
= flags
;
1259 gs_strFileSpec
= spec
;
1261 // Find path only so we can concatenate
1262 // found file onto path
1263 wxString
path(wxPathOnly(gs_strFileSpec
));
1265 // special case: path is really "/"
1266 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1268 // path is empty => Local directory
1272 gs_dirStream
= opendir(path
.fn_str());
1273 if ( !gs_dirStream
)
1275 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1280 result
= wxFindNextFile();
1282 #endif // !VMS6.x or earlier
1287 wxString
wxFindNextFile()
1291 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1292 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1294 // Find path only so we can concatenate
1295 // found file onto path
1296 wxString
path(wxPathOnly(gs_strFileSpec
));
1297 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1299 /* MATTHEW: special case: path is really "/" */
1300 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1304 struct dirent
*nextDir
;
1305 for ( nextDir
= readdir(gs_dirStream
);
1307 nextDir
= readdir(gs_dirStream
) )
1309 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1310 strcmp(nextDir
->d_name
, ".") &&
1311 strcmp(nextDir
->d_name
, "..") )
1314 if ( !path
.IsEmpty() )
1317 if ( path
!= wxT('/') )
1321 result
+= nextDir
->d_name
;
1323 // Only return "." and ".." when they match
1325 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1326 (strcmp(nextDir
->d_name
, "..") == 0))
1328 if ( (gs_findFlags
& wxDIR
) != 0 )
1334 isdir
= wxDirExists(result
);
1336 // and only return directories when flags & wxDIR
1337 if ( !gs_findFlags
||
1338 ((gs_findFlags
& wxDIR
) && isdir
) ||
1339 ((gs_findFlags
& wxFILE
) && !isdir
) )
1346 result
.Empty(); // not found
1348 closedir(gs_dirStream
);
1349 gs_dirStream
= (DIR *) NULL
;
1350 #endif // !VMS6.2 or earlier
1355 #elif defined(__WXMAC__)
1357 struct MacDirectoryIterator
1365 static int g_iter_flags
;
1367 static MacDirectoryIterator g_iter
;
1369 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1373 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1375 // Find path only so we can concatenate found file onto path
1376 wxString
path(wxPathOnly(spec
));
1377 if ( !path
.IsEmpty() )
1378 result
<< path
<< wxT('\\');
1382 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1383 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1384 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1385 g_iter
.m_index
= 0 ;
1388 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1390 return wxEmptyString
;
1392 return wxFindNextFile( ) ;
1395 wxString
wxFindNextFile()
1401 while ( err
== noErr
)
1404 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1405 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1406 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1410 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1413 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1421 return wxEmptyString
;
1425 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1430 return wxMacFSSpec2UnixFilename( &spec
) ;
1433 #elif defined(__WXMSW__)
1436 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1437 static WIN32_FIND_DATA gs_findDataStruct
;
1440 static struct ffblk gs_findDataStruct
;
1442 static struct _find_t gs_findDataStruct
;
1446 static wxString gs_strFileSpec
;
1447 static int gs_findFlags
= 0;
1449 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1453 gs_strFileSpec
= spec
;
1454 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1456 // Find path only so we can concatenate found file onto path
1457 wxString
path(wxPathOnly(gs_strFileSpec
));
1458 if ( !path
.IsEmpty() )
1459 result
<< path
<< wxT('\\');
1462 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1463 FindClose(gs_hFileStruct
);
1465 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1467 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1474 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1476 if (isdir
&& !(flags
& wxDIR
))
1477 return wxFindNextFile();
1478 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1479 return wxFindNextFile();
1481 result
+= gs_findDataStruct
.cFileName
;
1485 int flag
= _A_NORMAL
;
1486 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1490 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1492 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1495 /* MATTHEW: [5] Check directory flag */
1499 attrib
= gs_findDataStruct
.ff_attrib
;
1501 attrib
= gs_findDataStruct
.attrib
;
1504 if (attrib
& _A_SUBDIR
) {
1505 if (!(gs_findFlags
& wxDIR
))
1506 return wxFindNextFile();
1507 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1508 return wxFindNextFile();
1512 gs_findDataStruct
.ff_name
1514 gs_findDataStruct
.name
1523 wxString
wxFindNextFile()
1527 // Find path only so we can concatenate found file onto path
1528 wxString
path(wxPathOnly(gs_strFileSpec
));
1533 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1536 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1539 FindClose(gs_hFileStruct
);
1540 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1544 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1546 if (isdir
&& !(gs_findFlags
& wxDIR
))
1548 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1551 if ( !path
.IsEmpty() )
1552 result
<< path
<< wxT('\\');
1553 result
<< gs_findDataStruct
.cFileName
;
1560 if (findnext(&gs_findDataStruct
) == 0)
1562 if (_dos_findnext(&gs_findDataStruct
) == 0)
1565 /* MATTHEW: [5] Check directory flag */
1569 attrib
= gs_findDataStruct
.ff_attrib
;
1571 attrib
= gs_findDataStruct
.attrib
;
1574 if (attrib
& _A_SUBDIR
) {
1575 if (!(gs_findFlags
& wxDIR
))
1577 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1583 gs_findDataStruct
.ff_name
1585 gs_findDataStruct
.name
1594 #endif // Unix/Windows
1596 // Get current working directory.
1597 // If buf is NULL, allocates space using new, else
1599 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1602 buf
= new wxChar
[sz
+1];
1604 char *cbuf
= new char[sz
+1];
1606 if (_getcwd(cbuf
, sz
) == NULL
) {
1607 #elif defined( __WXMAC__)
1610 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1614 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1615 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1616 strcpy( buf
, res
) ;
1619 if (getcwd(cbuf
, sz
) == NULL
) {
1624 if (_getcwd(buf
, sz
) == NULL
) {
1625 #elif defined( __WXMAC__)
1628 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1632 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1633 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1634 strcpy( buf
, res
) ;
1637 if (getcwd(buf
, sz
) == NULL
) {
1645 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1654 static const size_t maxPathLen
= 1024;
1657 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1658 str
.UngetWriteBuf();
1663 bool wxSetWorkingDirectory(const wxString
& d
)
1665 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1666 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1667 #elif defined(__WINDOWS__)
1670 return (bool)(SetCurrentDirectory(d
) != 0);
1672 // Must change drive, too.
1673 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1676 wxChar firstChar
= d
[0];
1680 firstChar
= firstChar
- 32;
1682 // To a drive number
1683 unsigned int driveNo
= firstChar
- 64;
1686 unsigned int noDrives
;
1687 _dos_setdrive(driveNo
, &noDrives
);
1690 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1698 // Get the OS directory if appropriate (such as the Windows directory).
1699 // On non-Windows platform, probably just return the empty string.
1700 wxString
wxGetOSDirectory()
1704 GetWindowsDirectory(buf
, 256);
1705 return wxString(buf
);
1707 return wxEmptyString
;
1711 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1713 size_t len
= wxStrlen(pszFileName
);
1717 return wxIsPathSeparator(pszFileName
[len
- 1]);
1720 // find a file in a list of directories, returns false if not found
1721 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1723 // we assume that it's not empty
1724 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1725 _("empty file name in wxFindFileInPath"));
1727 // skip path separator in the beginning of the file name if present
1728 if ( wxIsPathSeparator(*pszFile
) )
1731 // copy the path (strtok will modify it)
1732 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1733 wxStrcpy(szPath
, pszPath
);
1736 wxChar
*pc
, *save_ptr
;
1737 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1739 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1741 // search for the file in this directory
1743 if ( !wxEndsWithPathSeparator(pc
) )
1744 strFile
+= wxFILE_SEP_PATH
;
1747 if ( FileExists(strFile
) ) {
1753 // suppress warning about unused variable save_ptr when wxStrtok() is a
1754 // macro which throws away its third argument
1759 return pc
!= NULL
; // if true => we breaked from the loop
1762 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1767 // it can be empty, but it shouldn't be NULL
1768 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1770 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1773 // under Windows we understand both separators
1774 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1775 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1776 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1777 #else // assume Unix
1778 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1780 if ( pDot
== pszFileName
)
1782 // under Unix files like .profile are treated in a special way
1787 if ( pDot
< pLastSeparator
)
1789 // the dot is part of the path, not the start of the extension
1795 if ( pLastSeparator
)
1796 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1803 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1804 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1806 *pstrName
= wxString(start
, end
- start
);
1812 *pstrExt
= wxString(pDot
+ 1);
1820 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1824 stat(filename
.fn_str(), &buf
);
1825 return buf
.st_mtime
;
1829 //------------------------------------------------------------------------
1830 // wild character routines
1831 //------------------------------------------------------------------------
1833 bool wxIsWild( const wxString
& pattern
)
1835 wxString tmp
= pattern
;
1836 wxChar
*pat
= WXSTRINGCAST(tmp
);
1839 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1849 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1851 #if defined(HAVE_FNMATCH_H)
1853 // this probably won't work well for multibyte chars in Unicode mode?
1855 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1857 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1861 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1864 * WARNING: this code is broken!
1867 wxString tmp1
= pat
;
1868 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1869 wxString tmp2
= text
;
1870 wxChar
*str
= WXSTRINGCAST(tmp2
);
1873 bool done
= FALSE
, ret_code
, ok
;
1874 // Below is for vi fans
1875 const wxChar OB
= wxT('{'), CB
= wxT('}');
1877 // dot_special means '.' only matches '.'
1878 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1881 while ((*pattern
!= wxT('\0')) && (!done
)
1882 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1886 if (*pattern
!= wxT('\0'))
1892 while ((*str
!=wxT('\0'))
1893 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1896 while (*str
!= wxT('\0'))
1898 while (*pattern
!= wxT('\0'))
1905 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1909 if (*pattern
== wxT('\\')) {
1911 if (*pattern
== wxT('\0')) {
1916 if (*(pattern
+ 1) == wxT('-')) {
1919 if (*pattern
== wxT(']')) {
1923 if (*pattern
== wxT('\\')) {
1925 if (*pattern
== wxT('\0')) {
1930 if ((*str
< c
) || (*str
> *pattern
)) {
1934 } else if (*pattern
!= *str
) {
1939 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1940 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1944 if (*pattern
!= wxT('\0')) {
1954 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1957 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1958 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1959 if (*pattern
== wxT('\\'))
1961 ok
= (*pattern
++ == *cp
++);
1963 if (*pattern
== wxT('\0')) {
1969 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1970 if (*++pattern
== wxT('\\')) {
1971 if (*++pattern
== CB
)
1976 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1977 if (*++pattern
== wxT('\\')) {
1978 if (*++pattern
== CB
|| *pattern
== wxT(','))
1983 if (*pattern
!= wxT('\0'))
1988 if (*str
== *pattern
) {
1995 while (*pattern
== wxT('*'))
1997 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2003 #pragma warning(default:4706) // assignment within conditional expression