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__
1180 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1181 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1184 // Get a temporary filename, opening and closing the file.
1185 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1191 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1193 wxChar tmp
[MAX_PATH
];
1194 wxChar tmpPath
[MAX_PATH
];
1195 ::GetTempPath(MAX_PATH
, tmpPath
);
1196 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1198 if (buf
) wxStrcpy(buf
, tmp
);
1199 else buf
= copystring(tmp
);
1203 static short last_temp
= 0; // cache last to speed things a bit
1204 // At most 1000 temp files to a process! We use a ring count.
1205 wxChar tmp
[100]; // FIXME static buffer
1207 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1209 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1210 if (!wxFileExists( tmp
))
1212 // Touch the file to create it (reserve name)
1213 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1218 wxStrcpy( buf
, tmp
);
1220 buf
= copystring( tmp
);
1224 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1225 if (buf
) buf
[0] = 0;
1226 return (wxChar
*) NULL
;
1230 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1233 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1242 // Get first file name matching given wild card.
1246 // Get first file name matching given wild card.
1247 // Flags are reserved for future use.
1249 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1250 static DIR *gs_dirStream
= (DIR *) NULL
;
1251 static wxString gs_strFileSpec
;
1252 static int gs_findFlags
= 0;
1255 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1259 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1261 closedir(gs_dirStream
); // edz 941103: better housekeping
1263 gs_findFlags
= flags
;
1265 gs_strFileSpec
= spec
;
1267 // Find path only so we can concatenate
1268 // found file onto path
1269 wxString
path(wxPathOnly(gs_strFileSpec
));
1271 // special case: path is really "/"
1272 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1274 // path is empty => Local directory
1278 gs_dirStream
= opendir(path
.fn_str());
1279 if ( !gs_dirStream
)
1281 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1286 result
= wxFindNextFile();
1288 #endif // !VMS6.x or earlier
1293 wxString
wxFindNextFile()
1297 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1298 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1300 // Find path only so we can concatenate
1301 // found file onto path
1302 wxString
path(wxPathOnly(gs_strFileSpec
));
1303 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1305 /* MATTHEW: special case: path is really "/" */
1306 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1310 struct dirent
*nextDir
;
1311 for ( nextDir
= readdir(gs_dirStream
);
1313 nextDir
= readdir(gs_dirStream
) )
1315 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1316 strcmp(nextDir
->d_name
, ".") &&
1317 strcmp(nextDir
->d_name
, "..") )
1320 if ( !path
.IsEmpty() )
1323 if ( path
!= wxT('/') )
1327 result
+= nextDir
->d_name
;
1329 // Only return "." and ".." when they match
1331 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1332 (strcmp(nextDir
->d_name
, "..") == 0))
1334 if ( (gs_findFlags
& wxDIR
) != 0 )
1340 isdir
= wxDirExists(result
);
1342 // and only return directories when flags & wxDIR
1343 if ( !gs_findFlags
||
1344 ((gs_findFlags
& wxDIR
) && isdir
) ||
1345 ((gs_findFlags
& wxFILE
) && !isdir
) )
1352 result
.Empty(); // not found
1354 closedir(gs_dirStream
);
1355 gs_dirStream
= (DIR *) NULL
;
1356 #endif // !VMS6.2 or earlier
1361 #elif defined(__WXMAC__)
1363 struct MacDirectoryIterator
1371 static int g_iter_flags
;
1373 static MacDirectoryIterator g_iter
;
1375 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1379 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1381 // Find path only so we can concatenate found file onto path
1382 wxString
path(wxPathOnly(spec
));
1383 if ( !path
.IsEmpty() )
1384 result
<< path
<< wxT('\\');
1388 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1389 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1390 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1391 g_iter
.m_index
= 0 ;
1394 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1396 return wxEmptyString
;
1398 return wxFindNextFile( ) ;
1401 wxString
wxFindNextFile()
1407 while ( err
== noErr
)
1410 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1411 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1412 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1416 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1419 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1427 return wxEmptyString
;
1431 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1436 return wxMacFSSpec2UnixFilename( &spec
) ;
1439 #elif defined(__WXMSW__)
1442 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1443 static WIN32_FIND_DATA gs_findDataStruct
;
1446 static struct ffblk gs_findDataStruct
;
1448 static struct _find_t gs_findDataStruct
;
1452 static wxString gs_strFileSpec
;
1453 static int gs_findFlags
= 0;
1455 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1459 gs_strFileSpec
= spec
;
1460 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1462 // Find path only so we can concatenate found file onto path
1463 wxString
path(wxPathOnly(gs_strFileSpec
));
1464 if ( !path
.IsEmpty() )
1465 result
<< path
<< wxT('\\');
1468 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1469 FindClose(gs_hFileStruct
);
1471 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1473 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1480 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1482 if (isdir
&& !(flags
& wxDIR
))
1483 return wxFindNextFile();
1484 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1485 return wxFindNextFile();
1487 result
+= gs_findDataStruct
.cFileName
;
1491 int flag
= _A_NORMAL
;
1496 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1498 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1504 attrib
= gs_findDataStruct
.ff_attrib
;
1506 attrib
= gs_findDataStruct
.attrib
;
1509 if (attrib
& _A_SUBDIR
) {
1510 if (!(gs_findFlags
& wxDIR
))
1511 return wxFindNextFile();
1512 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1513 return wxFindNextFile();
1517 gs_findDataStruct
.ff_name
1519 gs_findDataStruct
.name
1529 wxString
wxFindNextFile()
1533 // Find path only so we can concatenate found file onto path
1534 wxString
path(wxPathOnly(gs_strFileSpec
));
1539 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1542 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1545 FindClose(gs_hFileStruct
);
1546 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1550 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1552 if (isdir
&& !(gs_findFlags
& wxDIR
))
1554 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1557 if ( !path
.IsEmpty() )
1558 result
<< path
<< wxT('\\');
1559 result
<< gs_findDataStruct
.cFileName
;
1566 if (findnext(&gs_findDataStruct
) == 0)
1568 if (_dos_findnext(&gs_findDataStruct
) == 0)
1571 /* MATTHEW: [5] Check directory flag */
1575 attrib
= gs_findDataStruct
.ff_attrib
;
1577 attrib
= gs_findDataStruct
.attrib
;
1580 if (attrib
& _A_SUBDIR
) {
1581 if (!(gs_findFlags
& wxDIR
))
1583 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1589 gs_findDataStruct
.ff_name
1591 gs_findDataStruct
.name
1600 #elif defined(__WXPM__)
1602 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1607 // TODO: figure something out here for OS/2
1608 gs_strFileSpec = spec;
1609 gs_findFlags = flags;
1611 // Find path only so we can concatenate found file onto path
1612 wxString path(wxPathOnly(gs_strFileSpec));
1613 if ( !path.IsEmpty() )
1614 result << path << wxT('\\');
1616 int flag = _A_NORMAL;
1620 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1623 attrib = gs_findDataStruct.attrib;
1625 if (attrib & _A_SUBDIR) {
1626 if (!(gs_findFlags & wxDIR))
1627 return wxFindNextFile();
1628 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1629 return wxFindNextFile();
1631 result += gs_findDataStruct.name;
1637 wxString
wxFindNextFile()
1644 #endif // Unix/Windows/OS/2
1646 // Get current working directory.
1647 // If buf is NULL, allocates space using new, else
1649 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1652 buf
= new wxChar
[sz
+1];
1654 char *cbuf
= new char[sz
+1];
1656 if (_getcwd(cbuf
, sz
) == NULL
) {
1657 #elif defined( __WXMAC__)
1660 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1664 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1665 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1666 strcpy( buf
, res
) ;
1669 if (getcwd(cbuf
, sz
) == NULL
) {
1674 if (_getcwd(buf
, sz
) == NULL
) {
1675 #elif defined( __WXMAC__)
1678 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1682 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1683 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1684 strcpy( buf
, res
) ;
1686 #elif(__VISAGECPP__)
1688 rc
= ::DosQueryCurrentDir( 0 // current drive
1694 if (getcwd(buf
, sz
) == NULL
) {
1702 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1711 static const size_t maxPathLen
= 1024;
1714 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1715 str
.UngetWriteBuf();
1720 bool wxSetWorkingDirectory(const wxString
& d
)
1722 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1723 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1724 #elif defined(__WXPM__)
1725 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1726 #elif defined(__WINDOWS__)
1729 return (bool)(SetCurrentDirectory(d
) != 0);
1731 // Must change drive, too.
1732 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1735 wxChar firstChar
= d
[0];
1739 firstChar
= firstChar
- 32;
1741 // To a drive number
1742 unsigned int driveNo
= firstChar
- 64;
1745 unsigned int noDrives
;
1746 _dos_setdrive(driveNo
, &noDrives
);
1749 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1757 // Get the OS directory if appropriate (such as the Windows directory).
1758 // On non-Windows platform, probably just return the empty string.
1759 wxString
wxGetOSDirectory()
1763 GetWindowsDirectory(buf
, 256);
1764 return wxString(buf
);
1766 return wxEmptyString
;
1770 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1772 size_t len
= wxStrlen(pszFileName
);
1776 return wxIsPathSeparator(pszFileName
[len
- 1]);
1779 // find a file in a list of directories, returns false if not found
1780 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1782 // we assume that it's not empty
1783 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1784 _T("empty file name in wxFindFileInPath"));
1786 // skip path separator in the beginning of the file name if present
1787 if ( wxIsPathSeparator(*pszFile
) )
1790 // copy the path (strtok will modify it)
1791 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1792 wxStrcpy(szPath
, pszPath
);
1795 wxChar
*pc
, *save_ptr
;
1796 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1798 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1800 // search for the file in this directory
1802 if ( !wxEndsWithPathSeparator(pc
) )
1803 strFile
+= wxFILE_SEP_PATH
;
1806 if ( FileExists(strFile
) ) {
1812 // suppress warning about unused variable save_ptr when wxStrtok() is a
1813 // macro which throws away its third argument
1818 return pc
!= NULL
; // if true => we breaked from the loop
1821 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1826 // it can be empty, but it shouldn't be NULL
1827 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1829 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1832 // under Windows we understand both separators
1833 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1834 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1835 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1836 #else // assume Unix
1837 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1841 if ( (pDot
== pszFileName
) || (*(pDot
- 1) == wxFILE_SEP_PATH_UNIX
) )
1843 // under Unix, dot may be (and commonly is) the first character of the
1844 // filename, don't treat the entire filename as extension in this case
1850 if ( pDot
&& (pDot
< pLastSeparator
) )
1852 // the dot is part of the path, not the start of the extension
1858 if ( pLastSeparator
)
1859 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1866 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1867 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1869 *pstrName
= wxString(start
, end
- start
);
1875 *pstrExt
= wxString(pDot
+ 1);
1881 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1885 wxStat(filename
.fn_str(), &buf
);
1886 return buf
.st_mtime
;
1890 //------------------------------------------------------------------------
1891 // wild character routines
1892 //------------------------------------------------------------------------
1894 bool wxIsWild( const wxString
& pattern
)
1896 wxString tmp
= pattern
;
1897 wxChar
*pat
= WXSTRINGCAST(tmp
);
1900 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1910 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1912 #if defined(HAVE_FNMATCH_H)
1914 // this probably won't work well for multibyte chars in Unicode mode?
1916 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1918 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1922 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1925 * WARNING: this code is broken!
1928 wxString tmp1
= pat
;
1929 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1930 wxString tmp2
= text
;
1931 wxChar
*str
= WXSTRINGCAST(tmp2
);
1934 bool done
= FALSE
, ret_code
, ok
;
1935 // Below is for vi fans
1936 const wxChar OB
= wxT('{'), CB
= wxT('}');
1938 // dot_special means '.' only matches '.'
1939 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1942 while ((*pattern
!= wxT('\0')) && (!done
)
1943 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1947 if (*pattern
!= wxT('\0'))
1953 while ((*str
!=wxT('\0'))
1954 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1957 while (*str
!= wxT('\0'))
1959 while (*pattern
!= wxT('\0'))
1966 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1970 if (*pattern
== wxT('\\')) {
1972 if (*pattern
== wxT('\0')) {
1977 if (*(pattern
+ 1) == wxT('-')) {
1980 if (*pattern
== wxT(']')) {
1984 if (*pattern
== wxT('\\')) {
1986 if (*pattern
== wxT('\0')) {
1991 if ((*str
< c
) || (*str
> *pattern
)) {
1995 } else if (*pattern
!= *str
) {
2000 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
2001 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
2005 if (*pattern
!= wxT('\0')) {
2015 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2018 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
2019 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
2020 if (*pattern
== wxT('\\'))
2022 ok
= (*pattern
++ == *cp
++);
2024 if (*pattern
== wxT('\0')) {
2030 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2031 if (*++pattern
== wxT('\\')) {
2032 if (*++pattern
== CB
)
2037 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2038 if (*++pattern
== wxT('\\')) {
2039 if (*++pattern
== CB
|| *pattern
== wxT(','))
2044 if (*pattern
!= wxT('\0'))
2049 if (*str
== *pattern
) {
2056 while (*pattern
== wxT('*'))
2058 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2064 #pragma warning(default:4706) // assignment within conditional expression