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
116 extern wxChar gwxMacFileName
[] ;
117 extern wxChar gwxMacFileName2
[] ;
118 extern wxChar gwxMacFileName3
[] ;
121 #if !USE_SHARED_LIBRARIES
122 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
125 // ----------------------------------------------------------------------------
127 // ----------------------------------------------------------------------------
129 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
131 // ============================================================================
133 // ============================================================================
135 void wxPathList::Add (const wxString
& path
)
137 wxStringList::Add (WXSTRINGCAST path
);
140 // Add paths e.g. from the PATH environment variable
141 void wxPathList::AddEnvList (const wxString
& envVariable
)
143 static const wxChar PATH_TOKS
[] =
145 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
150 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
153 wxChar
*s
= copystring (val
);
154 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
158 Add (copystring (token
));
161 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
162 Add (wxString(token
));
166 // suppress warning about unused variable save_ptr when wxStrtok() is a
167 // macro which throws away its third argument
174 // Given a full filename (with path), ensure that that file can
175 // be accessed again USING FILENAME ONLY by adding the path
176 // to the list if not already there.
177 void wxPathList::EnsureFileAccessible (const wxString
& path
)
179 wxString
path_only(wxPathOnly(path
));
180 if ( !path_only
.IsEmpty() )
182 if ( !Member(path_only
) )
187 bool wxPathList::Member (const wxString
& path
)
189 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
191 wxString
path2((wxChar
*) node
->Data ());
193 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
195 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
197 // Case sensitive File System
198 path
.CompareTo (path2
) == 0
206 wxString
wxPathList::FindValidPath (const wxString
& file
)
208 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
209 return wxString(wxFileFunctionsBuffer
);
211 wxChar buf
[_MAXPATHLEN
];
212 wxStrcpy(buf
, wxFileFunctionsBuffer
);
214 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
215 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
217 for (wxNode
* node
= First (); node
; node
= node
->Next ())
219 wxChar
*path
= (wxChar
*) node
->Data ();
220 wxStrcpy (wxFileFunctionsBuffer
, path
);
221 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
222 if (ch
!= wxT('\\') && ch
!= wxT('/'))
223 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
224 wxStrcat (wxFileFunctionsBuffer
, filename
);
226 Unix2DosFilename (wxFileFunctionsBuffer
);
228 if (wxFileExists (wxFileFunctionsBuffer
))
230 return wxString(wxFileFunctionsBuffer
); // Found!
234 return wxString(wxT("")); // Not found
237 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
239 wxString f
= FindValidPath(file
);
240 if ( wxIsAbsolutePath(f
) )
244 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
246 if ( !wxEndsWithPathSeparator(buf
) )
248 buf
+= wxFILE_SEP_PATH
;
256 wxFileExists (const wxString
& filename
)
258 #ifdef __GNUWIN32__ // (fix a B20 bug)
259 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
263 #elif defined(__WXMAC__)
265 wxStrcpy( gwxMacFileName
, filename
) ;
266 wxUnix2MacFilename( gwxMacFileName
) ;
267 if (gwxMacFileName
&& stat (WXSTRINGCAST gwxMacFileName
, &stbuf
) == 0)
278 if ((filename
!= wxT("")) && stat (wxFNSTRINGCAST filename
.fn_str(), &stbuf
) == 0)
284 /* Vadim's alternative implementation
286 // does the file exist?
287 bool wxFileExists(const char *pszFileName)
290 return !access(pszFileName, 0) &&
291 !stat(pszFileName, &st) &&
292 (st.st_mode & S_IFREG);
297 wxIsAbsolutePath (const wxString
& filename
)
299 if (filename
!= wxT(""))
301 if (filename
[0] == wxT('/')
303 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
307 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
316 * Strip off any extension (dot something) from end of file,
317 * IF one exists. Inserts zero into buffer.
321 void wxStripExtension(wxChar
*buffer
)
323 int len
= wxStrlen(buffer
);
327 if (buffer
[i
] == wxT('.'))
336 void wxStripExtension(wxString
& buffer
)
338 size_t len
= buffer
.Length();
342 if (buffer
.GetChar(i
) == wxT('.'))
344 buffer
= buffer
.Left(i
);
351 // Destructive removal of /./ and /../ stuff
352 wxChar
*wxRealPath (wxChar
*path
)
355 static const wxChar SEP
= wxT('\\');
356 Unix2DosFilename(path
);
358 static const wxChar SEP
= wxT('/');
360 if (path
[0] && path
[1]) {
361 /* MATTHEW: special case "/./x" */
363 if (path
[2] == SEP
&& path
[1] == wxT('.'))
371 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
374 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
375 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
376 && (q
- 1 <= path
|| q
[-1] != SEP
))
379 if (path
[0] == wxT('\0'))
385 /* Check that path[2] is NULL! */
386 else if (path
[1] == wxT(':') && !path
[2])
395 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
404 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
406 if (filename
== wxT(""))
407 return (wxChar
*) NULL
;
409 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
410 wxChar buf
[_MAXPATHLEN
];
412 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
413 wxChar ch
= buf
[wxStrlen(buf
) - 1];
415 if (ch
!= wxT('\\') && ch
!= wxT('/'))
416 wxStrcat(buf
, wxT("\\"));
419 wxStrcat(buf
, wxT("/"));
421 wxStrcat(buf
, wxFileFunctionsBuffer
);
422 return copystring( wxRealPath(buf
) );
424 return copystring( wxFileFunctionsBuffer
);
430 ~user/ => user's home dir
431 If the environment variable a = "foo" and b = "bar" then:
448 /* input name in name, pathname output to buf. */
450 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
452 register wxChar
*d
, *s
, *nm
;
453 wxChar lnm
[_MAXPATHLEN
];
456 // Some compilers don't like this line.
457 // const wxChar trimchars[] = wxT("\n \t");
460 trimchars
[0] = wxT('\n');
461 trimchars
[1] = wxT(' ');
462 trimchars
[2] = wxT('\t');
466 const wxChar SEP
= wxT('\\');
468 const wxChar SEP
= wxT('/');
471 if (name
== NULL
|| *name
== wxT('\0'))
473 nm
= copystring(name
); // Make a scratch copy
476 /* Skip leading whitespace and cr */
477 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
479 /* And strip off trailing whitespace and cr */
480 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
481 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
489 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
492 /* Expand inline environment variables */
510 while ((*d
++ = *s
)) {
512 if (*s
== wxT('\\')) {
513 if ((*(d
- 1) = *++s
)) {
522 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
524 if (*s
++ == wxT('$'))
527 register wxChar
*start
= d
;
528 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
529 register wxChar
*value
;
531 // VA gives assignment in logical expr warning
537 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
542 value
= wxGetenv(braces
? start
+ 1 : start
);
545 // VA gives assignment in logical expr warning
546 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
548 for ((d
= start
- 1); (*d
++ = *value
++););
557 /* Expand ~ and ~user */
560 if (nm
[0] == wxT('~') && !q
)
563 if (nm
[1] == SEP
|| nm
[1] == 0)
565 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
566 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
571 { /* ~user/filename */
572 register wxChar
*nnm
;
573 register wxChar
*home
;
574 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
575 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
576 was_sep
= (*s
== SEP
);
577 nnm
= *s
? s
+ 1 : s
;
579 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
580 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
581 if (was_sep
) /* replace only if it was there: */
592 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
594 while (wxT('\0') != (*d
++ = *s
++))
597 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
602 // VA gives assignment in logical expr warning
606 while ((*d
++ = *s
++));
608 delete[] nm_tmp
; // clean up alloc
609 /* Now clean up the buffer */
610 return wxRealPath(buf
);
614 /* Contract Paths to be build upon an environment variable
617 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
619 The call wxExpandPath can convert these back!
622 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
624 static wxChar dest
[_MAXPATHLEN
];
626 if (filename
== wxT(""))
627 return (wxChar
*) NULL
;
629 wxStrcpy (dest
, WXSTRINGCAST filename
);
631 Unix2DosFilename(dest
);
634 // Handle environment
635 const wxChar
*val
= (const wxChar
*) NULL
;
636 wxChar
*tcp
= (wxChar
*) NULL
;
637 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
638 (tcp
= wxStrstr (dest
, val
)) != NULL
)
640 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
643 wxStrcpy (tcp
, WXSTRINGCAST envname
);
644 wxStrcat (tcp
, wxT("}"));
645 wxStrcat (tcp
, wxFileFunctionsBuffer
);
648 // Handle User's home (ignore root homes!)
650 if ((val
= wxGetUserHome (user
)) != NULL
&&
651 (len
= wxStrlen(val
)) > 2 &&
652 wxStrncmp(dest
, val
, len
) == 0)
654 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
656 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
658 // strcat(wxFileFunctionsBuffer, "\\");
660 // strcat(wxFileFunctionsBuffer, "/");
662 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
663 wxStrcpy (dest
, wxFileFunctionsBuffer
);
669 // Return just the filename, not the path
671 wxChar
*wxFileNameFromPath (wxChar
*path
)
675 register wxChar
*tcp
;
677 tcp
= path
+ wxStrlen (path
);
678 while (--tcp
>= path
)
680 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
682 || *tcp
== wxT(':') || *tcp
== wxT(']'))
688 #if defined(__WXMSW__) || defined(__WXPM__)
689 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
696 wxString
wxFileNameFromPath (const wxString
& path1
)
698 if (path1
!= wxT(""))
701 wxChar
*path
= WXSTRINGCAST path1
;
702 register wxChar
*tcp
;
704 tcp
= path
+ wxStrlen (path
);
705 while (--tcp
>= path
)
707 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
709 || *tcp
== wxT(':') || *tcp
== wxT(']'))
713 return wxString(tcp
+ 1);
715 #if defined(__WXMSW__) || defined(__WXPM__)
716 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
717 return wxString(path
+ 2);
720 // Yes, this should return the path, not an empty string, otherwise
721 // we get "thing.txt" -> "".
725 // Return just the directory, or NULL if no directory
727 wxPathOnly (wxChar
*path
)
731 static wxChar buf
[_MAXPATHLEN
];
734 wxStrcpy (buf
, path
);
736 int l
= wxStrlen(path
);
741 // Search backward for a backward or forward slash
742 while (!done
&& i
> -1)
745 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
759 #if defined(__WXMSW__) || defined(__WXPM__)
760 // Try Drive specifier
761 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
763 // A:junk --> A:. (since A:.\junk Not A:\junk)
771 return (wxChar
*) NULL
;
774 // Return just the directory, or NULL if no directory
775 wxString
wxPathOnly (const wxString
& path
)
779 wxChar buf
[_MAXPATHLEN
];
782 wxStrcpy (buf
, WXSTRINGCAST path
);
784 int l
= path
.Length();
789 // Search backward for a backward or forward slash
790 while (!done
&& i
> -1)
793 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
802 return wxString(buf
);
807 #if defined(__WXMSW__) || defined(__WXPM__)
808 // Try Drive specifier
809 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
811 // A:junk --> A:. (since A:.\junk Not A:\junk)
814 return wxString(buf
);
819 return wxString(wxT(""));
822 // Utility for converting delimiters in DOS filenames to UNIX style
823 // and back again - or we get nasty problems with delimiters.
824 // Also, convert to lower case, since case is significant in UNIX.
828 wxMac2UnixFilename (wxChar
*s
)
832 memmove( s
+1 , s
,(strlen( s
) + 1)*sizeof(wxChar
)) ;
833 if ( *s
== wxT(':') )
843 *s
= wxTolower(*s
); // Case INDEPENDENT
850 wxUnix2MacFilename (wxChar
*s
)
854 if ( *s
== wxT('.') )
856 // relative path , since it goes on with slash which is translated to a :
857 memmove( s
, s
+1 ,strlen( s
)*sizeof(wxChar
) ) ;
859 else if ( *s
== wxT('/') )
861 // absolute path -> on mac just start with the drive name
862 memmove( s
, s
+1 ,strlen( s
)*sizeof(wxChar
) ) ;
866 wxASSERT_MSG( 1 , wxT("unknown path beginning") ) ;
870 if (*s
== wxT('/') || *s
== wxT('\\'))
879 wxDos2UnixFilename (wxChar
*s
)
886 #if defined(__WXMSW__) || defined(__WXPM__)
888 *s
= wxTolower(*s
); // Case INDEPENDENT
895 #if defined(__WXMSW__) || defined(__WXPM__)
896 wxUnix2DosFilename (wxChar
*s
)
898 wxUnix2DosFilename (wxChar
*WXUNUSED(s
))
901 // Yes, I really mean this to happen under DOS only! JACS
902 #if defined(__WXMSW__) || defined(__WXPM__)
913 // Concatenate two files to form third
915 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
917 wxChar
*outfile
= wxGetTempFileName("cat");
919 FILE *fp1
= (FILE *) NULL
;
920 FILE *fp2
= (FILE *) NULL
;
921 FILE *fp3
= (FILE *) NULL
;
922 // Open the inputs and outputs
924 wxStrcpy( gwxMacFileName
, file1
) ;
925 wxUnix2MacFilename( gwxMacFileName
) ;
926 wxStrcpy( gwxMacFileName2
, file2
) ;
927 wxUnix2MacFilename( gwxMacFileName2
) ;
928 wxStrcpy( gwxMacFileName3
, outfile
) ;
929 wxUnix2MacFilename( gwxMacFileName3
) ;
931 if ((fp1
= fopen (gwxMacFileName
, "rb")) == NULL
||
932 (fp2
= fopen (gwxMacFileName2
, "rb")) == NULL
||
933 (fp3
= fopen (gwxMacFileName3
, "wb")) == NULL
)
935 if ((fp1
= fopen (wxFNSTRINGCAST file1
.fn_str(), "rb")) == NULL
||
936 (fp2
= fopen (wxFNSTRINGCAST file2
.fn_str(), "rb")) == NULL
||
937 (fp3
= fopen (wxFNCONV(outfile
), "wb")) == NULL
)
950 while ((ch
= getc (fp1
)) != EOF
)
951 (void) putc (ch
, fp3
);
954 while ((ch
= getc (fp2
)) != EOF
)
955 (void) putc (ch
, fp3
);
959 bool result
= wxRenameFile(outfile
, file3
);
966 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
973 wxStrcpy( gwxMacFileName
, file1
) ;
974 wxUnix2MacFilename( gwxMacFileName
) ;
975 wxStrcpy( gwxMacFileName2
, file2
) ;
976 wxUnix2MacFilename( gwxMacFileName2
) ;
978 if ((fd1
= fopen (gwxMacFileName
, "rb")) == NULL
)
980 if ((fd2
= fopen (gwxMacFileName2
, "wb")) == NULL
)
982 if ((fd1
= fopen (wxFNSTRINGCAST file1
.fn_str(), "rb")) == NULL
)
984 if ((fd2
= fopen (wxFNSTRINGCAST file2
.fn_str(), "wb")) == NULL
)
991 while ((ch
= getc (fd1
)) != EOF
)
992 (void) putc (ch
, fd2
);
1000 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1003 wxStrcpy( gwxMacFileName
, file1
) ;
1004 wxUnix2MacFilename( gwxMacFileName
) ;
1005 wxStrcpy( gwxMacFileName2
, file2
) ;
1006 wxUnix2MacFilename( gwxMacFileName2
) ;
1008 if (0 == rename (gwxMacFileName
, gwxMacFileName2
))
1011 // Normal system call
1012 if (0 == rename (wxFNSTRINGCAST file1
.fn_str(), wxFNSTRINGCAST file2
.fn_str()))
1016 if (wxCopyFile(file1
, file2
)) {
1017 wxRemoveFile(file1
);
1024 bool wxRemoveFile(const wxString
& file
)
1026 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1027 int flag
= remove(wxFNSTRINGCAST file
.fn_str());
1028 #elif defined( __WXMAC__ )
1029 wxStrcpy( gwxMacFileName
, file
) ;
1030 wxUnix2MacFilename( gwxMacFileName
) ;
1031 int flag
= unlink(gwxMacFileName
);
1033 int flag
= unlink(wxFNSTRINGCAST file
.fn_str());
1035 return (flag
== 0) ;
1038 bool wxMkdir(const wxString
& dir
, int perm
)
1040 #if defined( __WXMAC__ )
1041 wxStrcpy( gwxMacFileName
, dir
) ;
1042 wxUnix2MacFilename( gwxMacFileName
) ;
1043 const wxChar
*dirname
= gwxMacFileName
;
1045 const wxChar
*dirname
= dir
.c_str();
1048 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1049 // for the GNU compiler
1050 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1051 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1052 #else // MSW and OS/2
1053 if ( mkdir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1056 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1064 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1068 #elif defined( __WXMAC__ )
1069 wxStrcpy( gwxMacFileName
, dir
) ;
1070 wxUnix2MacFilename( gwxMacFileName
) ;
1071 return (rmdir(WXSTRINGCAST gwxMacFileName
) == 0);
1075 return FALSE
; // What to do?
1077 return (rmdir(wxFNSTRINGCAST dir
.fn_str()) == 0);
1084 bool wxDirExists(const wxString
& dir
)
1088 #elif !defined(__WXMSW__)
1090 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1093 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1094 #if defined(__WIN32__)
1095 WIN32_FIND_DATA fileInfo
;
1098 struct ffblk fileInfo
;
1100 struct find_t fileInfo
;
1104 #if defined(__WIN32__)
1105 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1107 if (h
==INVALID_HANDLE_VALUE
)
1111 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1114 // In Borland findfirst has a different argument
1115 // ordering from _dos_findfirst. But _dos_findfirst
1116 // _should_ be ok in both MS and Borland... why not?
1118 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1120 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1129 // does the path exists? (may have or not '/' or '\\' at the end)
1130 bool wxPathExists(const wxChar
*pszPathName
)
1132 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1133 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1134 wxString
strPath(pszPathName
);
1135 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != wxT('\0') )
1136 strPath
.Last() = wxT('\0');
1144 return stat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1147 // Get a temporary filename, opening and closing the file.
1148 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1154 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1156 wxChar tmp
[MAX_PATH
];
1157 wxChar tmpPath
[MAX_PATH
];
1158 ::GetTempPath(MAX_PATH
, tmpPath
);
1159 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1161 if (buf
) wxStrcpy(buf
, tmp
);
1162 else buf
= copystring(tmp
);
1166 static short last_temp
= 0; // cache last to speed things a bit
1167 // At most 1000 temp files to a process! We use a ring count.
1168 wxChar tmp
[100]; // FIXME static buffer
1170 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1172 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1173 if (!wxFileExists( tmp
))
1175 // Touch the file to create it (reserve name)
1176 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1181 wxStrcpy( buf
, tmp
);
1183 buf
= copystring( tmp
);
1187 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1188 if (buf
) buf
[0] = 0;
1189 return (wxChar
*) NULL
;
1193 // Get first file name matching given wild card.
1197 // Get first file name matching given wild card.
1198 // Flags are reserved for future use.
1201 static DIR *gs_dirStream
= (DIR *) NULL
;
1202 static wxString gs_strFileSpec
;
1203 static int gs_findFlags
= 0;
1206 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1212 closedir(gs_dirStream
); // edz 941103: better housekeping
1214 gs_findFlags
= flags
;
1216 gs_strFileSpec
= spec
;
1218 // Find path only so we can concatenate
1219 // found file onto path
1220 wxString
path(wxPathOnly(gs_strFileSpec
));
1222 // special case: path is really "/"
1223 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1225 // path is empty => Local directory
1229 gs_dirStream
= opendir(path
.fn_str());
1230 if ( !gs_dirStream
)
1232 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1237 result
= wxFindNextFile();
1244 wxString
wxFindNextFile()
1249 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1251 // Find path only so we can concatenate
1252 // found file onto path
1253 wxString
path(wxPathOnly(gs_strFileSpec
));
1254 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1256 /* MATTHEW: special case: path is really "/" */
1257 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1261 struct dirent
*nextDir
;
1262 for ( nextDir
= readdir(gs_dirStream
);
1264 nextDir
= readdir(gs_dirStream
) )
1266 if (wxMatchWild(name
, nextDir
->d_name
))
1269 if ( !path
.IsEmpty() )
1272 if ( path
!= wxT('/') )
1276 result
+= nextDir
->d_name
;
1278 // Only return "." and ".." when they match
1280 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1281 (strcmp(nextDir
->d_name
, "..") == 0))
1283 if ( (gs_findFlags
& wxDIR
) != 0 )
1289 isdir
= wxDirExists(result
);
1291 // and only return directories when flags & wxDIR
1292 if ( !gs_findFlags
||
1293 ((gs_findFlags
& wxDIR
) && isdir
) ||
1294 ((gs_findFlags
& wxFILE
) && !isdir
) )
1301 result
.Empty(); // not found
1303 closedir(gs_dirStream
);
1304 gs_dirStream
= (DIR *) NULL
;
1310 #elif defined(__WXMSW__)
1313 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1314 static WIN32_FIND_DATA gs_findDataStruct
;
1317 static struct ffblk gs_findDataStruct
;
1319 static struct _find_t gs_findDataStruct
;
1323 static wxString gs_strFileSpec
;
1324 static int gs_findFlags
= 0;
1326 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1330 gs_strFileSpec
= spec
;
1331 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1333 // Find path only so we can concatenate found file onto path
1334 wxString
path(wxPathOnly(gs_strFileSpec
));
1335 if ( !path
.IsEmpty() )
1336 result
<< path
<< wxT('\\');
1339 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1340 FindClose(gs_hFileStruct
);
1342 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1344 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1351 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1353 if (isdir
&& !(flags
& wxDIR
))
1354 return wxFindNextFile();
1355 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1356 return wxFindNextFile();
1358 result
+= gs_findDataStruct
.cFileName
;
1362 int flag
= _A_NORMAL
;
1363 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1367 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1369 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1372 /* MATTHEW: [5] Check directory flag */
1376 attrib
= gs_findDataStruct
.ff_attrib
;
1378 attrib
= gs_findDataStruct
.attrib
;
1381 if (attrib
& _A_SUBDIR
) {
1382 if (!(gs_findFlags
& wxDIR
))
1383 return wxFindNextFile();
1384 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1385 return wxFindNextFile();
1389 gs_findDataStruct
.ff_name
1391 gs_findDataStruct
.name
1400 wxString
wxFindNextFile()
1404 // Find path only so we can concatenate found file onto path
1405 wxString
path(wxPathOnly(gs_strFileSpec
));
1410 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1413 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1416 FindClose(gs_hFileStruct
);
1417 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1421 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1423 if (isdir
&& !(gs_findFlags
& wxDIR
))
1425 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1428 if ( !path
.IsEmpty() )
1429 result
<< path
<< wxT('\\');
1430 result
<< gs_findDataStruct
.cFileName
;
1437 if (findnext(&gs_findDataStruct
) == 0)
1439 if (_dos_findnext(&gs_findDataStruct
) == 0)
1442 /* MATTHEW: [5] Check directory flag */
1446 attrib
= gs_findDataStruct
.ff_attrib
;
1448 attrib
= gs_findDataStruct
.attrib
;
1451 if (attrib
& _A_SUBDIR
) {
1452 if (!(gs_findFlags
& wxDIR
))
1454 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1460 gs_findDataStruct
.ff_name
1462 gs_findDataStruct
.name
1471 #endif // Unix/Windows
1473 // Get current working directory.
1474 // If buf is NULL, allocates space using new, else
1476 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1479 buf
= new wxChar
[sz
+1];
1481 char *cbuf
= new char[sz
+1];
1483 if (_getcwd(cbuf
, sz
) == NULL
) {
1485 if (getcwd(cbuf
, sz
) == NULL
) {
1490 if (_getcwd(buf
, sz
) == NULL
) {
1492 if (getcwd(buf
, sz
) == NULL
) {
1500 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1509 static const size_t maxPathLen
= 1024;
1512 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1513 str
.UngetWriteBuf();
1518 bool wxSetWorkingDirectory(const wxString
& d
)
1520 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1521 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1522 #elif defined(__WINDOWS__)
1525 return (bool)(SetCurrentDirectory(d
) != 0);
1527 // Must change drive, too.
1528 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1531 wxChar firstChar
= d
[0];
1535 firstChar
= firstChar
- 32;
1537 // To a drive number
1538 unsigned int driveNo
= firstChar
- 64;
1541 unsigned int noDrives
;
1542 _dos_setdrive(driveNo
, &noDrives
);
1545 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1553 // Get the OS directory if appropriate (such as the Windows directory).
1554 // On non-Windows platform, probably just return the empty string.
1555 wxString
wxGetOSDirectory()
1559 GetWindowsDirectory(buf
, 256);
1560 return wxString(buf
);
1562 return wxEmptyString
;
1566 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1568 size_t len
= wxStrlen(pszFileName
);
1572 return wxIsPathSeparator(pszFileName
[len
- 1]);
1575 // find a file in a list of directories, returns false if not found
1576 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1578 // we assume that it's not empty
1579 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1580 _("empty file name in wxFindFileInPath"));
1582 // skip path separator in the beginning of the file name if present
1583 if ( wxIsPathSeparator(*pszFile
) )
1586 // copy the path (strtok will modify it)
1587 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1588 wxStrcpy(szPath
, pszPath
);
1591 wxChar
*pc
, *save_ptr
;
1592 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1594 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1596 // search for the file in this directory
1598 if ( !wxEndsWithPathSeparator(pc
) )
1599 strFile
+= wxFILE_SEP_PATH
;
1602 if ( FileExists(strFile
) ) {
1608 // suppress warning about unused variable save_ptr when wxStrtok() is a
1609 // macro which throws away its third argument
1614 return pc
!= NULL
; // if true => we breaked from the loop
1617 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1622 // it can be empty, but it shouldn't be NULL
1623 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1625 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1628 // under Windows we understand both separators
1629 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1630 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1631 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1632 #else // assume Unix
1633 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1635 if ( pDot
== pszFileName
)
1637 // under Unix files like .profile are treated in a special way
1642 if ( pDot
< pLastSeparator
)
1644 // the dot is part of the path, not the start of the extension
1650 if ( pLastSeparator
)
1651 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1658 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1659 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1661 *pstrName
= wxString(start
, end
- start
);
1667 *pstrExt
= wxString(pDot
+ 1);
1673 //------------------------------------------------------------------------
1674 // wild character routines
1675 //------------------------------------------------------------------------
1677 bool wxIsWild( const wxString
& pattern
)
1679 wxString tmp
= pattern
;
1680 wxChar
*pat
= WXSTRINGCAST(tmp
);
1683 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1693 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1695 #if defined(HAVE_FNMATCH_H)
1697 // this probably won't work well for multibyte chars in Unicode mode?
1699 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1701 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1705 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1708 * WARNING: this code is broken!
1711 wxString tmp1
= pat
;
1712 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1713 wxString tmp2
= text
;
1714 wxChar
*str
= WXSTRINGCAST(tmp2
);
1717 bool done
= FALSE
, ret_code
, ok
;
1718 // Below is for vi fans
1719 const wxChar OB
= wxT('{'), CB
= wxT('}');
1721 // dot_special means '.' only matches '.'
1722 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1725 while ((*pattern
!= wxT('\0')) && (!done
)
1726 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1730 if (*pattern
!= wxT('\0'))
1736 while ((*str
!=wxT('\0'))
1737 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1740 while (*str
!= wxT('\0'))
1742 while (*pattern
!= wxT('\0'))
1749 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1753 if (*pattern
== wxT('\\')) {
1755 if (*pattern
== wxT('\0')) {
1760 if (*(pattern
+ 1) == wxT('-')) {
1763 if (*pattern
== wxT(']')) {
1767 if (*pattern
== wxT('\\')) {
1769 if (*pattern
== wxT('\0')) {
1774 if ((*str
< c
) || (*str
> *pattern
)) {
1778 } else if (*pattern
!= *str
) {
1783 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1784 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1788 if (*pattern
!= wxT('\0')) {
1798 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1801 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1802 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1803 if (*pattern
== wxT('\\'))
1805 ok
= (*pattern
++ == *cp
++);
1807 if (*pattern
== wxT('\0')) {
1813 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1814 if (*++pattern
== wxT('\\')) {
1815 if (*++pattern
== CB
)
1820 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1821 if (*++pattern
== wxT('\\')) {
1822 if (*++pattern
== CB
|| *pattern
== wxT(','))
1827 if (*pattern
!= wxT('\0'))
1832 if (*str
== *pattern
) {
1839 while (*pattern
== wxT('*'))
1841 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
1847 #pragma warning(default:4706) // assignment within conditional expression