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>
85 #define stricmp strcasecmp
88 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
89 // this (3.1 I believe) and how to test for it.
90 // If this works for Borland 4.0 as well, then no worries.
102 // No, Cygwin doesn't appear to have fnmatch.h after all.
103 #if defined(HAVE_FNMATCH_H)
111 // ----------------------------------------------------------------------------
113 // ----------------------------------------------------------------------------
115 #define _MAXPATHLEN 500
118 extern wxChar gwxMacFileName
[] ;
119 extern wxChar gwxMacFileName2
[] ;
120 extern wxChar gwxMacFileName3
[] ;
123 #if !USE_SHARED_LIBRARIES
124 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
127 // ----------------------------------------------------------------------------
129 // ----------------------------------------------------------------------------
131 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
133 // ============================================================================
135 // ============================================================================
137 void wxPathList::Add (const wxString
& path
)
139 wxStringList::Add (WXSTRINGCAST path
);
142 // Add paths e.g. from the PATH environment variable
143 void wxPathList::AddEnvList (const wxString
& envVariable
)
145 static const wxChar PATH_TOKS
[] =
147 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
152 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
155 wxChar
*s
= copystring (val
);
156 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
160 Add (copystring (token
));
163 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
164 Add (wxString(token
));
171 // Given a full filename (with path), ensure that that file can
172 // be accessed again USING FILENAME ONLY by adding the path
173 // to the list if not already there.
174 void wxPathList::EnsureFileAccessible (const wxString
& path
)
176 wxString
path_only(wxPathOnly(path
));
177 if ( !path_only
.IsEmpty() )
179 if ( !Member(path_only
) )
184 bool wxPathList::Member (const wxString
& path
)
186 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
188 wxString
path2((wxChar
*) node
->Data ());
190 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
192 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
194 // Case sensitive File System
195 path
.CompareTo (path2
) == 0
203 wxString
wxPathList::FindValidPath (const wxString
& file
)
205 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
206 return wxString(wxFileFunctionsBuffer
);
208 wxChar buf
[_MAXPATHLEN
];
209 wxStrcpy(buf
, wxFileFunctionsBuffer
);
211 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
212 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
214 for (wxNode
* node
= First (); node
; node
= node
->Next ())
216 wxChar
*path
= (wxChar
*) node
->Data ();
217 wxStrcpy (wxFileFunctionsBuffer
, path
);
218 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
219 if (ch
!= wxT('\\') && ch
!= wxT('/'))
220 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
221 wxStrcat (wxFileFunctionsBuffer
, filename
);
223 Unix2DosFilename (wxFileFunctionsBuffer
);
225 if (wxFileExists (wxFileFunctionsBuffer
))
227 return wxString(wxFileFunctionsBuffer
); // Found!
231 return wxString(wxT("")); // Not found
234 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
236 wxString f
= FindValidPath(file
);
237 if ( wxIsAbsolutePath(f
) )
241 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
243 if ( !wxEndsWithPathSeparator(buf
) )
245 buf
+= wxFILE_SEP_PATH
;
253 wxFileExists (const wxString
& filename
)
255 #ifdef __GNUWIN32__ // (fix a B20 bug)
256 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
260 #elif defined(__WXMAC__)
262 wxStrcpy( gwxMacFileName
, filename
) ;
263 wxUnix2MacFilename( gwxMacFileName
) ;
264 if (gwxMacFileName
&& stat (WXSTRINGCAST gwxMacFileName
, &stbuf
) == 0)
275 if ((filename
!= wxT("")) && stat (wxFNSTRINGCAST filename
.fn_str(), &stbuf
) == 0)
281 /* Vadim's alternative implementation
283 // does the file exist?
284 bool wxFileExists(const char *pszFileName)
287 return !access(pszFileName, 0) &&
288 !stat(pszFileName, &st) &&
289 (st.st_mode & S_IFREG);
294 wxIsAbsolutePath (const wxString
& filename
)
296 if (filename
!= wxT(""))
298 if (filename
[0] == wxT('/')
300 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
304 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
313 * Strip off any extension (dot something) from end of file,
314 * IF one exists. Inserts zero into buffer.
318 void wxStripExtension(wxChar
*buffer
)
320 int len
= wxStrlen(buffer
);
324 if (buffer
[i
] == wxT('.'))
333 void wxStripExtension(wxString
& buffer
)
335 size_t len
= buffer
.Length();
339 if (buffer
.GetChar(i
) == wxT('.'))
341 buffer
= buffer
.Left(i
);
348 // Destructive removal of /./ and /../ stuff
349 wxChar
*wxRealPath (wxChar
*path
)
352 static const wxChar SEP
= wxT('\\');
353 Unix2DosFilename(path
);
355 static const wxChar SEP
= wxT('/');
357 if (path
[0] && path
[1]) {
358 /* MATTHEW: special case "/./x" */
360 if (path
[2] == SEP
&& path
[1] == wxT('.'))
368 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
371 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
372 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
373 && (q
- 1 <= path
|| q
[-1] != SEP
))
376 if (path
[0] == wxT('\0'))
382 /* Check that path[2] is NULL! */
383 else if (path
[1] == wxT(':') && !path
[2])
392 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
401 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
403 if (filename
== wxT(""))
404 return (wxChar
*) NULL
;
406 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
407 wxChar buf
[_MAXPATHLEN
];
409 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
410 wxChar ch
= buf
[wxStrlen(buf
) - 1];
412 if (ch
!= wxT('\\') && ch
!= wxT('/'))
413 wxStrcat(buf
, wxT("\\"));
416 wxStrcat(buf
, wxT("/"));
418 wxStrcat(buf
, wxFileFunctionsBuffer
);
419 return copystring( wxRealPath(buf
) );
421 return copystring( wxFileFunctionsBuffer
);
427 ~user/ => user's home dir
428 If the environment variable a = "foo" and b = "bar" then:
445 /* input name in name, pathname output to buf. */
447 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
449 register wxChar
*d
, *s
, *nm
;
450 wxChar lnm
[_MAXPATHLEN
];
453 // Some compilers don't like this line.
454 // const wxChar trimchars[] = wxT("\n \t");
457 trimchars
[0] = wxT('\n');
458 trimchars
[1] = wxT(' ');
459 trimchars
[2] = wxT('\t');
463 const wxChar SEP
= wxT('\\');
465 const wxChar SEP
= wxT('/');
468 if (name
== NULL
|| *name
== wxT('\0'))
470 nm
= copystring(name
); // Make a scratch copy
473 /* Skip leading whitespace and cr */
474 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
476 /* And strip off trailing whitespace and cr */
477 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
478 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
486 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
489 /* Expand inline environment variables */
507 while ((*d
++ = *s
)) {
509 if (*s
== wxT('\\')) {
510 if ((*(d
- 1) = *++s
)) {
519 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
521 if (*s
++ == wxT('$'))
524 register wxChar
*start
= d
;
525 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
526 register wxChar
*value
;
528 // VA gives assignment in logical expr warning
534 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
539 value
= wxGetenv(braces
? start
+ 1 : start
);
542 // VA gives assignment in logical expr warning
543 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
545 for ((d
= start
- 1); (*d
++ = *value
++););
554 /* Expand ~ and ~user */
557 if (nm
[0] == wxT('~') && !q
)
560 if (nm
[1] == SEP
|| nm
[1] == 0)
562 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
563 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
568 { /* ~user/filename */
569 register wxChar
*nnm
;
570 register wxChar
*home
;
571 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
572 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
573 was_sep
= (*s
== SEP
);
574 nnm
= *s
? s
+ 1 : s
;
576 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
577 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
578 if (was_sep
) /* replace only if it was there: */
589 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
591 while (wxT('\0') != (*d
++ = *s
++))
594 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
599 // VA gives assignment in logical expr warning
603 while ((*d
++ = *s
++));
605 delete[] nm_tmp
; // clean up alloc
606 /* Now clean up the buffer */
607 return wxRealPath(buf
);
611 /* Contract Paths to be build upon an environment variable
614 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
616 The call wxExpandPath can convert these back!
619 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
621 static wxChar dest
[_MAXPATHLEN
];
623 if (filename
== wxT(""))
624 return (wxChar
*) NULL
;
626 wxStrcpy (dest
, WXSTRINGCAST filename
);
628 Unix2DosFilename(dest
);
631 // Handle environment
632 const wxChar
*val
= (const wxChar
*) NULL
;
633 wxChar
*tcp
= (wxChar
*) NULL
;
634 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
635 (tcp
= wxStrstr (dest
, val
)) != NULL
)
637 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
640 wxStrcpy (tcp
, WXSTRINGCAST envname
);
641 wxStrcat (tcp
, wxT("}"));
642 wxStrcat (tcp
, wxFileFunctionsBuffer
);
645 // Handle User's home (ignore root homes!)
647 if ((val
= wxGetUserHome (user
)) != NULL
&&
648 (len
= wxStrlen(val
)) > 2 &&
649 wxStrncmp(dest
, val
, len
) == 0)
651 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
653 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
655 // strcat(wxFileFunctionsBuffer, "\\");
657 // strcat(wxFileFunctionsBuffer, "/");
659 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
660 wxStrcpy (dest
, wxFileFunctionsBuffer
);
666 // Return just the filename, not the path
668 wxChar
*wxFileNameFromPath (wxChar
*path
)
672 register wxChar
*tcp
;
674 tcp
= path
+ wxStrlen (path
);
675 while (--tcp
>= path
)
677 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
679 || *tcp
== wxT(':') || *tcp
== wxT(']'))
685 #if defined(__WXMSW__) || defined(__WXPM__)
686 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
693 wxString
wxFileNameFromPath (const wxString
& path1
)
695 if (path1
!= wxT(""))
698 wxChar
*path
= WXSTRINGCAST path1
;
699 register wxChar
*tcp
;
701 tcp
= path
+ wxStrlen (path
);
702 while (--tcp
>= path
)
704 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
706 || *tcp
== wxT(':') || *tcp
== wxT(']'))
710 return wxString(tcp
+ 1);
712 #if defined(__WXMSW__) || defined(__WXPM__)
713 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
714 return wxString(path
+ 2);
717 // Yes, this should return the path, not an empty string, otherwise
718 // we get "thing.txt" -> "".
722 // Return just the directory, or NULL if no directory
724 wxPathOnly (wxChar
*path
)
728 static wxChar buf
[_MAXPATHLEN
];
731 wxStrcpy (buf
, path
);
733 int l
= wxStrlen(path
);
738 // Search backward for a backward or forward slash
739 while (!done
&& i
> -1)
742 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
756 #if defined(__WXMSW__) || defined(__WXPM__)
757 // Try Drive specifier
758 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
760 // A:junk --> A:. (since A:.\junk Not A:\junk)
768 return (wxChar
*) NULL
;
771 // Return just the directory, or NULL if no directory
772 wxString
wxPathOnly (const wxString
& path
)
776 wxChar buf
[_MAXPATHLEN
];
779 wxStrcpy (buf
, WXSTRINGCAST path
);
781 int l
= path
.Length();
786 // Search backward for a backward or forward slash
787 while (!done
&& i
> -1)
790 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
799 return wxString(buf
);
804 #if defined(__WXMSW__) || defined(__WXPM__)
805 // Try Drive specifier
806 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
808 // A:junk --> A:. (since A:.\junk Not A:\junk)
811 return wxString(buf
);
816 return wxString(wxT(""));
819 // Utility for converting delimiters in DOS filenames to UNIX style
820 // and back again - or we get nasty problems with delimiters.
821 // Also, convert to lower case, since case is significant in UNIX.
825 wxMac2UnixFilename (wxChar
*s
)
829 memmove( s
+1 , s
,(strlen( s
) + 1)*sizeof(wxChar
)) ;
830 if ( *s
== wxT(':') )
840 *s
= wxTolower(*s
); // Case INDEPENDENT
847 wxUnix2MacFilename (wxChar
*s
)
851 if ( *s
== wxT('.') )
853 // relative path , since it goes on with slash which is translated to a :
854 memmove( s
, s
+1 ,strlen( s
)*sizeof(wxChar
) ) ;
856 else if ( *s
== wxT('/') )
858 // absolute path -> on mac just start with the drive name
859 memmove( s
, s
+1 ,strlen( s
)*sizeof(wxChar
) ) ;
863 wxASSERT_MSG( 1 , wxT("unknown path beginning") ) ;
867 if (*s
== wxT('/') || *s
== wxT('\\'))
876 wxDos2UnixFilename (wxChar
*s
)
883 #if defined(__WXMSW__) || defined(__WXPM__)
885 *s
= wxTolower(*s
); // Case INDEPENDENT
892 #if defined(__WXMSW__) || defined(__WXPM__)
893 wxUnix2DosFilename (wxChar
*s
)
895 wxUnix2DosFilename (wxChar
*WXUNUSED(s
))
898 // Yes, I really mean this to happen under DOS only! JACS
899 #if defined(__WXMSW__) || defined(__WXPM__)
910 // Concatenate two files to form third
912 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
914 wxChar
*outfile
= wxGetTempFileName("cat");
916 FILE *fp1
= (FILE *) NULL
;
917 FILE *fp2
= (FILE *) NULL
;
918 FILE *fp3
= (FILE *) NULL
;
919 // Open the inputs and outputs
921 wxStrcpy( gwxMacFileName
, file1
) ;
922 wxUnix2MacFilename( gwxMacFileName
) ;
923 wxStrcpy( gwxMacFileName2
, file2
) ;
924 wxUnix2MacFilename( gwxMacFileName2
) ;
925 wxStrcpy( gwxMacFileName3
, outfile
) ;
926 wxUnix2MacFilename( gwxMacFileName3
) ;
928 if ((fp1
= fopen (gwxMacFileName
, "rb")) == NULL
||
929 (fp2
= fopen (gwxMacFileName2
, "rb")) == NULL
||
930 (fp3
= fopen (gwxMacFileName3
, "wb")) == NULL
)
932 if ((fp1
= fopen (wxFNSTRINGCAST file1
.fn_str(), "rb")) == NULL
||
933 (fp2
= fopen (wxFNSTRINGCAST file2
.fn_str(), "rb")) == NULL
||
934 (fp3
= fopen (wxFNCONV(outfile
), "wb")) == NULL
)
947 while ((ch
= getc (fp1
)) != EOF
)
948 (void) putc (ch
, fp3
);
951 while ((ch
= getc (fp2
)) != EOF
)
952 (void) putc (ch
, fp3
);
956 bool result
= wxRenameFile(outfile
, file3
);
963 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
970 wxStrcpy( gwxMacFileName
, file1
) ;
971 wxUnix2MacFilename( gwxMacFileName
) ;
972 wxStrcpy( gwxMacFileName2
, file2
) ;
973 wxUnix2MacFilename( gwxMacFileName2
) ;
975 if ((fd1
= fopen (gwxMacFileName
, "rb")) == NULL
)
977 if ((fd2
= fopen (gwxMacFileName2
, "wb")) == NULL
)
979 if ((fd1
= fopen (wxFNSTRINGCAST file1
.fn_str(), "rb")) == NULL
)
981 if ((fd2
= fopen (wxFNSTRINGCAST file2
.fn_str(), "wb")) == NULL
)
988 while ((ch
= getc (fd1
)) != EOF
)
989 (void) putc (ch
, fd2
);
997 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1000 wxStrcpy( gwxMacFileName
, file1
) ;
1001 wxUnix2MacFilename( gwxMacFileName
) ;
1002 wxStrcpy( gwxMacFileName2
, file2
) ;
1003 wxUnix2MacFilename( gwxMacFileName2
) ;
1005 if (0 == rename (gwxMacFileName
, gwxMacFileName2
))
1008 // Normal system call
1009 if (0 == rename (wxFNSTRINGCAST file1
.fn_str(), wxFNSTRINGCAST file2
.fn_str()))
1013 if (wxCopyFile(file1
, file2
)) {
1014 wxRemoveFile(file1
);
1021 bool wxRemoveFile(const wxString
& file
)
1023 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1024 int flag
= remove(wxFNSTRINGCAST file
.fn_str());
1025 #elif defined( __WXMAC__ )
1026 wxStrcpy( gwxMacFileName
, file
) ;
1027 wxUnix2MacFilename( gwxMacFileName
) ;
1028 int flag
= unlink(gwxMacFileName
);
1030 int flag
= unlink(wxFNSTRINGCAST file
.fn_str());
1032 return (flag
== 0) ;
1035 bool wxMkdir(const wxString
& dir
, int perm
)
1037 #if defined( __WXMAC__ )
1038 wxStrcpy( gwxMacFileName
, dir
) ;
1039 wxUnix2MacFilename( gwxMacFileName
) ;
1040 const wxChar
*dirname
= gwxMacFileName
;
1042 const wxChar
*dirname
= dir
.c_str();
1045 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1046 // for the GNU compiler
1047 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1048 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1049 #else // MSW and OS/2
1050 if ( mkdir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1053 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1061 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1065 #elif defined( __WXMAC__ )
1066 wxStrcpy( gwxMacFileName
, dir
) ;
1067 wxUnix2MacFilename( gwxMacFileName
) ;
1068 return (rmdir(WXSTRINGCAST gwxMacFileName
) == 0);
1072 return FALSE
; // What to do?
1074 return (rmdir(wxFNSTRINGCAST dir
.fn_str()) == 0);
1081 bool wxDirExists(const wxString
& dir
)
1085 #elif !defined(__WXMSW__)
1087 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1090 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1091 #if defined(__WIN32__)
1092 WIN32_FIND_DATA fileInfo
;
1095 struct ffblk fileInfo
;
1097 struct find_t fileInfo
;
1101 #if defined(__WIN32__)
1102 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1104 if (h
==INVALID_HANDLE_VALUE
)
1108 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1111 // In Borland findfirst has a different argument
1112 // ordering from _dos_findfirst. But _dos_findfirst
1113 // _should_ be ok in both MS and Borland... why not?
1115 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1117 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1126 // does the path exists? (may have or not '/' or '\\' at the end)
1127 bool wxPathExists(const wxChar
*pszPathName
)
1129 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1130 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1131 wxString
strPath(pszPathName
);
1132 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != wxT('\0') )
1133 strPath
.Last() = wxT('\0');
1141 return stat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1144 // Get a temporary filename, opening and closing the file.
1145 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1151 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1153 wxChar tmp
[MAX_PATH
];
1154 wxChar tmpPath
[MAX_PATH
];
1155 ::GetTempPath(MAX_PATH
, tmpPath
);
1156 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1158 if (buf
) wxStrcpy(buf
, tmp
);
1159 else buf
= copystring(tmp
);
1163 static short last_temp
= 0; // cache last to speed things a bit
1164 // At most 1000 temp files to a process! We use a ring count.
1165 wxChar tmp
[100]; // FIXME static buffer
1167 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1169 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1170 if (!wxFileExists( tmp
))
1172 // Touch the file to create it (reserve name)
1173 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1178 wxStrcpy( buf
, tmp
);
1180 buf
= copystring( tmp
);
1184 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1185 if (buf
) buf
[0] = 0;
1186 return (wxChar
*) NULL
;
1190 // Get first file name matching given wild card.
1194 // Get first file name matching given wild card.
1195 // Flags are reserved for future use.
1198 static DIR *gs_dirStream
= (DIR *) NULL
;
1199 static wxString gs_strFileSpec
;
1200 static int gs_findFlags
= 0;
1203 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1209 closedir(gs_dirStream
); // edz 941103: better housekeping
1211 gs_findFlags
= flags
;
1213 gs_strFileSpec
= spec
;
1215 // Find path only so we can concatenate
1216 // found file onto path
1217 wxString
path(wxPathOnly(gs_strFileSpec
));
1219 // special case: path is really "/"
1220 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1222 // path is empty => Local directory
1226 gs_dirStream
= opendir(path
.fn_str());
1227 if ( !gs_dirStream
)
1229 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1234 result
= wxFindNextFile();
1241 wxString
wxFindNextFile()
1246 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1248 // Find path only so we can concatenate
1249 // found file onto path
1250 wxString
path(wxPathOnly(gs_strFileSpec
));
1251 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1253 /* MATTHEW: special case: path is really "/" */
1254 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1258 struct dirent
*nextDir
;
1259 for ( nextDir
= readdir(gs_dirStream
);
1261 nextDir
= readdir(gs_dirStream
) )
1263 if (wxMatchWild(name
, nextDir
->d_name
))
1266 if ( !path
.IsEmpty() )
1269 if ( path
!= wxT('/') )
1273 result
+= nextDir
->d_name
;
1275 // Only return "." and ".." when they match
1277 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1278 (strcmp(nextDir
->d_name
, "..") == 0))
1280 if ( (gs_findFlags
& wxDIR
) != 0 )
1286 isdir
= wxDirExists(result
);
1288 // and only return directories when flags & wxDIR
1289 if ( !gs_findFlags
||
1290 ((gs_findFlags
& wxDIR
) && isdir
) ||
1291 ((gs_findFlags
& wxFILE
) && !isdir
) )
1298 result
.Empty(); // not found
1300 closedir(gs_dirStream
);
1301 gs_dirStream
= (DIR *) NULL
;
1307 #elif defined(__WXMSW__)
1310 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1311 static WIN32_FIND_DATA gs_findDataStruct
;
1314 static struct ffblk gs_findDataStruct
;
1316 static struct _find_t gs_findDataStruct
;
1320 static wxString gs_strFileSpec
;
1321 static int gs_findFlags
= 0;
1323 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1327 gs_strFileSpec
= spec
;
1328 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1330 // Find path only so we can concatenate found file onto path
1331 wxString
path(wxPathOnly(gs_strFileSpec
));
1332 if ( !path
.IsEmpty() )
1333 result
<< path
<< wxT('\\');
1336 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1337 FindClose(gs_hFileStruct
);
1339 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1341 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1348 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1350 if (isdir
&& !(flags
& wxDIR
))
1351 return wxFindNextFile();
1352 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1353 return wxFindNextFile();
1355 result
+= gs_findDataStruct
.cFileName
;
1359 int flag
= _A_NORMAL
;
1360 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1364 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1366 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1369 /* MATTHEW: [5] Check directory flag */
1373 attrib
= gs_findDataStruct
.ff_attrib
;
1375 attrib
= gs_findDataStruct
.attrib
;
1378 if (attrib
& _A_SUBDIR
) {
1379 if (!(gs_findFlags
& wxDIR
))
1380 return wxFindNextFile();
1381 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1382 return wxFindNextFile();
1386 gs_findDataStruct
.ff_name
1388 gs_findDataStruct
.name
1397 wxString
wxFindNextFile()
1401 // Find path only so we can concatenate found file onto path
1402 wxString
path(wxPathOnly(gs_strFileSpec
));
1407 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1410 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1413 FindClose(gs_hFileStruct
);
1414 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1418 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1420 if (isdir
&& !(gs_findFlags
& wxDIR
))
1422 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1425 if ( !path
.IsEmpty() )
1426 result
<< path
<< wxT('\\');
1427 result
<< gs_findDataStruct
.cFileName
;
1434 if (findnext(&gs_findDataStruct
) == 0)
1436 if (_dos_findnext(&gs_findDataStruct
) == 0)
1439 /* MATTHEW: [5] Check directory flag */
1443 attrib
= gs_findDataStruct
.ff_attrib
;
1445 attrib
= gs_findDataStruct
.attrib
;
1448 if (attrib
& _A_SUBDIR
) {
1449 if (!(gs_findFlags
& wxDIR
))
1451 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1457 gs_findDataStruct
.ff_name
1459 gs_findDataStruct
.name
1468 #endif // Unix/Windows
1470 // Get current working directory.
1471 // If buf is NULL, allocates space using new, else
1473 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1476 buf
= new wxChar
[sz
+1];
1478 char *cbuf
= new char[sz
+1];
1480 if (_getcwd(cbuf
, sz
) == NULL
) {
1482 if (getcwd(cbuf
, sz
) == NULL
) {
1487 if (_getcwd(buf
, sz
) == NULL
) {
1489 if (getcwd(buf
, sz
) == NULL
) {
1497 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1506 static const size_t maxPathLen
= 1024;
1509 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1510 str
.UngetWriteBuf();
1515 bool wxSetWorkingDirectory(const wxString
& d
)
1517 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1518 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1519 #elif defined(__WINDOWS__)
1522 return (bool)(SetCurrentDirectory(d
) != 0);
1524 // Must change drive, too.
1525 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1528 wxChar firstChar
= d
[0];
1532 firstChar
= firstChar
- 32;
1534 // To a drive number
1535 unsigned int driveNo
= firstChar
- 64;
1538 unsigned int noDrives
;
1539 _dos_setdrive(driveNo
, &noDrives
);
1542 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1550 // Get the OS directory if appropriate (such as the Windows directory).
1551 // On non-Windows platform, probably just return the empty string.
1552 wxString
wxGetOSDirectory()
1556 GetWindowsDirectory(buf
, 256);
1557 return wxString(buf
);
1559 return wxEmptyString
;
1563 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1565 size_t len
= wxStrlen(pszFileName
);
1569 return wxIsPathSeparator(pszFileName
[len
- 1]);
1572 // find a file in a list of directories, returns false if not found
1573 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1575 // we assume that it's not empty
1576 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1577 _("empty file name in wxFindFileInPath"));
1579 // skip path separator in the beginning of the file name if present
1580 if ( wxIsPathSeparator(*pszFile
) )
1583 // copy the path (strtok will modify it)
1584 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1585 wxStrcpy(szPath
, pszPath
);
1588 wxChar
*pc
, *save_ptr
;
1589 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1591 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1593 // search for the file in this directory
1595 if ( !wxEndsWithPathSeparator(pc
) )
1596 strFile
+= wxFILE_SEP_PATH
;
1599 if ( FileExists(strFile
) ) {
1607 return pc
!= NULL
; // if true => we breaked from the loop
1610 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1615 // it can be empty, but it shouldn't be NULL
1616 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1618 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1621 // under Windows we understand both separators
1622 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1623 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1624 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1625 #else // assume Unix
1626 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1628 if ( pDot
== pszFileName
)
1630 // under Unix files like .profile are treated in a special way
1635 if ( pDot
< pLastSeparator
)
1637 // the dot is part of the path, not the start of the extension
1643 if ( pLastSeparator
)
1644 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1651 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1652 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1654 *pstrName
= wxString(start
, end
- start
);
1660 *pstrExt
= wxString(pDot
+ 1);
1666 //------------------------------------------------------------------------
1667 // wild character routines
1668 //------------------------------------------------------------------------
1670 bool wxIsWild( const wxString
& pattern
)
1672 wxString tmp
= pattern
;
1673 wxChar
*pat
= WXSTRINGCAST(tmp
);
1676 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1686 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1688 #if defined(HAVE_FNMATCH_H)
1690 // this probably won't work well for multibyte chars in Unicode mode?
1692 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1694 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1698 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1701 * WARNING: this code is broken!
1704 wxString tmp1
= pat
;
1705 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1706 wxString tmp2
= text
;
1707 wxChar
*str
= WXSTRINGCAST(tmp2
);
1710 bool done
= FALSE
, ret_code
, ok
;
1711 // Below is for vi fans
1712 const wxChar OB
= wxT('{'), CB
= wxT('}');
1714 // dot_special means '.' only matches '.'
1715 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1718 while ((*pattern
!= wxT('\0')) && (!done
)
1719 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1723 if (*pattern
!= wxT('\0'))
1729 while ((*str
!=wxT('\0'))
1730 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1733 while (*str
!= wxT('\0'))
1735 while (*pattern
!= wxT('\0'))
1742 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1746 if (*pattern
== wxT('\\')) {
1748 if (*pattern
== wxT('\0')) {
1753 if (*(pattern
+ 1) == wxT('-')) {
1756 if (*pattern
== wxT(']')) {
1760 if (*pattern
== wxT('\\')) {
1762 if (*pattern
== wxT('\0')) {
1767 if ((*str
< c
) || (*str
> *pattern
)) {
1771 } else if (*pattern
!= *str
) {
1776 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1777 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1781 if (*pattern
!= wxT('\0')) {
1791 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1794 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1795 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1796 if (*pattern
== wxT('\\'))
1798 ok
= (*pattern
++ == *cp
++);
1800 if (*pattern
== wxT('\0')) {
1806 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1807 if (*++pattern
== wxT('\\')) {
1808 if (*++pattern
== CB
)
1813 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1814 if (*++pattern
== wxT('\\')) {
1815 if (*++pattern
== CB
|| *pattern
== wxT(','))
1820 if (*pattern
!= wxT('\0'))
1825 if (*str
== *pattern
) {
1832 while (*pattern
== wxT('*'))
1834 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1840 #pragma warning(default:4706) // assignment within conditional expression