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
));
168 // suppress warning about unused variable save_ptr when wxStrtok() is a
169 // macro which throws away its third argument
176 // Given a full filename (with path), ensure that that file can
177 // be accessed again USING FILENAME ONLY by adding the path
178 // to the list if not already there.
179 void wxPathList::EnsureFileAccessible (const wxString
& path
)
181 wxString
path_only(wxPathOnly(path
));
182 if ( !path_only
.IsEmpty() )
184 if ( !Member(path_only
) )
189 bool wxPathList::Member (const wxString
& path
)
191 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
193 wxString
path2((wxChar
*) node
->Data ());
195 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
197 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
199 // Case sensitive File System
200 path
.CompareTo (path2
) == 0
208 wxString
wxPathList::FindValidPath (const wxString
& file
)
210 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
211 return wxString(wxFileFunctionsBuffer
);
213 wxChar buf
[_MAXPATHLEN
];
214 wxStrcpy(buf
, wxFileFunctionsBuffer
);
216 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
217 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
219 for (wxNode
* node
= First (); node
; node
= node
->Next ())
221 wxChar
*path
= (wxChar
*) node
->Data ();
222 wxStrcpy (wxFileFunctionsBuffer
, path
);
223 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
224 if (ch
!= wxT('\\') && ch
!= wxT('/'))
225 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
226 wxStrcat (wxFileFunctionsBuffer
, filename
);
228 Unix2DosFilename (wxFileFunctionsBuffer
);
230 if (wxFileExists (wxFileFunctionsBuffer
))
232 return wxString(wxFileFunctionsBuffer
); // Found!
236 return wxString(wxT("")); // Not found
239 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
241 wxString f
= FindValidPath(file
);
242 if ( wxIsAbsolutePath(f
) )
246 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
248 if ( !wxEndsWithPathSeparator(buf
) )
250 buf
+= wxFILE_SEP_PATH
;
258 wxFileExists (const wxString
& filename
)
260 #ifdef __GNUWIN32__ // (fix a B20 bug)
261 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
265 #elif defined(__WXMAC__)
267 wxStrcpy( gwxMacFileName
, filename
) ;
268 wxUnix2MacFilename( gwxMacFileName
) ;
269 if (gwxMacFileName
&& stat (WXSTRINGCAST gwxMacFileName
, &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
);
616 /* Contract Paths to be build upon an environment variable
619 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
621 The call wxExpandPath can convert these back!
624 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
626 static wxChar dest
[_MAXPATHLEN
];
628 if (filename
== wxT(""))
629 return (wxChar
*) NULL
;
631 wxStrcpy (dest
, WXSTRINGCAST filename
);
633 Unix2DosFilename(dest
);
636 // Handle environment
637 const wxChar
*val
= (const wxChar
*) NULL
;
638 wxChar
*tcp
= (wxChar
*) NULL
;
639 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
640 (tcp
= wxStrstr (dest
, val
)) != NULL
)
642 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
645 wxStrcpy (tcp
, WXSTRINGCAST envname
);
646 wxStrcat (tcp
, wxT("}"));
647 wxStrcat (tcp
, wxFileFunctionsBuffer
);
650 // Handle User's home (ignore root homes!)
652 if ((val
= wxGetUserHome (user
)) != NULL
&&
653 (len
= wxStrlen(val
)) > 2 &&
654 wxStrncmp(dest
, val
, len
) == 0)
656 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
658 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
660 // strcat(wxFileFunctionsBuffer, "\\");
662 // strcat(wxFileFunctionsBuffer, "/");
664 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
665 wxStrcpy (dest
, wxFileFunctionsBuffer
);
671 // Return just the filename, not the path
673 wxChar
*wxFileNameFromPath (wxChar
*path
)
677 register wxChar
*tcp
;
679 tcp
= path
+ wxStrlen (path
);
680 while (--tcp
>= path
)
682 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
684 || *tcp
== wxT(':') || *tcp
== wxT(']'))
690 #if defined(__WXMSW__) || defined(__WXPM__)
691 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
698 wxString
wxFileNameFromPath (const wxString
& path1
)
700 if (path1
!= wxT(""))
703 wxChar
*path
= WXSTRINGCAST path1
;
704 register wxChar
*tcp
;
706 tcp
= path
+ wxStrlen (path
);
707 while (--tcp
>= path
)
709 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
711 || *tcp
== wxT(':') || *tcp
== wxT(']'))
715 return wxString(tcp
+ 1);
717 #if defined(__WXMSW__) || defined(__WXPM__)
718 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
719 return wxString(path
+ 2);
722 // Yes, this should return the path, not an empty string, otherwise
723 // we get "thing.txt" -> "".
727 // Return just the directory, or NULL if no directory
729 wxPathOnly (wxChar
*path
)
733 static wxChar buf
[_MAXPATHLEN
];
736 wxStrcpy (buf
, path
);
738 int l
= wxStrlen(path
);
743 // Search backward for a backward or forward slash
744 while (!done
&& i
> -1)
747 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
761 #if defined(__WXMSW__) || defined(__WXPM__)
762 // Try Drive specifier
763 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
765 // A:junk --> A:. (since A:.\junk Not A:\junk)
773 return (wxChar
*) NULL
;
776 // Return just the directory, or NULL if no directory
777 wxString
wxPathOnly (const wxString
& path
)
781 wxChar buf
[_MAXPATHLEN
];
784 wxStrcpy (buf
, WXSTRINGCAST path
);
786 int l
= path
.Length();
791 // Search backward for a backward or forward slash
792 while (!done
&& i
> -1)
795 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
804 return wxString(buf
);
809 #if defined(__WXMSW__) || defined(__WXPM__)
810 // Try Drive specifier
811 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
813 // A:junk --> A:. (since A:.\junk Not A:\junk)
816 return wxString(buf
);
821 return wxString(wxT(""));
824 // Utility for converting delimiters in DOS filenames to UNIX style
825 // and back again - or we get nasty problems with delimiters.
826 // Also, convert to lower case, since case is significant in UNIX.
830 wxMac2UnixFilename (wxChar
*s
)
834 memmove( s
+1 , s
,(strlen( s
) + 1)*sizeof(wxChar
)) ;
835 if ( *s
== wxT(':') )
845 *s
= wxTolower(*s
); // Case INDEPENDENT
852 wxUnix2MacFilename (wxChar
*s
)
856 if ( *s
== wxT('.') )
858 // relative path , since it goes on with slash which is translated to a :
859 memmove( s
, s
+1 ,strlen( s
)*sizeof(wxChar
) ) ;
861 else if ( *s
== wxT('/') )
863 // absolute path -> on mac just start with the drive name
864 memmove( s
, s
+1 ,strlen( s
)*sizeof(wxChar
) ) ;
868 wxASSERT_MSG( 1 , wxT("unknown path beginning") ) ;
872 if (*s
== wxT('/') || *s
== wxT('\\'))
881 wxDos2UnixFilename (wxChar
*s
)
888 #if defined(__WXMSW__) || defined(__WXPM__)
890 *s
= wxTolower(*s
); // Case INDEPENDENT
897 #if defined(__WXMSW__) || defined(__WXPM__)
898 wxUnix2DosFilename (wxChar
*s
)
900 wxUnix2DosFilename (wxChar
*WXUNUSED(s
))
903 // Yes, I really mean this to happen under DOS only! JACS
904 #if defined(__WXMSW__) || defined(__WXPM__)
915 // Concatenate two files to form third
917 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
919 wxChar
*outfile
= wxGetTempFileName("cat");
921 FILE *fp1
= (FILE *) NULL
;
922 FILE *fp2
= (FILE *) NULL
;
923 FILE *fp3
= (FILE *) NULL
;
924 // Open the inputs and outputs
926 wxStrcpy( gwxMacFileName
, file1
) ;
927 wxUnix2MacFilename( gwxMacFileName
) ;
928 wxStrcpy( gwxMacFileName2
, file2
) ;
929 wxUnix2MacFilename( gwxMacFileName2
) ;
930 wxStrcpy( gwxMacFileName3
, outfile
) ;
931 wxUnix2MacFilename( gwxMacFileName3
) ;
933 if ((fp1
= fopen (gwxMacFileName
, "rb")) == NULL
||
934 (fp2
= fopen (gwxMacFileName2
, "rb")) == NULL
||
935 (fp3
= fopen (gwxMacFileName3
, "wb")) == NULL
)
937 if ((fp1
= fopen (wxFNSTRINGCAST file1
.fn_str(), "rb")) == NULL
||
938 (fp2
= fopen (wxFNSTRINGCAST file2
.fn_str(), "rb")) == NULL
||
939 (fp3
= fopen (wxFNCONV(outfile
), "wb")) == NULL
)
952 while ((ch
= getc (fp1
)) != EOF
)
953 (void) putc (ch
, fp3
);
956 while ((ch
= getc (fp2
)) != EOF
)
957 (void) putc (ch
, fp3
);
961 bool result
= wxRenameFile(outfile
, file3
);
968 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
975 wxStrcpy( gwxMacFileName
, file1
) ;
976 wxUnix2MacFilename( gwxMacFileName
) ;
977 wxStrcpy( gwxMacFileName2
, file2
) ;
978 wxUnix2MacFilename( gwxMacFileName2
) ;
980 if ((fd1
= fopen (gwxMacFileName
, "rb")) == NULL
)
982 if ((fd2
= fopen (gwxMacFileName2
, "wb")) == NULL
)
984 if ((fd1
= fopen (wxFNSTRINGCAST file1
.fn_str(), "rb")) == NULL
)
986 if ((fd2
= fopen (wxFNSTRINGCAST file2
.fn_str(), "wb")) == NULL
)
993 while ((ch
= getc (fd1
)) != EOF
)
994 (void) putc (ch
, fd2
);
1002 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1005 wxStrcpy( gwxMacFileName
, file1
) ;
1006 wxUnix2MacFilename( gwxMacFileName
) ;
1007 wxStrcpy( gwxMacFileName2
, file2
) ;
1008 wxUnix2MacFilename( gwxMacFileName2
) ;
1010 if (0 == rename (gwxMacFileName
, gwxMacFileName2
))
1013 // Normal system call
1014 if (0 == rename (wxFNSTRINGCAST file1
.fn_str(), wxFNSTRINGCAST file2
.fn_str()))
1018 if (wxCopyFile(file1
, file2
)) {
1019 wxRemoveFile(file1
);
1026 bool wxRemoveFile(const wxString
& file
)
1028 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1029 int flag
= remove(wxFNSTRINGCAST file
.fn_str());
1030 #elif defined( __WXMAC__ )
1031 wxStrcpy( gwxMacFileName
, file
) ;
1032 wxUnix2MacFilename( gwxMacFileName
) ;
1033 int flag
= unlink(gwxMacFileName
);
1035 int flag
= unlink(wxFNSTRINGCAST file
.fn_str());
1037 return (flag
== 0) ;
1040 bool wxMkdir(const wxString
& dir
, int perm
)
1042 #if defined( __WXMAC__ )
1043 wxStrcpy( gwxMacFileName
, dir
) ;
1044 wxUnix2MacFilename( gwxMacFileName
) ;
1045 const wxChar
*dirname
= gwxMacFileName
;
1047 const wxChar
*dirname
= dir
.c_str();
1050 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1051 // for the GNU compiler
1052 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1053 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1054 #else // MSW and OS/2
1055 if ( mkdir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1058 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1066 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1070 #elif defined( __WXMAC__ )
1071 wxStrcpy( gwxMacFileName
, dir
) ;
1072 wxUnix2MacFilename( gwxMacFileName
) ;
1073 return (rmdir(WXSTRINGCAST gwxMacFileName
) == 0);
1077 return FALSE
; // What to do?
1079 return (rmdir(wxFNSTRINGCAST dir
.fn_str()) == 0);
1086 bool wxDirExists(const wxString
& dir
)
1090 #elif !defined(__WXMSW__)
1092 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1095 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1096 #if defined(__WIN32__)
1097 WIN32_FIND_DATA fileInfo
;
1100 struct ffblk fileInfo
;
1102 struct find_t fileInfo
;
1106 #if defined(__WIN32__)
1107 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1109 if (h
==INVALID_HANDLE_VALUE
)
1113 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1116 // In Borland findfirst has a different argument
1117 // ordering from _dos_findfirst. But _dos_findfirst
1118 // _should_ be ok in both MS and Borland... why not?
1120 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1122 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1131 // does the path exists? (may have or not '/' or '\\' at the end)
1132 bool wxPathExists(const wxChar
*pszPathName
)
1134 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1135 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1136 wxString
strPath(pszPathName
);
1137 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != wxT('\0') )
1138 strPath
.Last() = wxT('\0');
1146 return stat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1149 // Get a temporary filename, opening and closing the file.
1150 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1156 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1158 wxChar tmp
[MAX_PATH
];
1159 wxChar tmpPath
[MAX_PATH
];
1160 ::GetTempPath(MAX_PATH
, tmpPath
);
1161 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1163 if (buf
) wxStrcpy(buf
, tmp
);
1164 else buf
= copystring(tmp
);
1168 static short last_temp
= 0; // cache last to speed things a bit
1169 // At most 1000 temp files to a process! We use a ring count.
1170 wxChar tmp
[100]; // FIXME static buffer
1172 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1174 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1175 if (!wxFileExists( tmp
))
1177 // Touch the file to create it (reserve name)
1178 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1183 wxStrcpy( buf
, tmp
);
1185 buf
= copystring( tmp
);
1189 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1190 if (buf
) buf
[0] = 0;
1191 return (wxChar
*) NULL
;
1195 // Get first file name matching given wild card.
1199 // Get first file name matching given wild card.
1200 // Flags are reserved for future use.
1203 static DIR *gs_dirStream
= (DIR *) NULL
;
1204 static wxString gs_strFileSpec
;
1205 static int gs_findFlags
= 0;
1208 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1214 closedir(gs_dirStream
); // edz 941103: better housekeping
1216 gs_findFlags
= flags
;
1218 gs_strFileSpec
= spec
;
1220 // Find path only so we can concatenate
1221 // found file onto path
1222 wxString
path(wxPathOnly(gs_strFileSpec
));
1224 // special case: path is really "/"
1225 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1227 // path is empty => Local directory
1231 gs_dirStream
= opendir(path
.fn_str());
1232 if ( !gs_dirStream
)
1234 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1239 result
= wxFindNextFile();
1246 wxString
wxFindNextFile()
1251 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1253 // Find path only so we can concatenate
1254 // found file onto path
1255 wxString
path(wxPathOnly(gs_strFileSpec
));
1256 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1258 /* MATTHEW: special case: path is really "/" */
1259 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1263 struct dirent
*nextDir
;
1264 for ( nextDir
= readdir(gs_dirStream
);
1266 nextDir
= readdir(gs_dirStream
) )
1268 if (wxMatchWild(name
, nextDir
->d_name
))
1271 if ( !path
.IsEmpty() )
1274 if ( path
!= wxT('/') )
1278 result
+= nextDir
->d_name
;
1280 // Only return "." and ".." when they match
1282 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1283 (strcmp(nextDir
->d_name
, "..") == 0))
1285 if ( (gs_findFlags
& wxDIR
) != 0 )
1291 isdir
= wxDirExists(result
);
1293 // and only return directories when flags & wxDIR
1294 if ( !gs_findFlags
||
1295 ((gs_findFlags
& wxDIR
) && isdir
) ||
1296 ((gs_findFlags
& wxFILE
) && !isdir
) )
1303 result
.Empty(); // not found
1305 closedir(gs_dirStream
);
1306 gs_dirStream
= (DIR *) NULL
;
1312 #elif defined(__WXMSW__)
1315 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1316 static WIN32_FIND_DATA gs_findDataStruct
;
1319 static struct ffblk gs_findDataStruct
;
1321 static struct _find_t gs_findDataStruct
;
1325 static wxString gs_strFileSpec
;
1326 static int gs_findFlags
= 0;
1328 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1332 gs_strFileSpec
= spec
;
1333 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1335 // Find path only so we can concatenate found file onto path
1336 wxString
path(wxPathOnly(gs_strFileSpec
));
1337 if ( !path
.IsEmpty() )
1338 result
<< path
<< wxT('\\');
1341 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1342 FindClose(gs_hFileStruct
);
1344 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1346 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1353 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1355 if (isdir
&& !(flags
& wxDIR
))
1356 return wxFindNextFile();
1357 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1358 return wxFindNextFile();
1360 result
+= gs_findDataStruct
.cFileName
;
1364 int flag
= _A_NORMAL
;
1365 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1369 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1371 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1374 /* MATTHEW: [5] Check directory flag */
1378 attrib
= gs_findDataStruct
.ff_attrib
;
1380 attrib
= gs_findDataStruct
.attrib
;
1383 if (attrib
& _A_SUBDIR
) {
1384 if (!(gs_findFlags
& wxDIR
))
1385 return wxFindNextFile();
1386 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1387 return wxFindNextFile();
1391 gs_findDataStruct
.ff_name
1393 gs_findDataStruct
.name
1402 wxString
wxFindNextFile()
1406 // Find path only so we can concatenate found file onto path
1407 wxString
path(wxPathOnly(gs_strFileSpec
));
1412 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1415 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1418 FindClose(gs_hFileStruct
);
1419 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1423 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1425 if (isdir
&& !(gs_findFlags
& wxDIR
))
1427 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1430 if ( !path
.IsEmpty() )
1431 result
<< path
<< wxT('\\');
1432 result
<< gs_findDataStruct
.cFileName
;
1439 if (findnext(&gs_findDataStruct
) == 0)
1441 if (_dos_findnext(&gs_findDataStruct
) == 0)
1444 /* MATTHEW: [5] Check directory flag */
1448 attrib
= gs_findDataStruct
.ff_attrib
;
1450 attrib
= gs_findDataStruct
.attrib
;
1453 if (attrib
& _A_SUBDIR
) {
1454 if (!(gs_findFlags
& wxDIR
))
1456 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1462 gs_findDataStruct
.ff_name
1464 gs_findDataStruct
.name
1473 #endif // Unix/Windows
1475 // Get current working directory.
1476 // If buf is NULL, allocates space using new, else
1478 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1481 buf
= new wxChar
[sz
+1];
1483 char *cbuf
= new char[sz
+1];
1485 if (_getcwd(cbuf
, sz
) == NULL
) {
1487 if (getcwd(cbuf
, sz
) == NULL
) {
1492 if (_getcwd(buf
, sz
) == NULL
) {
1494 if (getcwd(buf
, sz
) == NULL
) {
1502 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1511 static const size_t maxPathLen
= 1024;
1514 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1515 str
.UngetWriteBuf();
1520 bool wxSetWorkingDirectory(const wxString
& d
)
1522 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1523 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1524 #elif defined(__WINDOWS__)
1527 return (bool)(SetCurrentDirectory(d
) != 0);
1529 // Must change drive, too.
1530 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1533 wxChar firstChar
= d
[0];
1537 firstChar
= firstChar
- 32;
1539 // To a drive number
1540 unsigned int driveNo
= firstChar
- 64;
1543 unsigned int noDrives
;
1544 _dos_setdrive(driveNo
, &noDrives
);
1547 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1555 // Get the OS directory if appropriate (such as the Windows directory).
1556 // On non-Windows platform, probably just return the empty string.
1557 wxString
wxGetOSDirectory()
1561 GetWindowsDirectory(buf
, 256);
1562 return wxString(buf
);
1564 return wxEmptyString
;
1568 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1570 size_t len
= wxStrlen(pszFileName
);
1574 return wxIsPathSeparator(pszFileName
[len
- 1]);
1577 // find a file in a list of directories, returns false if not found
1578 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1580 // we assume that it's not empty
1581 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1582 _("empty file name in wxFindFileInPath"));
1584 // skip path separator in the beginning of the file name if present
1585 if ( wxIsPathSeparator(*pszFile
) )
1588 // copy the path (strtok will modify it)
1589 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1590 wxStrcpy(szPath
, pszPath
);
1593 wxChar
*pc
, *save_ptr
;
1594 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1596 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1598 // search for the file in this directory
1600 if ( !wxEndsWithPathSeparator(pc
) )
1601 strFile
+= wxFILE_SEP_PATH
;
1604 if ( FileExists(strFile
) ) {
1610 // suppress warning about unused variable save_ptr when wxStrtok() is a
1611 // macro which throws away its third argument
1616 return pc
!= NULL
; // if true => we breaked from the loop
1619 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1624 // it can be empty, but it shouldn't be NULL
1625 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1627 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1630 // under Windows we understand both separators
1631 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1632 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1633 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1634 #else // assume Unix
1635 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1637 if ( pDot
== pszFileName
)
1639 // under Unix files like .profile are treated in a special way
1644 if ( pDot
< pLastSeparator
)
1646 // the dot is part of the path, not the start of the extension
1652 if ( pLastSeparator
)
1653 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1660 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1661 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1663 *pstrName
= wxString(start
, end
- start
);
1669 *pstrExt
= wxString(pDot
+ 1);
1675 //------------------------------------------------------------------------
1676 // wild character routines
1677 //------------------------------------------------------------------------
1679 bool wxIsWild( const wxString
& pattern
)
1681 wxString tmp
= pattern
;
1682 wxChar
*pat
= WXSTRINGCAST(tmp
);
1685 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1695 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1697 #if defined(HAVE_FNMATCH_H)
1699 // this probably won't work well for multibyte chars in Unicode mode?
1701 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1703 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1707 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1710 * WARNING: this code is broken!
1713 wxString tmp1
= pat
;
1714 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1715 wxString tmp2
= text
;
1716 wxChar
*str
= WXSTRINGCAST(tmp2
);
1719 bool done
= FALSE
, ret_code
, ok
;
1720 // Below is for vi fans
1721 const wxChar OB
= wxT('{'), CB
= wxT('}');
1723 // dot_special means '.' only matches '.'
1724 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1727 while ((*pattern
!= wxT('\0')) && (!done
)
1728 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1732 if (*pattern
!= wxT('\0'))
1738 while ((*str
!=wxT('\0'))
1739 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1742 while (*str
!= wxT('\0'))
1744 while (*pattern
!= wxT('\0'))
1751 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1755 if (*pattern
== wxT('\\')) {
1757 if (*pattern
== wxT('\0')) {
1762 if (*(pattern
+ 1) == wxT('-')) {
1765 if (*pattern
== wxT(']')) {
1769 if (*pattern
== wxT('\\')) {
1771 if (*pattern
== wxT('\0')) {
1776 if ((*str
< c
) || (*str
> *pattern
)) {
1780 } else if (*pattern
!= *str
) {
1785 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1786 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1790 if (*pattern
!= wxT('\0')) {
1800 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1803 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1804 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1805 if (*pattern
== wxT('\\'))
1807 ok
= (*pattern
++ == *cp
++);
1809 if (*pattern
== wxT('\0')) {
1815 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1816 if (*++pattern
== wxT('\\')) {
1817 if (*++pattern
== CB
)
1822 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1823 if (*++pattern
== wxT('\\')) {
1824 if (*++pattern
== CB
|| *pattern
== wxT(','))
1829 if (*pattern
!= wxT('\0'))
1834 if (*str
== *pattern
) {
1841 while (*pattern
== wxT('*'))
1843 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1849 #pragma warning(default:4706) // assignment within conditional expression