1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "filefn.h"
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
31 // there are just too many of those...
33 #pragma warning(disable:4706) // assignment within conditional expression
40 #if !defined(__WATCOMC__)
41 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
49 #include <sys/types.h>
66 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
70 #endif // native Win compiler
74 #include <sys/unistd.h>
77 #define stricmp strcasecmp
80 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
81 // this (3.1 I believe) and how to test for it.
82 // If this works for Borland 4.0 as well, then no worries.
94 // No, Cygwin doesn't appear to have fnmatch.h after all.
95 #if defined(HAVE_FNMATCH_H)
103 #define _MAXPATHLEN 500
105 extern wxChar
*wxBuffer
;
107 extern wxChar gwxMacFileName
[] ;
108 extern wxChar gwxMacFileName2
[] ;
109 extern wxChar gwxMacFileName3
[] ;
112 #if !USE_SHARED_LIBRARIES
113 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
116 void wxPathList::Add (const wxString
& path
)
118 wxStringList::Add (WXSTRINGCAST path
);
121 // Add paths e.g. from the PATH environment variable
122 void wxPathList::AddEnvList (const wxString
& envVariable
)
124 static const wxChar PATH_TOKS
[] =
126 _T(" ;"); // Don't seperate with colon in DOS (used for drive)
131 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
134 wxChar
*s
= copystring (val
);
135 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
139 Add (copystring (token
));
142 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
143 Add (wxString(token
));
150 // Given a full filename (with path), ensure that that file can
151 // be accessed again USING FILENAME ONLY by adding the path
152 // to the list if not already there.
153 void wxPathList::EnsureFileAccessible (const wxString
& path
)
155 wxString
path_only(wxPathOnly(path
));
156 if ( !path_only
.IsEmpty() )
158 if ( !Member(path_only
) )
163 bool wxPathList::Member (const wxString
& path
)
165 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
167 wxString
path2((wxChar
*) node
->Data ());
169 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
171 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
173 // Case sensitive File System
174 path
.CompareTo (path2
) == 0
182 wxString
wxPathList::FindValidPath (const wxString
& file
)
184 if (wxFileExists (wxExpandPath(wxBuffer
, file
)))
185 return wxString(wxBuffer
);
187 wxChar buf
[_MAXPATHLEN
];
188 wxStrcpy(buf
, wxBuffer
);
190 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
191 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
193 for (wxNode
* node
= First (); node
; node
= node
->Next ())
195 wxChar
*path
= (wxChar
*) node
->Data ();
196 wxStrcpy (wxBuffer
, path
);
197 wxChar ch
= wxBuffer
[wxStrlen(wxBuffer
)-1];
198 if (ch
!= _T('\\') && ch
!= _T('/'))
199 wxStrcat (wxBuffer
, _T("/"));
200 wxStrcat (wxBuffer
, filename
);
202 Unix2DosFilename (wxBuffer
);
204 if (wxFileExists (wxBuffer
))
206 return wxString(wxBuffer
); // Found!
210 return wxString(_T("")); // Not found
213 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
215 wxString f
= FindValidPath(file
);
216 if (wxIsAbsolutePath(f
))
221 wxGetWorkingDirectory(buf
, 499);
222 int len
= (int)wxStrlen(buf
);
226 if (lastCh
!= _T('/') && lastCh
!= _T('\\'))
229 wxStrcat(buf
, _T("\\"));
231 wxStrcat(buf
, _T("/"));
234 wxStrcat(buf
, (const wxChar
*)f
);
235 wxStrcpy(wxBuffer
, buf
);
236 return wxString(wxBuffer
);
241 wxFileExists (const wxString
& filename
)
243 #ifdef __GNUWIN32__ // (fix a B20 bug)
244 if (GetFileAttributes(filename
) == 0xFFFFFFFF)
248 #elif defined(__WXMAC__)
250 wxStrcpy( gwxMacFileName
, filename
) ;
251 wxUnix2MacFilename( gwxMacFileName
) ;
252 if (gwxMacFileName
&& stat (WXSTRINGCAST gwxMacFileName
, &stbuf
) == 0)
263 if ((filename
!= _T("")) && stat (FNSTRINGCAST filename
.fn_str(), &stbuf
) == 0)
269 /* Vadim's alternative implementation
271 // does the file exist?
272 bool wxFileExists(const char *pszFileName)
275 return !access(pszFileName, 0) &&
276 !stat(pszFileName, &st) &&
277 (st.st_mode & S_IFREG);
282 wxIsAbsolutePath (const wxString
& filename
)
284 if (filename
!= _T(""))
286 if (filename
[0] == _T('/')
288 || (filename
[0] == _T('[') && filename
[1] != _T('.'))
292 || filename
[0] == _T('\\') || (wxIsalpha (filename
[0]) && filename
[1] == _T(':'))
301 * Strip off any extension (dot something) from end of file,
302 * IF one exists. Inserts zero into buffer.
306 void wxStripExtension(wxChar
*buffer
)
308 int len
= wxStrlen(buffer
);
312 if (buffer
[i
] == _T('.'))
321 void wxStripExtension(wxString
& buffer
)
323 size_t len
= buffer
.Length();
327 if (buffer
.GetChar(i
) == _T('.'))
329 buffer
= buffer
.Left(i
);
336 // Destructive removal of /./ and /../ stuff
337 wxChar
*wxRealPath (wxChar
*path
)
340 static const wxChar SEP
= _T('\\');
341 Unix2DosFilename(path
);
343 static const wxChar SEP
= _T('/');
345 if (path
[0] && path
[1]) {
346 /* MATTHEW: special case "/./x" */
348 if (path
[2] == SEP
&& path
[1] == _T('.'))
356 if (p
[1] == _T('.') && p
[2] == _T('.') && (p
[3] == SEP
|| p
[3] == _T('\0')))
359 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
360 if (q
[0] == SEP
&& (q
[1] != _T('.') || q
[2] != _T('.') || q
[3] != SEP
)
361 && (q
- 1 <= path
|| q
[-1] != SEP
))
364 if (path
[0] == _T('\0'))
370 /* Check that path[2] is NULL! */
371 else if (path
[1] == _T(':') && !path
[2])
380 else if (p
[1] == _T('.') && (p
[2] == SEP
|| p
[2] == _T('\0')))
389 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
391 if (filename
== _T(""))
392 return (wxChar
*) NULL
;
394 if (! IsAbsolutePath(wxExpandPath(wxBuffer
, filename
))) {
395 wxChar buf
[_MAXPATHLEN
];
397 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
398 wxChar ch
= buf
[wxStrlen(buf
) - 1];
400 if (ch
!= _T('\\') && ch
!= _T('/'))
401 wxStrcat(buf
, _T("\\"));
404 wxStrcat(buf
, _T("/"));
406 wxStrcat(buf
, wxBuffer
);
407 return copystring( wxRealPath(buf
) );
409 return copystring( wxBuffer
);
415 ~user/ => user's home dir
416 If the environment variable a = "foo" and b = "bar" then:
433 /* input name in name, pathname output to buf. */
435 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
437 register wxChar
*d
, *s
, *nm
;
438 wxChar lnm
[_MAXPATHLEN
];
441 // Some compilers don't like this line.
442 // const wxChar trimchars[] = _T("\n \t");
445 trimchars
[0] = _T('\n');
446 trimchars
[1] = _T(' ');
447 trimchars
[2] = _T('\t');
451 const wxChar SEP
= _T('\\');
453 const wxChar SEP
= _T('/');
456 if (name
== NULL
|| *name
== _T('\0'))
458 nm
= copystring(name
); // Make a scratch copy
461 /* Skip leading whitespace and cr */
462 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
464 /* And strip off trailing whitespace and cr */
465 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
466 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
474 q
= nm
[0] == _T('\\') && nm
[1] == _T('~');
477 /* Expand inline environment variables */
495 while ((*d
++ = *s
)) {
497 if (*s
== _T('\\')) {
498 if ((*(d
- 1) = *++s
)) {
507 if (*s
++ == _T('$') && (*s
== _T('{') || *s
== _T(')')))
512 register wxChar
*start
= d
;
513 register int braces
= (*s
== _T('{') || *s
== _T('('));
514 register wxChar
*value
;
516 // VA gives assignment in logical expr warning
522 if (braces
? (*s
== _T('}') || *s
== _T(')')) : !(wxIsalnum(*s
) || *s
== _T('_')) )
527 value
= wxGetenv(braces
? start
+ 1 : start
);
530 // VA gives assignment in logical expr warning
531 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
533 for ((d
= start
- 1); (*d
++ = *value
++););
542 /* Expand ~ and ~user */
545 if (nm
[0] == _T('~') && !q
)
548 if (nm
[1] == SEP
|| nm
[1] == 0)
550 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
551 if ((s
= WXSTRINGCAST
wxGetUserHome(_T(""))) != NULL
) {
556 { /* ~user/filename */
557 register wxChar
*nnm
;
558 register wxChar
*home
;
559 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
560 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
561 was_sep
= (*s
== SEP
);
562 nnm
= *s
? s
+ 1 : s
;
564 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
565 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
566 if (was_sep
) /* replace only if it was there: */
577 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
579 while (_T('\0') != (*d
++ = *s
++))
582 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
587 // VA gives assignment in logical expr warning
591 while ((*d
++ = *s
++));
593 delete[] nm_tmp
; // clean up alloc
594 /* Now clean up the buffer */
595 return wxRealPath(buf
);
599 /* Contract Paths to be build upon an environment variable
602 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
604 The call wxExpandPath can convert these back!
607 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
609 static wxChar dest
[_MAXPATHLEN
];
611 if (filename
== _T(""))
612 return (wxChar
*) NULL
;
614 wxStrcpy (dest
, WXSTRINGCAST filename
);
616 Unix2DosFilename(dest
);
619 // Handle environment
620 const wxChar
*val
= (const wxChar
*) NULL
;
621 wxChar
*tcp
= (wxChar
*) NULL
;
622 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
623 (tcp
= wxStrstr (dest
, val
)) != NULL
)
625 wxStrcpy (wxBuffer
, tcp
+ wxStrlen (val
));
628 wxStrcpy (tcp
, WXSTRINGCAST envname
);
629 wxStrcat (tcp
, _T("}"));
630 wxStrcat (tcp
, wxBuffer
);
633 // Handle User's home (ignore root homes!)
635 if ((val
= wxGetUserHome (user
)) != NULL
&&
636 (len
= wxStrlen(val
)) > 2 &&
637 wxStrncmp(dest
, val
, len
) == 0)
639 wxStrcpy(wxBuffer
, _T("~"));
641 wxStrcat(wxBuffer
, (const wxChar
*) user
);
643 // strcat(wxBuffer, "\\");
645 // strcat(wxBuffer, "/");
647 wxStrcat(wxBuffer
, dest
+ len
);
648 wxStrcpy (dest
, wxBuffer
);
654 // Return just the filename, not the path
656 wxChar
*wxFileNameFromPath (wxChar
*path
)
660 register wxChar
*tcp
;
662 tcp
= path
+ wxStrlen (path
);
663 while (--tcp
>= path
)
665 if (*tcp
== _T('/') || *tcp
== _T('\\')
667 || *tcp
== _T(':') || *tcp
== _T(']'))
673 #if defined(__WXMSW__) || defined(__WXPM__)
674 if (wxIsalpha (*path
) && *(path
+ 1) == _T(':'))
681 wxString
wxFileNameFromPath (const wxString
& path1
)
686 wxChar
*path
= WXSTRINGCAST path1
;
687 register wxChar
*tcp
;
689 tcp
= path
+ wxStrlen (path
);
690 while (--tcp
>= path
)
692 if (*tcp
== _T('/') || *tcp
== _T('\\')
694 || *tcp
== _T(':') || *tcp
== _T(']'))
698 return wxString(tcp
+ 1);
700 #if defined(__WXMSW__) || defined(__WXPM__)
701 if (wxIsalpha (*path
) && *(path
+ 1) == _T(':'))
702 return wxString(path
+ 2);
705 // Yes, this should return the path, not an empty string, otherwise
706 // we get "thing.txt" -> "".
710 // Return just the directory, or NULL if no directory
712 wxPathOnly (wxChar
*path
)
716 static wxChar buf
[_MAXPATHLEN
];
719 wxStrcpy (buf
, path
);
721 int l
= wxStrlen(path
);
726 // Search backward for a backward or forward slash
727 while (!done
&& i
> -1)
730 if (path
[i
] == _T('/') || path
[i
] == _T('\\') || path
[i
] == _T(']'))
744 #if defined(__WXMSW__) || defined(__WXPM__)
745 // Try Drive specifier
746 if (wxIsalpha (buf
[0]) && buf
[1] == _T(':'))
748 // A:junk --> A:. (since A:.\junk Not A:\junk)
756 return (wxChar
*) NULL
;
759 // Return just the directory, or NULL if no directory
760 wxString
wxPathOnly (const wxString
& path
)
764 wxChar buf
[_MAXPATHLEN
];
767 wxStrcpy (buf
, WXSTRINGCAST path
);
769 int l
= path
.Length();
774 // Search backward for a backward or forward slash
775 while (!done
&& i
> -1)
778 if (path
[i
] == _T('/') || path
[i
] == _T('\\') || path
[i
] == _T(']'))
787 return wxString(buf
);
792 #if defined(__WXMSW__) || defined(__WXPM__)
793 // Try Drive specifier
794 if (wxIsalpha (buf
[0]) && buf
[1] == _T(':'))
796 // A:junk --> A:. (since A:.\junk Not A:\junk)
799 return wxString(buf
);
804 return wxString(_T(""));
807 // Utility for converting delimiters in DOS filenames to UNIX style
808 // and back again - or we get nasty problems with delimiters.
809 // Also, convert to lower case, since case is significant in UNIX.
813 wxMac2UnixFilename (wxChar
*s
)
817 memmove( s
+1 , s
,(strlen( s
) + 1)*sizeof(wxChar
)) ;
828 *s
= wxTolower(*s
); // Case INDEPENDENT
835 wxUnix2MacFilename (wxChar
*s
)
841 // relative path , since it goes on with slash which is translated to a :
842 memmove( s
, s
+1 ,strlen( s
)*sizeof(wxChar
) ) ;
844 else if ( *s
== _T('/') )
846 // absolute path -> on mac just start with the drive name
847 memmove( s
, s
+1 ,strlen( s
)*sizeof(wxChar
) ) ;
851 wxASSERT_MSG( 1 , _T("unknown path beginning") ) ;
855 if (*s
== _T('/') || *s
== _T('\\'))
864 wxDos2UnixFilename (wxChar
*s
)
871 #if defined(__WXMSW__) || defined(__WXPM__)
873 *s
= wxTolower(*s
); // Case INDEPENDENT
880 #if defined(__WXMSW__) || defined(__WXPM__)
881 wxUnix2DosFilename (wxChar
*s
)
883 wxUnix2DosFilename (wxChar
*WXUNUSED(s
))
886 // Yes, I really mean this to happen under DOS only! JACS
887 #if defined(__WXMSW__) || defined(__WXPM__)
898 // Concatenate two files to form third
900 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
902 wxChar
*outfile
= wxGetTempFileName("cat");
904 FILE *fp1
= (FILE *) NULL
;
905 FILE *fp2
= (FILE *) NULL
;
906 FILE *fp3
= (FILE *) NULL
;
907 // Open the inputs and outputs
909 wxStrcpy( gwxMacFileName
, file1
) ;
910 wxUnix2MacFilename( gwxMacFileName
) ;
911 wxStrcpy( gwxMacFileName2
, file2
) ;
912 wxUnix2MacFilename( gwxMacFileName2
) ;
913 wxStrcpy( gwxMacFileName3
, outfile
) ;
914 wxUnix2MacFilename( gwxMacFileName3
) ;
916 if ((fp1
= fopen (gwxMacFileName
, "rb")) == NULL
||
917 (fp2
= fopen (gwxMacFileName2
, "rb")) == NULL
||
918 (fp3
= fopen (gwxMacFileName3
, "wb")) == NULL
)
920 if ((fp1
= fopen (FNSTRINGCAST file1
.fn_str(), "rb")) == NULL
||
921 (fp2
= fopen (FNSTRINGCAST file2
.fn_str(), "rb")) == NULL
||
922 (fp3
= fopen (wxFNCONV(outfile
), "wb")) == NULL
)
935 while ((ch
= getc (fp1
)) != EOF
)
936 (void) putc (ch
, fp3
);
939 while ((ch
= getc (fp2
)) != EOF
)
940 (void) putc (ch
, fp3
);
944 bool result
= wxRenameFile(outfile
, file3
);
951 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
958 wxStrcpy( gwxMacFileName
, file1
) ;
959 wxUnix2MacFilename( gwxMacFileName
) ;
960 wxStrcpy( gwxMacFileName2
, file2
) ;
961 wxUnix2MacFilename( gwxMacFileName2
) ;
963 if ((fd1
= fopen (gwxMacFileName
, "rb")) == NULL
)
965 if ((fd2
= fopen (gwxMacFileName2
, "wb")) == NULL
)
967 if ((fd1
= fopen (FNSTRINGCAST file1
.fn_str(), "rb")) == NULL
)
969 if ((fd2
= fopen (FNSTRINGCAST file2
.fn_str(), "wb")) == NULL
)
976 while ((ch
= getc (fd1
)) != EOF
)
977 (void) putc (ch
, fd2
);
985 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
988 wxStrcpy( gwxMacFileName
, file1
) ;
989 wxUnix2MacFilename( gwxMacFileName
) ;
990 wxStrcpy( gwxMacFileName2
, file2
) ;
991 wxUnix2MacFilename( gwxMacFileName2
) ;
993 if (0 == rename (gwxMacFileName
, gwxMacFileName2
))
996 // Normal system call
997 if (0 == rename (FNSTRINGCAST file1
.fn_str(), FNSTRINGCAST file2
.fn_str()))
1001 if (wxCopyFile(file1
, file2
)) {
1002 wxRemoveFile(file1
);
1009 bool wxRemoveFile(const wxString
& file
)
1011 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1012 int flag
= remove(FNSTRINGCAST file
.fn_str());
1013 #elif defined( __WXMAC__ )
1014 wxStrcpy( gwxMacFileName
, file
) ;
1015 wxUnix2MacFilename( gwxMacFileName
) ;
1016 int flag
= unlink(gwxMacFileName
);
1018 int flag
= unlink(FNSTRINGCAST file
.fn_str());
1020 return (flag
== 0) ;
1023 bool wxMkdir(const wxString
& dir
, int perm
)
1025 #if defined( __WXMAC__ )
1026 wxStrcpy( gwxMacFileName
, dir
) ;
1027 wxUnix2MacFilename( gwxMacFileName
) ;
1028 const wxChar
*dirname
= gwxMacFileName
;
1030 const wxChar
*dirname
= dir
.c_str();
1033 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1034 // for the GNU compiler
1035 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1036 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1037 #else // MSW and OS/2
1038 if ( mkdir(FNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1041 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1049 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1053 #elif defined( __WXMAC__ )
1054 wxStrcpy( gwxMacFileName
, dir
) ;
1055 wxUnix2MacFilename( gwxMacFileName
) ;
1056 return (rmdir(WXSTRINGCAST gwxMacFileName
) == 0);
1060 return FALSE
; // What to do?
1062 return (rmdir(FNSTRINGCAST dir
.fn_str()) == 0);
1069 bool wxDirExists(const wxString
& dir
)
1073 #elif !defined(__WXMSW__)
1075 return (stat(dir
.fn_str(), &sbuf
) != -1) && S_ISDIR(sbuf
.st_mode
) ? TRUE
: FALSE
;
1078 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1079 #if defined(__WIN32__)
1080 WIN32_FIND_DATA fileInfo
;
1083 struct ffblk fileInfo
;
1085 struct find_t fileInfo
;
1089 #if defined(__WIN32__)
1090 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
1092 if (h
==INVALID_HANDLE_VALUE
)
1096 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
1099 // In Borland findfirst has a different argument
1100 // ordering from _dos_findfirst. But _dos_findfirst
1101 // _should_ be ok in both MS and Borland... why not?
1103 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
1105 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
1114 // does the path exists? (may have or not '/' or '\\' at the end)
1115 bool wxPathExists(const wxChar
*pszPathName
)
1117 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1118 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1119 wxString
strPath(pszPathName
);
1120 if ( wxEndsWithPathSeparator(pszPathName
) && pszPathName
[1] != _T('\0') )
1121 strPath
.Last() = _T('\0');
1129 return stat(FNSTRINGCAST strPath
.fn_str(), &st
) == 0 && (st
.st_mode
& S_IFDIR
);
1132 // Get a temporary filename, opening and closing the file.
1133 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1139 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1141 wxChar tmp
[MAX_PATH
];
1142 wxChar tmpPath
[MAX_PATH
];
1143 ::GetTempPath(MAX_PATH
, tmpPath
);
1144 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1146 if (buf
) wxStrcpy(buf
, tmp
);
1147 else buf
= copystring(tmp
);
1151 static short last_temp
= 0; // cache last to speed things a bit
1152 // At most 1000 temp files to a process! We use a ring count.
1153 wxChar tmp
[100]; // FIXME static buffer
1155 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1157 wxSprintf (tmp
, _T("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1158 if (!wxFileExists( tmp
))
1160 // Touch the file to create it (reserve name)
1161 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1166 wxStrcpy( buf
, tmp
);
1168 buf
= copystring( tmp
);
1172 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1173 if (buf
) buf
[0] = 0;
1174 return (wxChar
*) NULL
;
1178 // Get first file name matching given wild card.
1182 // Get first file name matching given wild card.
1183 // Flags are reserved for future use.
1186 static DIR *gs_dirStream
= (DIR *) NULL
;
1187 static wxString gs_strFileSpec
;
1188 static int gs_findFlags
= 0;
1191 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1197 closedir(gs_dirStream
); // edz 941103: better housekeping
1199 gs_findFlags
= flags
;
1201 gs_strFileSpec
= spec
;
1203 // Find path only so we can concatenate
1204 // found file onto path
1205 wxString
path(wxPathOnly(gs_strFileSpec
));
1207 // special case: path is really "/"
1208 if ( !path
&& gs_strFileSpec
[0u] == _T('/') )
1210 // path is empty => Local directory
1214 gs_dirStream
= opendir(path
.fn_str());
1215 if ( !gs_dirStream
)
1217 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1222 result
= wxFindNextFile();
1229 wxString
wxFindNextFile()
1234 wxCHECK_MSG( gs_dirStream
, result
, _T("must call wxFindFirstFile first") );
1236 // Find path only so we can concatenate
1237 // found file onto path
1238 wxString
path(wxPathOnly(gs_strFileSpec
));
1239 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1241 /* MATTHEW: special case: path is really "/" */
1242 if ( !path
&& gs_strFileSpec
[0u] == _T('/'))
1246 struct dirent
*nextDir
;
1247 for ( nextDir
= readdir(gs_dirStream
);
1249 nextDir
= readdir(gs_dirStream
) )
1251 if (wxMatchWild(name
, nextDir
->d_name
))
1254 if ( !path
.IsEmpty() )
1257 if ( path
!= _T('/') )
1261 result
+= nextDir
->d_name
;
1263 // Only return "." and ".." when they match
1265 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1266 (strcmp(nextDir
->d_name
, "..") == 0))
1268 if ( (gs_findFlags
& wxDIR
) != 0 )
1274 isdir
= wxDirExists(result
);
1276 // and only return directories when flags & wxDIR
1277 if ( !gs_findFlags
||
1278 ((gs_findFlags
& wxDIR
) && isdir
) ||
1279 ((gs_findFlags
& wxFILE
) && !isdir
) )
1286 result
.Empty(); // not found
1288 closedir(gs_dirStream
);
1289 gs_dirStream
= (DIR *) NULL
;
1295 #elif defined(__WXMSW__)
1298 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1299 static WIN32_FIND_DATA gs_findDataStruct
;
1302 static struct ffblk gs_findDataStruct
;
1304 static struct _find_t gs_findDataStruct
;
1308 static wxString gs_strFileSpec
;
1309 static int gs_findFlags
= 0;
1311 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1315 gs_strFileSpec
= spec
;
1316 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1318 // Find path only so we can concatenate found file onto path
1319 wxString
path(wxPathOnly(gs_strFileSpec
));
1320 if ( !path
.IsEmpty() )
1321 result
<< path
<< _T('\\');
1324 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1325 FindClose(gs_hFileStruct
);
1327 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1329 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1336 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1338 if (isdir
&& !(flags
& wxDIR
))
1339 return wxFindNextFile();
1340 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1341 return wxFindNextFile();
1343 result
+= gs_findDataStruct
.cFileName
;
1347 int flag
= _A_NORMAL
;
1348 if (flags
& wxDIR
) /* MATTHEW: [5] Use & */
1352 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1354 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1357 /* MATTHEW: [5] Check directory flag */
1361 attrib
= gs_findDataStruct
.ff_attrib
;
1363 attrib
= gs_findDataStruct
.attrib
;
1366 if (attrib
& _A_SUBDIR
) {
1367 if (!(gs_findFlags
& wxDIR
))
1368 return wxFindNextFile();
1369 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1370 return wxFindNextFile();
1374 gs_findDataStruct
.ff_name
1376 gs_findDataStruct
.name
1385 wxString
wxFindNextFile()
1389 // Find path only so we can concatenate found file onto path
1390 wxString
path(wxPathOnly(gs_strFileSpec
));
1395 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1398 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1401 FindClose(gs_hFileStruct
);
1402 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1406 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1408 if (isdir
&& !(gs_findFlags
& wxDIR
))
1410 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1413 if ( !path
.IsEmpty() )
1414 result
<< path
<< _T('\\');
1415 result
<< gs_findDataStruct
.cFileName
;
1422 if (findnext(&gs_findDataStruct
) == 0)
1424 if (_dos_findnext(&gs_findDataStruct
) == 0)
1427 /* MATTHEW: [5] Check directory flag */
1431 attrib
= gs_findDataStruct
.ff_attrib
;
1433 attrib
= gs_findDataStruct
.attrib
;
1436 if (attrib
& _A_SUBDIR
) {
1437 if (!(gs_findFlags
& wxDIR
))
1439 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1445 gs_findDataStruct
.ff_name
1447 gs_findDataStruct
.name
1456 #endif // Unix/Windows
1458 // Get current working directory.
1459 // If buf is NULL, allocates space using new, else
1461 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1464 buf
= new wxChar
[sz
+1];
1466 char *cbuf
= new char[sz
+1];
1468 if (_getcwd(cbuf
, sz
) == NULL
) {
1470 if (getcwd(cbuf
, sz
) == NULL
) {
1475 if (_getcwd(buf
, sz
) == NULL
) {
1477 if (getcwd(buf
, sz
) == NULL
) {
1485 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1494 static const size_t maxPathLen
= 1024;
1497 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1498 str
.UngetWriteBuf();
1503 bool wxSetWorkingDirectory(const wxString
& d
)
1505 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1506 return (chdir(FNSTRINGCAST d
.fn_str()) == 0);
1507 #elif defined(__WINDOWS__)
1510 return (bool)(SetCurrentDirectory(d
) != 0);
1512 // Must change drive, too.
1513 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1516 wxChar firstChar
= d
[0];
1520 firstChar
= firstChar
- 32;
1522 // To a drive number
1523 unsigned int driveNo
= firstChar
- 64;
1526 unsigned int noDrives
;
1527 _dos_setdrive(driveNo
, &noDrives
);
1530 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1538 // Get the OS directory if appropriate (such as the Windows directory).
1539 // On non-Windows platform, probably just return the empty string.
1540 wxString
wxGetOSDirectory()
1544 GetWindowsDirectory(buf
, 256);
1545 return wxString(buf
);
1547 return wxEmptyString
;
1551 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1553 size_t len
= wxStrlen(pszFileName
);
1557 return wxIsPathSeparator(pszFileName
[len
- 1]);
1560 // find a file in a list of directories, returns false if not found
1561 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1563 // we assume that it's not empty
1564 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1565 _("empty file name in wxFindFileInPath"));
1567 // skip path separator in the beginning of the file name if present
1568 if ( wxIsPathSeparator(*pszFile
) )
1571 // copy the path (strtok will modify it)
1572 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1573 wxStrcpy(szPath
, pszPath
);
1576 wxChar
*pc
, *save_ptr
;
1577 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1579 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1581 // search for the file in this directory
1583 if ( !wxEndsWithPathSeparator(pc
) )
1584 strFile
+= wxFILE_SEP_PATH
;
1587 if ( FileExists(strFile
) ) {
1595 return pc
!= NULL
; // if true => we breaked from the loop
1598 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1603 // it can be empty, but it shouldn't be NULL
1604 wxCHECK_RET( pszFileName
, _T("NULL file name in wxSplitPath") );
1606 const wxChar
*pDot
= wxStrrchr(pszFileName
, wxFILE_SEP_EXT
);
1609 // under Windows we understand both separators
1610 const wxChar
*pSepUnix
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1611 const wxChar
*pSepDos
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_DOS
);
1612 const wxChar
*pLastSeparator
= pSepUnix
> pSepDos
? pSepUnix
: pSepDos
;
1613 #else // assume Unix
1614 const wxChar
*pLastSeparator
= wxStrrchr(pszFileName
, wxFILE_SEP_PATH_UNIX
);
1616 if ( pDot
== pszFileName
)
1618 // under Unix files like .profile are treated in a special way
1623 if ( pDot
< pLastSeparator
)
1625 // the dot is part of the path, not the start of the extension
1631 if ( pLastSeparator
)
1632 *pstrPath
= wxString(pszFileName
, pLastSeparator
- pszFileName
);
1639 const wxChar
*start
= pLastSeparator
? pLastSeparator
+ 1 : pszFileName
;
1640 const wxChar
*end
= pDot
? pDot
: pszFileName
+ wxStrlen(pszFileName
);
1642 *pstrName
= wxString(start
, end
- start
);
1648 *pstrExt
= wxString(pDot
+ 1);
1654 //------------------------------------------------------------------------
1655 // wild character routines
1656 //------------------------------------------------------------------------
1658 bool wxIsWild( const wxString
& pattern
)
1660 wxString tmp
= pattern
;
1661 wxChar
*pat
= WXSTRINGCAST(tmp
);
1664 case _T('?'): case _T('*'): case _T('['): case _T('{'):
1674 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1676 #if defined(HAVE_FNMATCH_H)
1678 // this probably won't work well for multibyte chars in Unicode mode?
1680 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1682 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1686 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1689 * WARNING: this code is broken!
1692 wxString tmp1
= pat
;
1693 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1694 wxString tmp2
= text
;
1695 wxChar
*str
= WXSTRINGCAST(tmp2
);
1698 bool done
= FALSE
, ret_code
, ok
;
1699 // Below is for vi fans
1700 const wxChar OB
= _T('{'), CB
= _T('}');
1702 // dot_special means '.' only matches '.'
1703 if (dot_special
&& *str
== _T('.') && *pattern
!= *str
)
1706 while ((*pattern
!= _T('\0')) && (!done
)
1707 && (((*str
==_T('\0'))&&((*pattern
==OB
)||(*pattern
==_T('*'))))||(*str
!=_T('\0')))) {
1711 if (*pattern
!= _T('\0'))
1717 while ((*str
!=_T('\0'))
1718 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1721 while (*str
!= _T('\0'))
1723 while (*pattern
!= _T('\0'))
1730 if ((*pattern
== _T('\0')) || (*pattern
== _T(']'))) {
1734 if (*pattern
== _T('\\')) {
1736 if (*pattern
== _T('\0')) {
1741 if (*(pattern
+ 1) == _T('-')) {
1744 if (*pattern
== _T(']')) {
1748 if (*pattern
== _T('\\')) {
1750 if (*pattern
== _T('\0')) {
1755 if ((*str
< c
) || (*str
> *pattern
)) {
1759 } else if (*pattern
!= *str
) {
1764 while ((*pattern
!= _T(']')) && (*pattern
!= _T('\0'))) {
1765 if ((*pattern
== _T('\\')) && (*(pattern
+ 1) != _T('\0')))
1769 if (*pattern
!= _T('\0')) {
1779 while ((*pattern
!= CB
) && (*pattern
!= _T('\0'))) {
1782 while (ok
&& (*cp
!= _T('\0')) && (*pattern
!= _T('\0'))
1783 && (*pattern
!= _T(',')) && (*pattern
!= CB
)) {
1784 if (*pattern
== _T('\\'))
1786 ok
= (*pattern
++ == *cp
++);
1788 if (*pattern
== _T('\0')) {
1794 while ((*pattern
!= CB
) && (*pattern
!= _T('\0'))) {
1795 if (*++pattern
== _T('\\')) {
1796 if (*++pattern
== CB
)
1801 while (*pattern
!=CB
&& *pattern
!=_T(',') && *pattern
!=_T('\0')) {
1802 if (*++pattern
== _T('\\')) {
1803 if (*++pattern
== CB
|| *pattern
== _T(','))
1808 if (*pattern
!= _T('\0'))
1813 if (*str
== *pattern
) {
1820 while (*pattern
== _T('*'))
1822 return ((*str
== _T('\0')) && (*pattern
== _T('\0')));
1828 #pragma warning(default:4706) // assignment within conditional expression