1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "filefn.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
39 // there are just too many of those...
41 #pragma warning(disable:4706) // assignment within conditional expression
48 #if !defined(__WATCOMC__)
49 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
57 #include <sys/types.h>
74 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
78 #endif // native Win compiler
82 #include <sys/unistd.h>
86 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
87 // this (3.1 I believe) and how to test for it.
88 // If this works for Borland 4.0 as well, then no worries.
100 // No, Cygwin doesn't appear to have fnmatch.h after all.
101 #if defined(HAVE_FNMATCH_H)
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 #define _MAXPATHLEN 500
115 extern wxChar
*wxBuffer
;
119 #include "morefile.h"
120 #include "moreextr.h"
121 #include "fullpath.h"
122 #include "fspcompa.h"
125 #if !USE_SHARED_LIBRARIES
126 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
129 // ----------------------------------------------------------------------------
131 // ----------------------------------------------------------------------------
133 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
135 // ============================================================================
137 // ============================================================================
139 void wxPathList::Add (const wxString
& path
)
141 wxStringList::Add (WXSTRINGCAST path
);
144 // Add paths e.g. from the PATH environment variable
145 void wxPathList::AddEnvList (const wxString
& envVariable
)
147 static const wxChar PATH_TOKS
[] =
149 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
154 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
157 wxChar
*s
= copystring (val
);
158 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
162 Add (copystring (token
));
165 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
166 Add (wxString(token
));
170 // suppress warning about unused variable save_ptr when wxStrtok() is a
171 // macro which throws away its third argument
178 // Given a full filename (with path), ensure that that file can
179 // be accessed again USING FILENAME ONLY by adding the path
180 // to the list if not already there.
181 void wxPathList::EnsureFileAccessible (const wxString
& path
)
183 wxString
path_only(wxPathOnly(path
));
184 if ( !path_only
.IsEmpty() )
186 if ( !Member(path_only
) )
191 bool wxPathList::Member (const wxString
& path
)
193 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
195 wxString
path2((wxChar
*) node
->Data ());
197 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
199 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
201 // Case sensitive File System
202 path
.CompareTo (path2
) == 0
210 wxString
wxPathList::FindValidPath (const wxString
& file
)
212 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
213 return wxString(wxFileFunctionsBuffer
);
215 wxChar buf
[_MAXPATHLEN
];
216 wxStrcpy(buf
, wxFileFunctionsBuffer
);
218 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
219 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
221 for (wxNode
* node
= First (); node
; node
= node
->Next ())
223 wxChar
*path
= (wxChar
*) node
->Data ();
224 wxStrcpy (wxFileFunctionsBuffer
, path
);
225 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
226 if (ch
!= wxT('\\') && ch
!= wxT('/'))
227 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
228 wxStrcat (wxFileFunctionsBuffer
, filename
);
230 Unix2DosFilename (wxFileFunctionsBuffer
);
232 if (wxFileExists (wxFileFunctionsBuffer
))
234 return wxString(wxFileFunctionsBuffer
); // Found!
238 return wxString(wxT("")); // Not found
241 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
243 wxString f
= FindValidPath(file
);
244 if ( wxIsAbsolutePath(f
) )
248 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
250 if ( !wxEndsWithPathSeparator(buf
) )
252 buf
+= wxFILE_SEP_PATH
;
260 wxFileExists (const wxString
& filename
)
262 #ifdef __GNUWIN32__ // (fix a B20 bug)
263 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
267 #elif defined(__WXMAC__)
269 if (filename
&& stat (wxUnix2MacFilename(filename
), &stbuf
) == 0 )
280 if ((filename
!= wxT("")) && stat (wxFNSTRINGCAST filename
.fn_str(), &stbuf
) == 0)
286 /* Vadim's alternative implementation
288 // does the file exist?
289 bool wxFileExists(const char *pszFileName)
292 return !access(pszFileName, 0) &&
293 !stat(pszFileName, &st) &&
294 (st.st_mode & S_IFREG);
299 wxIsAbsolutePath (const wxString
& filename
)
301 if (filename
!= wxT(""))
303 if (filename
[0] == wxT('/')
305 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
309 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
318 * Strip off any extension (dot something) from end of file,
319 * IF one exists. Inserts zero into buffer.
323 void wxStripExtension(wxChar
*buffer
)
325 int len
= wxStrlen(buffer
);
329 if (buffer
[i
] == wxT('.'))
338 void wxStripExtension(wxString
& buffer
)
340 size_t len
= buffer
.Length();
344 if (buffer
.GetChar(i
) == wxT('.'))
346 buffer
= buffer
.Left(i
);
353 // Destructive removal of /./ and /../ stuff
354 wxChar
*wxRealPath (wxChar
*path
)
357 static const wxChar SEP
= wxT('\\');
358 Unix2DosFilename(path
);
360 static const wxChar SEP
= wxT('/');
362 if (path
[0] && path
[1]) {
363 /* MATTHEW: special case "/./x" */
365 if (path
[2] == SEP
&& path
[1] == wxT('.'))
373 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
376 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
377 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
378 && (q
- 1 <= path
|| q
[-1] != SEP
))
381 if (path
[0] == wxT('\0'))
387 /* Check that path[2] is NULL! */
388 else if (path
[1] == wxT(':') && !path
[2])
397 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
406 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
408 if (filename
== wxT(""))
409 return (wxChar
*) NULL
;
411 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
412 wxChar buf
[_MAXPATHLEN
];
414 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
415 wxChar ch
= buf
[wxStrlen(buf
) - 1];
417 if (ch
!= wxT('\\') && ch
!= wxT('/'))
418 wxStrcat(buf
, wxT("\\"));
421 wxStrcat(buf
, wxT("/"));
423 wxStrcat(buf
, wxFileFunctionsBuffer
);
424 return copystring( wxRealPath(buf
) );
426 return copystring( wxFileFunctionsBuffer
);
432 ~user/ => user's home dir
433 If the environment variable a = "foo" and b = "bar" then:
450 /* input name in name, pathname output to buf. */
452 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
454 register wxChar
*d
, *s
, *nm
;
455 wxChar lnm
[_MAXPATHLEN
];
458 // Some compilers don't like this line.
459 // const wxChar trimchars[] = wxT("\n \t");
462 trimchars
[0] = wxT('\n');
463 trimchars
[1] = wxT(' ');
464 trimchars
[2] = wxT('\t');
468 const wxChar SEP
= wxT('\\');
470 const wxChar SEP
= wxT('/');
473 if (name
== NULL
|| *name
== wxT('\0'))
475 nm
= copystring(name
); // Make a scratch copy
478 /* Skip leading whitespace and cr */
479 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
481 /* And strip off trailing whitespace and cr */
482 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
483 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
491 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
494 /* Expand inline environment variables */
512 while ((*d
++ = *s
)) {
514 if (*s
== wxT('\\')) {
515 if ((*(d
- 1) = *++s
)) {
524 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
526 if (*s
++ == wxT('$'))
529 register wxChar
*start
= d
;
530 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
531 register wxChar
*value
;
533 // VA gives assignment in logical expr warning
539 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
544 value
= wxGetenv(braces
? start
+ 1 : start
);
547 // VA gives assignment in logical expr warning
548 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
550 for ((d
= start
- 1); (*d
++ = *value
++););
559 /* Expand ~ and ~user */
562 if (nm
[0] == wxT('~') && !q
)
565 if (nm
[1] == SEP
|| nm
[1] == 0)
567 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
568 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
573 { /* ~user/filename */
574 register wxChar
*nnm
;
575 register wxChar
*home
;
576 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
577 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
578 was_sep
= (*s
== SEP
);
579 nnm
= *s
? s
+ 1 : s
;
581 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
582 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
583 if (was_sep
) /* replace only if it was there: */
594 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
596 while (wxT('\0') != (*d
++ = *s
++))
599 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
604 // VA gives assignment in logical expr warning
608 while ((*d
++ = *s
++));
610 delete[] nm_tmp
; // clean up alloc
611 /* Now clean up the buffer */
612 return wxRealPath(buf
);
615 /* Contract Paths to be build upon an environment variable
618 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
620 The call wxExpandPath can convert these back!
623 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
625 static wxChar dest
[_MAXPATHLEN
];
627 if (filename
== wxT(""))
628 return (wxChar
*) NULL
;
630 wxStrcpy (dest
, WXSTRINGCAST filename
);
632 Unix2DosFilename(dest
);
635 // Handle environment
636 const wxChar
*val
= (const wxChar
*) NULL
;
637 wxChar
*tcp
= (wxChar
*) NULL
;
638 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
639 (tcp
= wxStrstr (dest
, val
)) != NULL
)
641 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
644 wxStrcpy (tcp
, WXSTRINGCAST envname
);
645 wxStrcat (tcp
, wxT("}"));
646 wxStrcat (tcp
, wxFileFunctionsBuffer
);
649 // Handle User's home (ignore root homes!)
651 if ((val
= wxGetUserHome (user
)) != NULL
&&
652 (len
= wxStrlen(val
)) > 2 &&
653 wxStrncmp(dest
, val
, len
) == 0)
655 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
657 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
659 // strcat(wxFileFunctionsBuffer, "\\");
661 // strcat(wxFileFunctionsBuffer, "/");
663 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
664 wxStrcpy (dest
, wxFileFunctionsBuffer
);
670 // Return just the filename, not the path
672 wxChar
*wxFileNameFromPath (wxChar
*path
)
676 register wxChar
*tcp
;
678 tcp
= path
+ wxStrlen (path
);
679 while (--tcp
>= path
)
681 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
683 || *tcp
== wxT(':') || *tcp
== wxT(']'))
689 #if defined(__WXMSW__) || defined(__WXPM__)
690 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
697 wxString
wxFileNameFromPath (const wxString
& path1
)
699 if (path1
!= wxT(""))
702 wxChar
*path
= WXSTRINGCAST path1
;
703 register wxChar
*tcp
;
705 tcp
= path
+ wxStrlen (path
);
706 while (--tcp
>= path
)
708 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
710 || *tcp
== wxT(':') || *tcp
== wxT(']'))
714 return wxString(tcp
+ 1);
716 #if defined(__WXMSW__) || defined(__WXPM__)
717 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
718 return wxString(path
+ 2);
721 // Yes, this should return the path, not an empty string, otherwise
722 // we get "thing.txt" -> "".
726 // Return just the directory, or NULL if no directory
728 wxPathOnly (wxChar
*path
)
732 static wxChar buf
[_MAXPATHLEN
];
735 wxStrcpy (buf
, path
);
737 int l
= wxStrlen(path
);
742 // Search backward for a backward or forward slash
743 while (!done
&& i
> -1)
746 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
760 #if defined(__WXMSW__) || defined(__WXPM__)
761 // Try Drive specifier
762 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
764 // A:junk --> A:. (since A:.\junk Not A:\junk)
772 return (wxChar
*) NULL
;
775 // Return just the directory, or NULL if no directory
776 wxString
wxPathOnly (const wxString
& path
)
780 wxChar buf
[_MAXPATHLEN
];
783 wxStrcpy (buf
, WXSTRINGCAST path
);
785 int l
= path
.Length();
790 // Search backward for a backward or forward slash
791 while (!done
&& i
> -1)
794 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
803 return wxString(buf
);
808 #if defined(__WXMSW__) || defined(__WXPM__)
809 // Try Drive specifier
810 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
812 // A:junk --> A:. (since A:.\junk Not A:\junk)
815 return wxString(buf
);
820 return wxString(wxT(""));
823 // Utility for converting delimiters in DOS filenames to UNIX style
824 // and back again - or we get nasty problems with delimiters.
825 // Also, convert to lower case, since case is significant in UNIX.
829 static char sMacFileNameConversion
[ 1000 ] ;
831 wxString
wxMac2UnixFilename (const char *str
)
833 char *s
= sMacFileNameConversion
;
837 memmove( s
+1 , s
,strlen( s
) + 1) ;
848 *s
= wxTolower (*s
); // Case INDEPENDENT
852 return wxString (sMacFileNameConversion
) ;
855 wxString
wxUnix2MacFilename (const char *str
)
857 char *s
= sMacFileNameConversion
;
863 // relative path , since it goes on with slash which is translated to a :
864 memmove( s
, s
+1 ,strlen( s
) ) ;
866 else if ( *s
== '/' )
868 // absolute path -> on mac just start with the drive name
869 memmove( s
, s
+1 ,strlen( s
) ) ;
873 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
877 if (*s
== '/' || *s
== '\\')
879 // convert any back-directory situations
880 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
883 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
892 return wxString (sMacFileNameConversion
) ;
895 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
900 FSpGetFullPath( spec
, &length
, &myPath
) ;
901 ::SetHandleSize( myPath
, length
+ 1 ) ;
903 (*myPath
)[length
] = 0 ;
904 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
905 (*myPath
)[length
-1] = 0 ;
907 wxString
result( (char*) *myPath
) ;
908 ::HUnlock( myPath
) ;
909 ::DisposeHandle( myPath
) ;
913 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
915 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
918 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
920 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
923 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
925 wxString var
= wxUnix2MacFilename( path
) ;
926 wxMacFilename2FSSpec( var
, spec
) ;
931 wxDos2UnixFilename (char *s
)
940 *s
= wxTolower (*s
); // Case INDEPENDENT
947 #if defined(__WXMSW__) || defined(__WXPM__)
948 wxUnix2DosFilename (char *s
)
950 wxUnix2DosFilename (char *WXUNUSED(s
) )
953 // Yes, I really mean this to happen under DOS only! JACS
954 #if defined(__WXMSW__) || defined(__WXPM__)
965 // Concatenate two files to form third
967 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
969 wxChar
*outfile
= wxGetTempFileName("cat");
971 FILE *fp1
= (FILE *) NULL
;
972 FILE *fp2
= (FILE *) NULL
;
973 FILE *fp3
= (FILE *) NULL
;
974 // Open the inputs and outputs
976 if ((fp1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
||
977 (fp2
= fopen (wxUnix2MacFilename( file2
), "rb")) == NULL
||
978 (fp3
= fopen (wxUnix2MacFilename( outfile
), "wb")) == NULL
)
980 if ((fp1
= wxFopen (WXSTRINGCAST file1
, wxT("rb"))) == NULL
||
981 (fp2
= wxFopen (WXSTRINGCAST file2
, wxT("rb"))) == NULL
||
982 (fp3
= wxFopen (outfile
, wxT("wb"))) == NULL
)
995 while ((ch
= getc (fp1
)) != EOF
)
996 (void) putc (ch
, fp3
);
999 while ((ch
= getc (fp2
)) != EOF
)
1000 (void) putc (ch
, fp3
);
1004 bool result
= wxRenameFile(outfile
, file3
);
1011 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
1018 if ((fd1
= fopen (wxUnix2MacFilename( file1
), "rb")) == NULL
)
1020 if ((fd2
= fopen (wxUnix2MacFilename( file2
), "wb")) == NULL
)
1022 if ((fd1
= wxFopen (WXSTRINGCAST file1
, wxT("rb"))) == NULL
)
1024 if ((fd2
= wxFopen (WXSTRINGCAST file2
, wxT("wb"))) == NULL
)
1031 while ((ch
= getc (fd1
)) != EOF
)
1032 (void) putc (ch
, fd2
);
1040 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1043 if (0 == rename (wxUnix2MacFilename( file1
), wxUnix2MacFilename( file2
)))
1046 // Normal system call
1047 if (0 == rename (wxFNSTRINGCAST file1
.fn_str(), wxFNSTRINGCAST file2
.fn_str()))
1051 if (wxCopyFile(file1
, file2
)) {
1052 wxRemoveFile(file1
);
1059 bool wxRemoveFile(const wxString
& file
)
1061 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1062 int flag
= remove(wxFNSTRINGCAST file
.fn_str());
1063 #elif defined( __WXMAC__ )
1064 int flag
= unlink(wxUnix2MacFilename( file
));
1066 int flag
= unlink(wxFNSTRINGCAST file
.fn_str());
1068 return (flag
== 0) ;
1071 bool wxMkdir(const wxString
& dir
, int perm
)
1073 #if defined( __WXMAC__ )
1074 return (mkdir(wxUnix2MacFilename( dir
) , 0 ) == 0);
1076 const wxChar
*dirname
= dir
.c_str();
1078 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1079 // for the GNU compiler
1080 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1081 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1082 #else // MSW and OS/2
1083 if ( mkdir(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);
1104 return FALSE
; // What to do?
1106 return (rmdir(wxFNSTRINGCAST dir
.fn_str()) == 0);
1113 bool wxDirExists(const wxString
& dir
)
1116 return FALSE
; //To be changed since stat exists in VMS7.x
1117 #elif !defined(__WXMSW__)
1119 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1122 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1123 #if defined(__WIN32__)
1124 WIN32_FIND_DATA fileInfo
;
1127 struct ffblk fileInfo
;
1129 struct find_t fileInfo
;
1133 #if defined(__WIN32__)
1134 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1136 if (h
==INVALID_HANDLE_VALUE
)
1140 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1143 // In Borland findfirst has a different argument
1144 // ordering from _dos_findfirst. But _dos_findfirst
1145 // _should_ be ok in both MS and Borland... why not?
1147 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1149 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1158 // does the path exists? (may have or not '/' or '\\' at the end)
1159 bool wxPathExists(const wxChar
*pszPathName
)
1161 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1162 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1163 wxString
strPath(pszPathName
);
1164 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != wxT('\0') )
1165 strPath
.Last() = wxT('\0');
1173 return stat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1176 // Get a temporary filename, opening and closing the file.
1177 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1183 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1185 wxChar tmp
[MAX_PATH
];
1186 wxChar tmpPath
[MAX_PATH
];
1187 ::GetTempPath(MAX_PATH
, tmpPath
);
1188 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1190 if (buf
) wxStrcpy(buf
, tmp
);
1191 else buf
= copystring(tmp
);
1195 static short last_temp
= 0; // cache last to speed things a bit
1196 // At most 1000 temp files to a process! We use a ring count.
1197 wxChar tmp
[100]; // FIXME static buffer
1199 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1201 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1202 if (!wxFileExists( tmp
))
1204 // Touch the file to create it (reserve name)
1205 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1210 wxStrcpy( buf
, tmp
);
1212 buf
= copystring( tmp
);
1216 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1217 if (buf
) buf
[0] = 0;
1218 return (wxChar
*) NULL
;
1222 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1225 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1234 // Get first file name matching given wild card.
1238 // Get first file name matching given wild card.
1239 // Flags are reserved for future use.
1241 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1242 static DIR *gs_dirStream
= (DIR *) NULL
;
1243 static wxString gs_strFileSpec
;
1244 static int gs_findFlags
= 0;
1247 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1251 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1253 closedir(gs_dirStream
); // edz 941103: better housekeping
1255 gs_findFlags
= flags
;
1257 gs_strFileSpec
= spec
;
1259 // Find path only so we can concatenate
1260 // found file onto path
1261 wxString
path(wxPathOnly(gs_strFileSpec
));
1263 // special case: path is really "/"
1264 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1266 // path is empty => Local directory
1270 gs_dirStream
= opendir(path
.fn_str());
1271 if ( !gs_dirStream
)
1273 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1278 result
= wxFindNextFile();
1280 #endif // !VMS6.x or earlier
1285 wxString
wxFindNextFile()
1289 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1290 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1292 // Find path only so we can concatenate
1293 // found file onto path
1294 wxString
path(wxPathOnly(gs_strFileSpec
));
1295 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1297 /* MATTHEW: special case: path is really "/" */
1298 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1302 struct dirent
*nextDir
;
1303 for ( nextDir
= readdir(gs_dirStream
);
1305 nextDir
= readdir(gs_dirStream
) )
1307 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1308 strcmp(nextDir
->d_name
, ".") &&
1309 strcmp(nextDir
->d_name
, "..") )
1312 if ( !path
.IsEmpty() )
1315 if ( path
!= wxT('/') )
1319 result
+= nextDir
->d_name
;
1321 // Only return "." and ".." when they match
1323 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1324 (strcmp(nextDir
->d_name
, "..") == 0))
1326 if ( (gs_findFlags
& wxDIR
) != 0 )
1332 isdir
= wxDirExists(result
);
1334 // and only return directories when flags & wxDIR
1335 if ( !gs_findFlags
||
1336 ((gs_findFlags
& wxDIR
) && isdir
) ||
1337 ((gs_findFlags
& wxFILE
) && !isdir
) )
1344 result
.Empty(); // not found
1346 closedir(gs_dirStream
);
1347 gs_dirStream
= (DIR *) NULL
;
1348 #endif // !VMS6.2 or earlier
1353 #elif defined(__WXMAC__)
1355 struct MacDirectoryIterator
1363 static int g_iter_flags
;
1365 static MacDirectoryIterator g_iter
;
1367 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1371 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1373 // Find path only so we can concatenate found file onto path
1374 wxString
path(wxPathOnly(spec
));
1375 if ( !path
.IsEmpty() )
1376 result
<< path
<< wxT('\\');
1380 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1381 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1382 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1383 g_iter
.m_index
= 0 ;
1386 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1388 return wxEmptyString
;
1390 return wxFindNextFile( ) ;
1393 wxString
wxFindNextFile()
1399 while ( err
== noErr
)
1402 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1403 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1404 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1408 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1411 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1419 return wxEmptyString
;
1423 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1428 return wxMacFSSpec2UnixFilename( &spec
) ;
1431 #elif defined(__WXMSW__)
1434 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1435 static WIN32_FIND_DATA gs_findDataStruct
;
1438 static struct ffblk gs_findDataStruct
;
1440 static struct _find_t gs_findDataStruct
;
1444 static wxString gs_strFileSpec
;
1445 static int gs_findFlags
= 0;
1447 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1451 gs_strFileSpec
= spec
;
1452 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1454 // Find path only so we can concatenate found file onto path
1455 wxString
path(wxPathOnly(gs_strFileSpec
));
1456 if ( !path
.IsEmpty() )
1457 result
<< path
<< wxT('\\');
1460 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1461 FindClose(gs_hFileStruct
);
1463 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1465 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1472 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1474 if (isdir
&& !(flags
& wxDIR
))
1475 return wxFindNextFile();
1476 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1477 return wxFindNextFile();
1479 result
+= gs_findDataStruct
.cFileName
;
1483 int flag
= _A_NORMAL
;
1484 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1488 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1490 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1493 /* MATTHEW: [5] Check directory flag */
1497 attrib
= gs_findDataStruct
.ff_attrib
;
1499 attrib
= gs_findDataStruct
.attrib
;
1502 if (attrib
& _A_SUBDIR
) {
1503 if (!(gs_findFlags
& wxDIR
))
1504 return wxFindNextFile();
1505 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1506 return wxFindNextFile();
1510 gs_findDataStruct
.ff_name
1512 gs_findDataStruct
.name
1521 wxString
wxFindNextFile()
1525 // Find path only so we can concatenate found file onto path
1526 wxString
path(wxPathOnly(gs_strFileSpec
));
1531 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1534 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1537 FindClose(gs_hFileStruct
);
1538 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1542 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1544 if (isdir
&& !(gs_findFlags
& wxDIR
))
1546 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1549 if ( !path
.IsEmpty() )
1550 result
<< path
<< wxT('\\');
1551 result
<< gs_findDataStruct
.cFileName
;
1558 if (findnext(&gs_findDataStruct
) == 0)
1560 if (_dos_findnext(&gs_findDataStruct
) == 0)
1563 /* MATTHEW: [5] Check directory flag */
1567 attrib
= gs_findDataStruct
.ff_attrib
;
1569 attrib
= gs_findDataStruct
.attrib
;
1572 if (attrib
& _A_SUBDIR
) {
1573 if (!(gs_findFlags
& wxDIR
))
1575 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1581 gs_findDataStruct
.ff_name
1583 gs_findDataStruct
.name
1592 #endif // Unix/Windows
1594 // Get current working directory.
1595 // If buf is NULL, allocates space using new, else
1597 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1600 buf
= new wxChar
[sz
+1];
1602 char *cbuf
= new char[sz
+1];
1604 if (_getcwd(cbuf
, sz
) == NULL
) {
1605 #elif defined( __WXMAC__)
1608 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1612 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1613 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1614 strcpy( buf
, res
) ;
1617 if (getcwd(cbuf
, sz
) == NULL
) {
1622 if (_getcwd(buf
, sz
) == NULL
) {
1623 #elif defined( __WXMAC__)
1626 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1630 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1631 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1632 strcpy( buf
, res
) ;
1635 if (getcwd(buf
, sz
) == NULL
) {
1643 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1652 static const size_t maxPathLen
= 1024;
1655 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1656 str
.UngetWriteBuf();
1661 bool wxSetWorkingDirectory(const wxString
& d
)
1663 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1664 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1665 #elif defined(__WINDOWS__)
1668 return (bool)(SetCurrentDirectory(d
) != 0);
1670 // Must change drive, too.
1671 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1674 wxChar firstChar
= d
[0];
1678 firstChar
= firstChar
- 32;
1680 // To a drive number
1681 unsigned int driveNo
= firstChar
- 64;
1684 unsigned int noDrives
;
1685 _dos_setdrive(driveNo
, &noDrives
);
1688 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1696 // Get the OS directory if appropriate (such as the Windows directory).
1697 // On non-Windows platform, probably just return the empty string.
1698 wxString
wxGetOSDirectory()
1702 GetWindowsDirectory(buf
, 256);
1703 return wxString(buf
);
1705 return wxEmptyString
;
1709 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1711 size_t len
= wxStrlen(pszFileName
);
1715 return wxIsPathSeparator(pszFileName
[len
- 1]);
1718 // find a file in a list of directories, returns false if not found
1719 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1721 // we assume that it's not empty
1722 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1723 _("empty file name in wxFindFileInPath"));
1725 // skip path separator in the beginning of the file name if present
1726 if ( wxIsPathSeparator(*pszFile
) )
1729 // copy the path (strtok will modify it)
1730 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1731 wxStrcpy(szPath
, pszPath
);
1734 wxChar
*pc
, *save_ptr
;
1735 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1737 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1739 // search for the file in this directory
1741 if ( !wxEndsWithPathSeparator(pc
) )
1742 strFile
+= wxFILE_SEP_PATH
;
1745 if ( FileExists(strFile
) ) {
1751 // suppress warning about unused variable save_ptr when wxStrtok() is a
1752 // macro which throws away its third argument
1757 return pc
!= NULL
; // if true => we breaked from the loop
1760 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1765 // it can be empty, but it shouldn't be NULL
1766 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1768 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1771 // under Windows we understand both separators
1772 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1773 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1774 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1775 #else // assume Unix
1776 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1778 if ( pDot
== pszFileName
)
1780 // under Unix files like .profile are treated in a special way
1785 if ( pDot
< pLastSeparator
)
1787 // the dot is part of the path, not the start of the extension
1793 if ( pLastSeparator
)
1794 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1801 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1802 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1804 *pstrName
= wxString(start
, end
- start
);
1810 *pstrExt
= wxString(pDot
+ 1);
1816 //------------------------------------------------------------------------
1817 // wild character routines
1818 //------------------------------------------------------------------------
1820 bool wxIsWild( const wxString
& pattern
)
1822 wxString tmp
= pattern
;
1823 wxChar
*pat
= WXSTRINGCAST(tmp
);
1826 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1836 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1838 #if defined(HAVE_FNMATCH_H)
1840 // this probably won't work well for multibyte chars in Unicode mode?
1842 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1844 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1848 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1851 * WARNING: this code is broken!
1854 wxString tmp1
= pat
;
1855 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1856 wxString tmp2
= text
;
1857 wxChar
*str
= WXSTRINGCAST(tmp2
);
1860 bool done
= FALSE
, ret_code
, ok
;
1861 // Below is for vi fans
1862 const wxChar OB
= wxT('{'), CB
= wxT('}');
1864 // dot_special means '.' only matches '.'
1865 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1868 while ((*pattern
!= wxT('\0')) && (!done
)
1869 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1873 if (*pattern
!= wxT('\0'))
1879 while ((*str
!=wxT('\0'))
1880 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1883 while (*str
!= wxT('\0'))
1885 while (*pattern
!= wxT('\0'))
1892 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1896 if (*pattern
== wxT('\\')) {
1898 if (*pattern
== wxT('\0')) {
1903 if (*(pattern
+ 1) == wxT('-')) {
1906 if (*pattern
== wxT(']')) {
1910 if (*pattern
== wxT('\\')) {
1912 if (*pattern
== wxT('\0')) {
1917 if ((*str
< c
) || (*str
> *pattern
)) {
1921 } else if (*pattern
!= *str
) {
1926 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1927 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1931 if (*pattern
!= wxT('\0')) {
1941 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1944 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1945 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1946 if (*pattern
== wxT('\\'))
1948 ok
= (*pattern
++ == *cp
++);
1950 if (*pattern
== wxT('\0')) {
1956 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1957 if (*++pattern
== wxT('\\')) {
1958 if (*++pattern
== CB
)
1963 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1964 if (*++pattern
== wxT('\\')) {
1965 if (*++pattern
== CB
|| *pattern
== wxT(','))
1970 if (*pattern
!= wxT('\0'))
1975 if (*str
== *pattern
) {
1982 while (*pattern
== wxT('*'))
1984 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1990 #pragma warning(default:4706) // assignment within conditional expression