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"
35 // there are just too many of those...
37 #pragma warning(disable:4706) // assignment within conditional expression
44 #if !defined(__WATCOMC__)
45 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
53 #include <sys/types.h>
67 #include "wx/os2/private.h"
70 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
74 #endif // native Win compiler
78 #include <sys/unistd.h>
82 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
83 // this (3.1 I believe) and how to test for it.
84 // If this works for Borland 4.0 as well, then no worries.
96 // No, Cygwin doesn't appear to have fnmatch.h after all.
97 #if defined(HAVE_FNMATCH_H)
105 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 #define _MAXPATHLEN 500
111 extern wxChar
*wxBuffer
;
115 #include "morefile.h"
116 #include "moreextr.h"
117 #include "fullpath.h"
118 #include "fspcompa.h"
121 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
129 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
131 // VisualAge C++ V4.0 cannot have any external linkage const decs
132 // in headers included by more than one primary source
134 const off_t wxInvalidOffset
= (off_t
)-1;
137 // ============================================================================
139 // ============================================================================
141 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 )
277 if ((filename
!= wxT("")) && wxStat (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 == wxRename (wxCSTRINGCAST file1
, wxCSTRINGCAST file2
))
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
= wxRemove(file
);
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(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1079 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1080 #elif defined(__WXPM__)
1081 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1082 #else // !MSW and !OS/2 VAC++
1083 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1086 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1095 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1098 return FALSE
; //to be changed since rmdir exists in VMS7.x
1099 #elif defined( __WXMAC__ )
1100 return (rmdir(wxUnix2MacFilename( dir
)) == 0);
1101 #elif defined(__WXPM__)
1102 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1106 return FALSE
; // What to do?
1108 return (wxRmDir(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 wxString
strPath(pszPathName
);
1165 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1166 // so remove all trailing backslashes from the path - but don't do this for
1167 // the pathes "d:\" (which are different from "d:") nor for just "\"
1168 while ( wxEndsWithPathSeparator(strPath
) )
1170 size_t len
= strPath
.length();
1171 if ( len
== 1 || strPath
[len
- 1] == _T(':') )
1174 strPath
.Truncate(len
- 1);
1176 #endif // __WINDOWS__
1179 #ifndef __VISAGECPP__
1180 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1181 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1183 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1184 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1185 (st
.st_mode
== S_IFDIR
);
1190 // Get a temporary filename, opening and closing the file.
1191 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1197 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1199 wxChar tmp
[MAX_PATH
];
1200 wxChar tmpPath
[MAX_PATH
];
1201 ::GetTempPath(MAX_PATH
, tmpPath
);
1202 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1204 if (buf
) wxStrcpy(buf
, tmp
);
1205 else buf
= copystring(tmp
);
1209 static short last_temp
= 0; // cache last to speed things a bit
1210 // At most 1000 temp files to a process! We use a ring count.
1211 wxChar tmp
[100]; // FIXME static buffer
1213 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1215 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1216 if (!wxFileExists( tmp
))
1218 // Touch the file to create it (reserve name)
1219 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1224 wxStrcpy( buf
, tmp
);
1226 buf
= copystring( tmp
);
1230 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1231 if (buf
) buf
[0] = 0;
1232 return (wxChar
*) NULL
;
1236 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1239 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1248 // Get first file name matching given wild card.
1252 // Get first file name matching given wild card.
1253 // Flags are reserved for future use.
1255 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1256 static DIR *gs_dirStream
= (DIR *) NULL
;
1257 static wxString gs_strFileSpec
;
1258 static int gs_findFlags
= 0;
1261 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1265 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1267 closedir(gs_dirStream
); // edz 941103: better housekeping
1269 gs_findFlags
= flags
;
1271 gs_strFileSpec
= spec
;
1273 // Find path only so we can concatenate
1274 // found file onto path
1275 wxString
path(wxPathOnly(gs_strFileSpec
));
1277 // special case: path is really "/"
1278 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1280 // path is empty => Local directory
1284 gs_dirStream
= opendir(path
.fn_str());
1285 if ( !gs_dirStream
)
1287 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1292 result
= wxFindNextFile();
1294 #endif // !VMS6.x or earlier
1299 wxString
wxFindNextFile()
1303 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1304 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1306 // Find path only so we can concatenate
1307 // found file onto path
1308 wxString
path(wxPathOnly(gs_strFileSpec
));
1309 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1311 /* MATTHEW: special case: path is really "/" */
1312 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1316 struct dirent
*nextDir
;
1317 for ( nextDir
= readdir(gs_dirStream
);
1319 nextDir
= readdir(gs_dirStream
) )
1321 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1322 strcmp(nextDir
->d_name
, ".") &&
1323 strcmp(nextDir
->d_name
, "..") )
1326 if ( !path
.IsEmpty() )
1329 if ( path
!= wxT('/') )
1333 result
+= nextDir
->d_name
;
1335 // Only return "." and ".." when they match
1337 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1338 (strcmp(nextDir
->d_name
, "..") == 0))
1340 if ( (gs_findFlags
& wxDIR
) != 0 )
1346 isdir
= wxDirExists(result
);
1348 // and only return directories when flags & wxDIR
1349 if ( !gs_findFlags
||
1350 ((gs_findFlags
& wxDIR
) && isdir
) ||
1351 ((gs_findFlags
& wxFILE
) && !isdir
) )
1358 result
.Empty(); // not found
1360 closedir(gs_dirStream
);
1361 gs_dirStream
= (DIR *) NULL
;
1362 #endif // !VMS6.2 or earlier
1367 #elif defined(__WXMAC__)
1369 struct MacDirectoryIterator
1377 static int g_iter_flags
;
1379 static MacDirectoryIterator g_iter
;
1381 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1385 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1387 // Find path only so we can concatenate found file onto path
1388 wxString
path(wxPathOnly(spec
));
1389 if ( !path
.IsEmpty() )
1390 result
<< path
<< wxT('\\');
1394 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1395 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1396 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1397 g_iter
.m_index
= 0 ;
1400 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1402 return wxEmptyString
;
1404 return wxFindNextFile( ) ;
1407 wxString
wxFindNextFile()
1413 while ( err
== noErr
)
1416 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1417 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1418 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1422 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1425 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1433 return wxEmptyString
;
1437 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1442 return wxMacFSSpec2UnixFilename( &spec
) ;
1445 #elif defined(__WXMSW__)
1448 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1449 static WIN32_FIND_DATA gs_findDataStruct
;
1452 static struct ffblk gs_findDataStruct
;
1454 static struct _find_t gs_findDataStruct
;
1458 static wxString gs_strFileSpec
;
1459 static int gs_findFlags
= 0;
1461 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1465 gs_strFileSpec
= spec
;
1466 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1468 // Find path only so we can concatenate found file onto path
1469 wxString
path(wxPathOnly(gs_strFileSpec
));
1470 if ( !path
.IsEmpty() )
1471 result
<< path
<< wxT('\\');
1474 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1475 FindClose(gs_hFileStruct
);
1477 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1479 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1486 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1488 if (isdir
&& !(flags
& wxDIR
))
1489 return wxFindNextFile();
1490 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1491 return wxFindNextFile();
1493 result
+= gs_findDataStruct
.cFileName
;
1497 int flag
= _A_NORMAL
;
1502 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1504 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1510 attrib
= gs_findDataStruct
.ff_attrib
;
1512 attrib
= gs_findDataStruct
.attrib
;
1515 if (attrib
& _A_SUBDIR
) {
1516 if (!(gs_findFlags
& wxDIR
))
1517 return wxFindNextFile();
1518 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1519 return wxFindNextFile();
1523 gs_findDataStruct
.ff_name
1525 gs_findDataStruct
.name
1535 wxString
wxFindNextFile()
1539 // Find path only so we can concatenate found file onto path
1540 wxString
path(wxPathOnly(gs_strFileSpec
));
1545 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1548 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1551 FindClose(gs_hFileStruct
);
1552 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1556 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1558 if (isdir
&& !(gs_findFlags
& wxDIR
))
1560 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1563 if ( !path
.IsEmpty() )
1564 result
<< path
<< wxT('\\');
1565 result
<< gs_findDataStruct
.cFileName
;
1572 if (findnext(&gs_findDataStruct
) == 0)
1574 if (_dos_findnext(&gs_findDataStruct
) == 0)
1577 /* MATTHEW: [5] Check directory flag */
1581 attrib
= gs_findDataStruct
.ff_attrib
;
1583 attrib
= gs_findDataStruct
.attrib
;
1586 if (attrib
& _A_SUBDIR
) {
1587 if (!(gs_findFlags
& wxDIR
))
1589 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1595 gs_findDataStruct
.ff_name
1597 gs_findDataStruct
.name
1606 #elif defined(__WXPM__)
1608 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1613 // TODO: figure something out here for OS/2
1614 gs_strFileSpec = spec;
1615 gs_findFlags = flags;
1617 // Find path only so we can concatenate found file onto path
1618 wxString path(wxPathOnly(gs_strFileSpec));
1619 if ( !path.IsEmpty() )
1620 result << path << wxT('\\');
1622 int flag = _A_NORMAL;
1626 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1629 attrib = gs_findDataStruct.attrib;
1631 if (attrib & _A_SUBDIR) {
1632 if (!(gs_findFlags & wxDIR))
1633 return wxFindNextFile();
1634 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1635 return wxFindNextFile();
1637 result += gs_findDataStruct.name;
1643 wxString
wxFindNextFile()
1650 #endif // Unix/Windows/OS/2
1652 // Get current working directory.
1653 // If buf is NULL, allocates space using new, else
1655 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1658 buf
= new wxChar
[sz
+1];
1660 char *cbuf
= new char[sz
+1];
1662 if (_getcwd(cbuf
, sz
) == NULL
) {
1663 #elif defined( __WXMAC__)
1666 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1670 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1671 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1672 strcpy( buf
, res
) ;
1675 if (getcwd(cbuf
, sz
) == NULL
) {
1680 if (_getcwd(buf
, sz
) == NULL
) {
1681 #elif defined( __WXMAC__)
1684 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1688 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1689 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1690 strcpy( buf
, res
) ;
1692 #elif(__VISAGECPP__)
1694 rc
= ::DosQueryCurrentDir( 0 // current drive
1700 if (getcwd(buf
, sz
) == NULL
) {
1708 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1717 static const size_t maxPathLen
= 1024;
1720 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1721 str
.UngetWriteBuf();
1726 bool wxSetWorkingDirectory(const wxString
& d
)
1728 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1729 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1730 #elif defined(__WXPM__)
1731 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1732 #elif defined(__WINDOWS__)
1735 return (bool)(SetCurrentDirectory(d
) != 0);
1737 // Must change drive, too.
1738 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1741 wxChar firstChar
= d
[0];
1745 firstChar
= firstChar
- 32;
1747 // To a drive number
1748 unsigned int driveNo
= firstChar
- 64;
1751 unsigned int noDrives
;
1752 _dos_setdrive(driveNo
, &noDrives
);
1755 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1763 // Get the OS directory if appropriate (such as the Windows directory).
1764 // On non-Windows platform, probably just return the empty string.
1765 wxString
wxGetOSDirectory()
1769 GetWindowsDirectory(buf
, 256);
1770 return wxString(buf
);
1772 return wxEmptyString
;
1776 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1778 size_t len
= wxStrlen(pszFileName
);
1782 return wxIsPathSeparator(pszFileName
[len
- 1]);
1785 // find a file in a list of directories, returns false if not found
1786 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1788 // we assume that it's not empty
1789 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1790 _T("empty file name in wxFindFileInPath"));
1792 // skip path separator in the beginning of the file name if present
1793 if ( wxIsPathSeparator(*pszFile
) )
1796 // copy the path (strtok will modify it)
1797 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1798 wxStrcpy(szPath
, pszPath
);
1801 wxChar
*pc
, *save_ptr
;
1802 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1804 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1806 // search for the file in this directory
1808 if ( !wxEndsWithPathSeparator(pc
) )
1809 strFile
+= wxFILE_SEP_PATH
;
1812 if ( FileExists(strFile
) ) {
1818 // suppress warning about unused variable save_ptr when wxStrtok() is a
1819 // macro which throws away its third argument
1824 return pc
!= NULL
; // if true => we breaked from the loop
1827 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1832 // it can be empty, but it shouldn't be NULL
1833 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1835 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1838 // under Windows we understand both separators
1839 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1840 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1841 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1842 #else // assume Unix
1843 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1847 if ( (pDot
== pszFileName
) || (*(pDot
- 1) == wxFILE_SEP_PATH_UNIX
) )
1849 // under Unix, dot may be (and commonly is) the first character of the
1850 // filename, don't treat the entire filename as extension in this case
1856 if ( pDot
&& (pDot
< pLastSeparator
) )
1858 // the dot is part of the path, not the start of the extension
1864 if ( pLastSeparator
)
1865 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1872 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1873 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1875 *pstrName
= wxString(start
, end
- start
);
1881 *pstrExt
= wxString(pDot
+ 1);
1887 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1891 wxStat(filename
.fn_str(), &buf
);
1892 return buf
.st_mtime
;
1896 //------------------------------------------------------------------------
1897 // wild character routines
1898 //------------------------------------------------------------------------
1900 bool wxIsWild( const wxString
& pattern
)
1902 wxString tmp
= pattern
;
1903 wxChar
*pat
= WXSTRINGCAST(tmp
);
1906 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1916 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1918 #if defined(HAVE_FNMATCH_H)
1920 // this probably won't work well for multibyte chars in Unicode mode?
1922 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1924 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1928 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1931 * WARNING: this code is broken!
1934 wxString tmp1
= pat
;
1935 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1936 wxString tmp2
= text
;
1937 wxChar
*str
= WXSTRINGCAST(tmp2
);
1940 bool done
= FALSE
, ret_code
, ok
;
1941 // Below is for vi fans
1942 const wxChar OB
= wxT('{'), CB
= wxT('}');
1944 // dot_special means '.' only matches '.'
1945 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1948 while ((*pattern
!= wxT('\0')) && (!done
)
1949 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1953 if (*pattern
!= wxT('\0'))
1959 while ((*str
!=wxT('\0'))
1960 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1963 while (*str
!= wxT('\0'))
1965 while (*pattern
!= wxT('\0'))
1972 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1976 if (*pattern
== wxT('\\')) {
1978 if (*pattern
== wxT('\0')) {
1983 if (*(pattern
+ 1) == wxT('-')) {
1986 if (*pattern
== wxT(']')) {
1990 if (*pattern
== wxT('\\')) {
1992 if (*pattern
== wxT('\0')) {
1997 if ((*str
< c
) || (*str
> *pattern
)) {
2001 } else if (*pattern
!= *str
) {
2006 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
2007 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
2011 if (*pattern
!= wxT('\0')) {
2021 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2024 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
2025 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
2026 if (*pattern
== wxT('\\'))
2028 ok
= (*pattern
++ == *cp
++);
2030 if (*pattern
== wxT('\0')) {
2036 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2037 if (*++pattern
== wxT('\\')) {
2038 if (*++pattern
== CB
)
2043 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2044 if (*++pattern
== wxT('\\')) {
2045 if (*++pattern
== CB
|| *pattern
== wxT(','))
2050 if (*pattern
!= wxT('\0'))
2055 if (*str
== *pattern
) {
2062 while (*pattern
== wxT('*'))
2064 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2070 #pragma warning(default:4706) // assignment within conditional expression