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"
35 #include "wx/filename.h"
37 // there are just too many of those...
39 #pragma warning(disable:4706) // assignment within conditional expression
46 #if !defined(__WATCOMC__)
47 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
55 #include <sys/types.h>
69 #include "wx/os2/private.h"
72 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
77 #endif // native Win compiler
81 #include <sys/unistd.h>
85 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
86 // this (3.1 I believe) and how to test for it.
87 // If this works for Borland 4.0 as well, then no worries.
99 // No, Cygwin doesn't appear to have fnmatch.h after all.
100 #if defined(HAVE_FNMATCH_H)
108 // ----------------------------------------------------------------------------
110 // ----------------------------------------------------------------------------
112 #define _MAXPATHLEN 500
114 extern wxChar
*wxBuffer
;
117 #include "morefile.h"
118 #include "moreextr.h"
119 #include "fullpath.h"
120 #include "fspcompa.h"
123 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
125 // ----------------------------------------------------------------------------
127 // ----------------------------------------------------------------------------
129 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
131 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
133 // VisualAge C++ V4.0 cannot have any external linkage const decs
134 // in headers included by more than one primary source
136 const off_t wxInvalidOffset
= (off_t
)-1;
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
143 // we need to translate Mac filenames before passing them to OS functions
145 #define OS_FILENAME(s) (wxUnix2MacFilename(s))
147 #define OS_FILENAME(s) (s.fn_str())
150 // ============================================================================
152 // ============================================================================
154 void wxPathList::Add (const wxString
& path
)
156 wxStringList::Add (WXSTRINGCAST path
);
159 // Add paths e.g. from the PATH environment variable
160 void wxPathList::AddEnvList (const wxString
& envVariable
)
162 static const wxChar PATH_TOKS
[] =
164 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
169 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
172 wxChar
*s
= copystring (val
);
173 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
177 Add (copystring (token
));
180 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
181 Add (wxString(token
));
185 // suppress warning about unused variable save_ptr when wxStrtok() is a
186 // macro which throws away its third argument
193 // Given a full filename (with path), ensure that that file can
194 // be accessed again USING FILENAME ONLY by adding the path
195 // to the list if not already there.
196 void wxPathList::EnsureFileAccessible (const wxString
& path
)
198 wxString
path_only(wxPathOnly(path
));
199 if ( !path_only
.IsEmpty() )
201 if ( !Member(path_only
) )
206 bool wxPathList::Member (const wxString
& path
)
208 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
210 wxString
path2((wxChar
*) node
->Data ());
212 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
214 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
216 // Case sensitive File System
217 path
.CompareTo (path2
) == 0
225 wxString
wxPathList::FindValidPath (const wxString
& file
)
227 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
228 return wxString(wxFileFunctionsBuffer
);
230 wxChar buf
[_MAXPATHLEN
];
231 wxStrcpy(buf
, wxFileFunctionsBuffer
);
233 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
234 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
236 for (wxNode
* node
= First (); node
; node
= node
->Next ())
238 wxChar
*path
= (wxChar
*) node
->Data ();
239 wxStrcpy (wxFileFunctionsBuffer
, path
);
240 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
241 if (ch
!= wxT('\\') && ch
!= wxT('/'))
242 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
243 wxStrcat (wxFileFunctionsBuffer
, filename
);
245 Unix2DosFilename (wxFileFunctionsBuffer
);
247 if (wxFileExists (wxFileFunctionsBuffer
))
249 return wxString(wxFileFunctionsBuffer
); // Found!
253 return wxString(wxT("")); // Not found
256 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
258 wxString f
= FindValidPath(file
);
259 if ( wxIsAbsolutePath(f
) )
263 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
265 if ( !wxEndsWithPathSeparator(buf
) )
267 buf
+= wxFILE_SEP_PATH
;
275 wxFileExists (const wxString
& filename
)
277 #ifdef __GNUWIN32__ // (fix a B20 bug)
278 return GetFileAttributes(filename
) != 0xFFFFFFFF;
281 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
289 wxIsAbsolutePath (const wxString
& filename
)
291 if (filename
!= wxT(""))
293 if (filename
[0] == wxT('/')
295 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
299 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
308 * Strip off any extension (dot something) from end of file,
309 * IF one exists. Inserts zero into buffer.
313 void wxStripExtension(wxChar
*buffer
)
315 int len
= wxStrlen(buffer
);
319 if (buffer
[i
] == wxT('.'))
328 void wxStripExtension(wxString
& buffer
)
330 size_t len
= buffer
.Length();
334 if (buffer
.GetChar(i
) == wxT('.'))
336 buffer
= buffer
.Left(i
);
343 // Destructive removal of /./ and /../ stuff
344 wxChar
*wxRealPath (wxChar
*path
)
347 static const wxChar SEP
= wxT('\\');
348 Unix2DosFilename(path
);
350 static const wxChar SEP
= wxT('/');
352 if (path
[0] && path
[1]) {
353 /* MATTHEW: special case "/./x" */
355 if (path
[2] == SEP
&& path
[1] == wxT('.'))
363 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
366 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
367 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
368 && (q
- 1 <= path
|| q
[-1] != SEP
))
371 if (path
[0] == wxT('\0'))
377 /* Check that path[2] is NULL! */
378 else if (path
[1] == wxT(':') && !path
[2])
387 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
396 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
398 if (filename
== wxT(""))
399 return (wxChar
*) NULL
;
401 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
402 wxChar buf
[_MAXPATHLEN
];
404 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
405 wxChar ch
= buf
[wxStrlen(buf
) - 1];
407 if (ch
!= wxT('\\') && ch
!= wxT('/'))
408 wxStrcat(buf
, wxT("\\"));
411 wxStrcat(buf
, wxT("/"));
413 wxStrcat(buf
, wxFileFunctionsBuffer
);
414 return copystring( wxRealPath(buf
) );
416 return copystring( wxFileFunctionsBuffer
);
422 ~user/ => user's home dir
423 If the environment variable a = "foo" and b = "bar" then:
440 /* input name in name, pathname output to buf. */
442 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
444 register wxChar
*d
, *s
, *nm
;
445 wxChar lnm
[_MAXPATHLEN
];
448 // Some compilers don't like this line.
449 // const wxChar trimchars[] = wxT("\n \t");
452 trimchars
[0] = wxT('\n');
453 trimchars
[1] = wxT(' ');
454 trimchars
[2] = wxT('\t');
458 const wxChar SEP
= wxT('\\');
460 const wxChar SEP
= wxT('/');
463 if (name
== NULL
|| *name
== wxT('\0'))
465 nm
= copystring(name
); // Make a scratch copy
468 /* Skip leading whitespace and cr */
469 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
471 /* And strip off trailing whitespace and cr */
472 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
473 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
481 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
484 /* Expand inline environment variables */
502 while ((*d
++ = *s
)) {
504 if (*s
== wxT('\\')) {
505 if ((*(d
- 1) = *++s
)) {
514 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
516 if (*s
++ == wxT('$'))
519 register wxChar
*start
= d
;
520 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
521 register wxChar
*value
;
523 // VA gives assignment in logical expr warning
529 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
534 value
= wxGetenv(braces
? start
+ 1 : start
);
537 // VA gives assignment in logical expr warning
538 for ((d
= start
- 1); (*d
); *d
++ = *value
++);
540 for ((d
= start
- 1); (*d
++ = *value
++););
549 /* Expand ~ and ~user */
552 if (nm
[0] == wxT('~') && !q
)
555 if (nm
[1] == SEP
|| nm
[1] == 0)
557 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
558 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
563 { /* ~user/filename */
564 register wxChar
*nnm
;
565 register wxChar
*home
;
566 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
567 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
568 was_sep
= (*s
== SEP
);
569 nnm
= *s
? s
+ 1 : s
;
571 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
572 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
573 if (was_sep
) /* replace only if it was there: */
584 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
586 while (wxT('\0') != (*d
++ = *s
++))
589 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
594 // VA gives assignment in logical expr warning
598 while ((*d
++ = *s
++));
600 delete[] nm_tmp
; // clean up alloc
601 /* Now clean up the buffer */
602 return wxRealPath(buf
);
605 /* Contract Paths to be build upon an environment variable
608 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
610 The call wxExpandPath can convert these back!
613 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
615 static wxChar dest
[_MAXPATHLEN
];
617 if (filename
== wxT(""))
618 return (wxChar
*) NULL
;
620 wxStrcpy (dest
, WXSTRINGCAST filename
);
622 Unix2DosFilename(dest
);
625 // Handle environment
626 const wxChar
*val
= (const wxChar
*) NULL
;
627 wxChar
*tcp
= (wxChar
*) NULL
;
628 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
629 (tcp
= wxStrstr (dest
, val
)) != NULL
)
631 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
634 wxStrcpy (tcp
, WXSTRINGCAST envname
);
635 wxStrcat (tcp
, wxT("}"));
636 wxStrcat (tcp
, wxFileFunctionsBuffer
);
639 // Handle User's home (ignore root homes!)
641 if ((val
= wxGetUserHome (user
)) != NULL
&&
642 (len
= wxStrlen(val
)) > 2 &&
643 wxStrncmp(dest
, val
, len
) == 0)
645 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
647 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
649 // strcat(wxFileFunctionsBuffer, "\\");
651 // strcat(wxFileFunctionsBuffer, "/");
653 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
654 wxStrcpy (dest
, wxFileFunctionsBuffer
);
660 // Return just the filename, not the path
662 wxChar
*wxFileNameFromPath (wxChar
*path
)
666 register wxChar
*tcp
;
668 tcp
= path
+ wxStrlen (path
);
669 while (--tcp
>= path
)
671 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
673 || *tcp
== wxT(':') || *tcp
== wxT(']'))
679 #if defined(__WXMSW__) || defined(__WXPM__)
680 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
687 wxString
wxFileNameFromPath (const wxString
& path1
)
689 if (path1
!= wxT(""))
692 wxChar
*path
= WXSTRINGCAST path1
;
693 register wxChar
*tcp
;
695 tcp
= path
+ wxStrlen (path
);
696 while (--tcp
>= path
)
698 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
700 || *tcp
== wxT(':') || *tcp
== wxT(']'))
704 return wxString(tcp
+ 1);
706 #if defined(__WXMSW__) || defined(__WXPM__)
707 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
708 return wxString(path
+ 2);
711 // Yes, this should return the path, not an empty string, otherwise
712 // we get "thing.txt" -> "".
716 // Return just the directory, or NULL if no directory
718 wxPathOnly (wxChar
*path
)
722 static wxChar buf
[_MAXPATHLEN
];
725 wxStrcpy (buf
, path
);
727 int l
= wxStrlen(path
);
732 // Search backward for a backward or forward slash
733 while (!done
&& i
> -1)
736 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
740 if ( path
[i
] == wxT(']') )
751 #if defined(__WXMSW__) || defined(__WXPM__)
752 // Try Drive specifier
753 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
755 // A:junk --> A:. (since A:.\junk Not A:\junk)
763 return (wxChar
*) NULL
;
766 // Return just the directory, or NULL if no directory
767 wxString
wxPathOnly (const wxString
& path
)
771 wxChar buf
[_MAXPATHLEN
];
774 wxStrcpy (buf
, WXSTRINGCAST path
);
776 int l
= path
.Length();
781 // Search backward for a backward or forward slash
782 while (!done
&& i
> -1)
785 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
789 if ( path
[i
] == wxT(']') )
795 return wxString(buf
);
800 #if defined(__WXMSW__) || defined(__WXPM__)
801 // Try Drive specifier
802 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
804 // A:junk --> A:. (since A:.\junk Not A:\junk)
807 return wxString(buf
);
812 return wxString(wxT(""));
815 // Utility for converting delimiters in DOS filenames to UNIX style
816 // and back again - or we get nasty problems with delimiters.
817 // Also, convert to lower case, since case is significant in UNIX.
821 static char sMacFileNameConversion
[ 1000 ] ;
823 wxString
wxMac2UnixFilename (const char *str
)
825 char *s
= sMacFileNameConversion
;
829 memmove( s
+1 , s
,strlen( s
) + 1) ;
840 *s
= wxTolower (*s
); // Case INDEPENDENT
844 return wxString (sMacFileNameConversion
) ;
847 wxString
wxUnix2MacFilename (const char *str
)
849 char *s
= sMacFileNameConversion
;
855 // relative path , since it goes on with slash which is translated to a :
856 memmove( s
, s
+1 ,strlen( s
) ) ;
858 else if ( *s
== '/' )
860 // absolute path -> on mac just start with the drive name
861 memmove( s
, s
+1 ,strlen( s
) ) ;
865 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
869 if (*s
== '/' || *s
== '\\')
871 // convert any back-directory situations
872 if ( *(s
+1) == '.' && *(s
+2) == '.' && ( (*(s
+3) == '/' || *(s
+3) == '\\') ) )
875 memmove( s
+1 , s
+3 ,strlen( s
+3 ) + 1 ) ;
884 return wxString (sMacFileNameConversion
) ;
887 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
892 FSpGetFullPath( spec
, &length
, &myPath
) ;
893 ::SetHandleSize( myPath
, length
+ 1 ) ;
895 (*myPath
)[length
] = 0 ;
896 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
897 (*myPath
)[length
-1] = 0 ;
899 wxString
result( (char*) *myPath
) ;
900 ::HUnlock( myPath
) ;
901 ::DisposeHandle( myPath
) ;
905 wxString
wxMacFSSpec2UnixFilename( const FSSpec
*spec
)
907 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec
) ) ;
910 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
912 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
915 void wxUnixFilename2FSSpec( const char *path
, FSSpec
*spec
)
917 wxString var
= wxUnix2MacFilename( path
) ;
918 wxMacFilename2FSSpec( var
, spec
) ;
923 wxDos2UnixFilename (char *s
)
932 *s
= wxTolower (*s
); // Case INDEPENDENT
939 #if defined(__WXMSW__) || defined(__WXPM__)
940 wxUnix2DosFilename (wxChar
*s
)
942 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
945 // Yes, I really mean this to happen under DOS only! JACS
946 #if defined(__WXMSW__) || defined(__WXPM__)
957 // Concatenate two files to form third
959 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
962 if ( !wxGetTempFileName("cat", outfile
) )
965 FILE *fp1
= (FILE *) NULL
;
966 FILE *fp2
= (FILE *) NULL
;
967 FILE *fp3
= (FILE *) NULL
;
968 // Open the inputs and outputs
969 if ((fp1
= fopen (OS_FILENAME( file1
), "rb")) == NULL
||
970 (fp2
= fopen (OS_FILENAME( file2
), "rb")) == NULL
||
971 (fp3
= fopen (OS_FILENAME( outfile
), "wb")) == NULL
)
983 while ((ch
= getc (fp1
)) != EOF
)
984 (void) putc (ch
, fp3
);
987 while ((ch
= getc (fp2
)) != EOF
)
988 (void) putc (ch
, fp3
);
992 bool result
= wxRenameFile(outfile
, file3
);
998 wxCopyFile (const wxString
& file1
, const wxString
& file2
)
1002 // get permissions of file1
1003 if ( wxStat(file1
, &fbuf
) != 0 )
1005 // the file probably doesn't exist or we haven't the rights to read
1007 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1012 // open file1 for reading
1013 wxFile
fileIn(file1
, wxFile::read
);
1014 if ( !fileIn
.IsOpened() )
1017 // remove file2, if it exists. This is needed for creating
1018 // file2 with the correct permissions in the next step
1019 if ( wxFileExists(file2
) && !wxRemoveFile(file2
) )
1021 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1027 // reset the umask as we want to create the file with exactly the same
1028 // permissions as the original one
1029 mode_t oldUmask
= umask( 0 );
1032 // create file2 with the same permissions than file1 and open it for
1035 if ( !fileOut
.Create(file2
, TRUE
, fbuf
.st_mode
& 0777) )
1039 /// restore the old umask
1043 // copy contents of file1 to file2
1048 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1049 if ( fileIn
.Error() )
1056 if ( fileOut
.Write(buf
, count
) < count
)
1060 #ifndef __VISAGECPP__
1061 // no chmod in VA. SHould be some permission API for HPFS386 partitions however
1062 if ( chmod(file2
, fbuf
.st_mode
) != 0 )
1064 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1073 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1075 // Normal system call
1076 if ( wxRename (OS_FILENAME(file1
), OS_FILENAME(file2
)) == 0 )
1080 if (wxCopyFile(file1
, file2
)) {
1081 wxRemoveFile(file1
);
1088 bool wxRemoveFile(const wxString
& file
)
1090 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1091 int res
= wxRemove(file
);
1093 int res
= unlink(OS_FILENAME(file
));
1099 bool wxMkdir(const wxString
& dir
, int perm
)
1101 #if defined( __WXMAC__ )
1102 return (mkdir(wxUnix2MacFilename( dir
) , 0 ) == 0);
1104 const wxChar
*dirname
= dir
.c_str();
1106 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1107 // for the GNU compiler
1108 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1109 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1110 #elif defined(__WXPM__)
1111 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1112 #else // !MSW and !OS/2 VAC++
1113 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1116 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1125 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1128 return FALSE
; //to be changed since rmdir exists in VMS7.x
1129 #elif defined(__WXPM__)
1130 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1134 return FALSE
; // What to do?
1136 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1142 // does the path exists? (may have or not '/' or '\\' at the end)
1143 bool wxPathExists(const wxChar
*pszPathName
)
1145 wxString
strPath(pszPathName
);
1147 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1148 // so remove all trailing backslashes from the path - but don't do this for
1149 // the pathes "d:\" (which are different from "d:") nor for just "\"
1150 while ( wxEndsWithPathSeparator(strPath
) )
1152 size_t len
= strPath
.length();
1153 if ( len
== 1 || strPath
[len
- 1] == _T(':') )
1156 strPath
.Truncate(len
- 1);
1158 #endif // __WINDOWS__
1161 #ifndef __VISAGECPP__
1162 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1163 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1165 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1166 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1167 (st
.st_mode
== S_IFDIR
);
1172 // Get a temporary filename, opening and closing the file.
1173 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1179 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1181 wxChar tmp
[MAX_PATH
];
1182 wxChar tmpPath
[MAX_PATH
];
1183 ::GetTempPath(MAX_PATH
, tmpPath
);
1184 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1186 if (buf
) wxStrcpy(buf
, tmp
);
1187 else buf
= copystring(tmp
);
1191 static short last_temp
= 0; // cache last to speed things a bit
1192 // At most 1000 temp files to a process! We use a ring count.
1193 wxChar tmp
[100]; // FIXME static buffer
1195 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1197 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1198 if (!wxFileExists( tmp
))
1200 // Touch the file to create it (reserve name)
1201 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1206 wxStrcpy( buf
, tmp
);
1208 buf
= copystring( tmp
);
1212 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1213 if (buf
) buf
[0] = 0;
1214 return (wxChar
*) NULL
;
1218 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1221 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1230 // Get first file name matching given wild card.
1234 // Get first file name matching given wild card.
1235 // Flags are reserved for future use.
1237 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1238 static DIR *gs_dirStream
= (DIR *) NULL
;
1239 static wxString gs_strFileSpec
;
1240 static int gs_findFlags
= 0;
1243 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1247 wxChar
*specvms
= NULL
;
1250 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1252 closedir(gs_dirStream
); // edz 941103: better housekeping
1254 gs_findFlags
= flags
;
1256 gs_strFileSpec
= spec
;
1258 // Find path only so we can concatenate
1259 // found file onto path
1260 wxString
path(wxPathOnly(gs_strFileSpec
));
1262 // special case: path is really "/"
1263 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1266 wxStrcpy( specvms
, wxT( "[000000]" ) );
1267 gs_strFileSpec
= specvms
;
1268 wxString
path_vms(wxPathOnly(gs_strFileSpec
));
1274 // path is empty => Local directory
1278 wxStrcpy( specvms
, wxT( "[]" ) );
1279 gs_strFileSpec
= specvms
;
1280 wxString
path_vms1(wxPathOnly(gs_strFileSpec
));
1287 gs_dirStream
= opendir(path
.fn_str());
1288 if ( !gs_dirStream
)
1290 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1295 result
= wxFindNextFile();
1297 #endif // !VMS6.x or earlier
1302 wxString
wxFindNextFile()
1306 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1307 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1309 // Find path only so we can concatenate
1310 // found file onto path
1311 wxString
path(wxPathOnly(gs_strFileSpec
));
1312 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1314 /* MATTHEW: special case: path is really "/" */
1315 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1319 struct dirent
*nextDir
;
1320 for ( nextDir
= readdir(gs_dirStream
);
1322 nextDir
= readdir(gs_dirStream
) )
1324 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1325 strcmp(nextDir
->d_name
, ".") &&
1326 strcmp(nextDir
->d_name
, "..") )
1329 if ( !path
.IsEmpty() )
1332 if ( path
!= wxT('/') )
1336 result
+= nextDir
->d_name
;
1338 // Only return "." and ".." when they match
1340 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1341 (strcmp(nextDir
->d_name
, "..") == 0))
1343 if ( (gs_findFlags
& wxDIR
) != 0 )
1349 isdir
= wxDirExists(result
);
1351 // and only return directories when flags & wxDIR
1352 if ( !gs_findFlags
||
1353 ((gs_findFlags
& wxDIR
) && isdir
) ||
1354 ((gs_findFlags
& wxFILE
) && !isdir
) )
1361 result
.Empty(); // not found
1363 closedir(gs_dirStream
);
1364 gs_dirStream
= (DIR *) NULL
;
1365 #endif // !VMS6.2 or earlier
1370 #elif defined(__WXMAC__)
1372 struct MacDirectoryIterator
1380 static int g_iter_flags
;
1382 static MacDirectoryIterator g_iter
;
1384 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1388 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1390 // Find path only so we can concatenate found file onto path
1391 wxString
path(wxPathOnly(spec
));
1392 if ( !path
.IsEmpty() )
1393 result
<< path
<< wxT('\\');
1397 wxUnixFilename2FSSpec( result
, &fsspec
) ;
1398 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1399 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1400 g_iter
.m_index
= 0 ;
1403 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1405 return wxEmptyString
;
1407 return wxFindNextFile( ) ;
1410 wxString
wxFindNextFile()
1416 while ( err
== noErr
)
1419 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1420 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1421 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1425 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1428 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1436 return wxEmptyString
;
1440 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1445 return wxMacFSSpec2UnixFilename( &spec
) ;
1448 #elif defined(__WXMSW__)
1451 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1452 static WIN32_FIND_DATA gs_findDataStruct
;
1455 static struct ffblk gs_findDataStruct
;
1457 static struct _find_t gs_findDataStruct
;
1461 static wxString gs_strFileSpec
;
1462 static int gs_findFlags
= 0;
1464 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1468 gs_strFileSpec
= spec
;
1469 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1471 // Find path only so we can concatenate found file onto path
1472 wxString
path(wxPathOnly(gs_strFileSpec
));
1473 if ( !path
.IsEmpty() )
1474 result
<< path
<< wxT('\\');
1477 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1478 FindClose(gs_hFileStruct
);
1480 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1482 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1489 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1491 if (isdir
&& !(flags
& wxDIR
))
1492 return wxFindNextFile();
1493 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1494 return wxFindNextFile();
1496 result
+= gs_findDataStruct
.cFileName
;
1500 int flag
= _A_NORMAL
;
1505 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1507 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1513 attrib
= gs_findDataStruct
.ff_attrib
;
1515 attrib
= gs_findDataStruct
.attrib
;
1518 if (attrib
& _A_SUBDIR
) {
1519 if (!(gs_findFlags
& wxDIR
))
1520 return wxFindNextFile();
1521 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1522 return wxFindNextFile();
1526 gs_findDataStruct
.ff_name
1528 gs_findDataStruct
.name
1538 wxString
wxFindNextFile()
1542 // Find path only so we can concatenate found file onto path
1543 wxString
path(wxPathOnly(gs_strFileSpec
));
1548 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1551 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1554 FindClose(gs_hFileStruct
);
1555 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1559 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1561 if (isdir
&& !(gs_findFlags
& wxDIR
))
1563 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1566 if ( !path
.IsEmpty() )
1567 result
<< path
<< wxT('\\');
1568 result
<< gs_findDataStruct
.cFileName
;
1575 if (findnext(&gs_findDataStruct
) == 0)
1577 if (_dos_findnext(&gs_findDataStruct
) == 0)
1580 /* MATTHEW: [5] Check directory flag */
1584 attrib
= gs_findDataStruct
.ff_attrib
;
1586 attrib
= gs_findDataStruct
.attrib
;
1589 if (attrib
& _A_SUBDIR
) {
1590 if (!(gs_findFlags
& wxDIR
))
1592 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1598 gs_findDataStruct
.ff_name
1600 gs_findDataStruct
.name
1609 #elif defined(__WXPM__)
1611 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1616 // TODO: figure something out here for OS/2
1617 gs_strFileSpec = spec;
1618 gs_findFlags = flags;
1620 // Find path only so we can concatenate found file onto path
1621 wxString path(wxPathOnly(gs_strFileSpec));
1622 if ( !path.IsEmpty() )
1623 result << path << wxT('\\');
1625 int flag = _A_NORMAL;
1629 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1632 attrib = gs_findDataStruct.attrib;
1634 if (attrib & _A_SUBDIR) {
1635 if (!(gs_findFlags & wxDIR))
1636 return wxFindNextFile();
1637 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1638 return wxFindNextFile();
1640 result += gs_findDataStruct.name;
1646 wxString
wxFindNextFile()
1653 #endif // Unix/Windows/OS/2
1655 // Get current working directory.
1656 // If buf is NULL, allocates space using new, else
1658 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1661 buf
= new wxChar
[sz
+1];
1663 char *cbuf
= new char[sz
+1];
1665 if (_getcwd(cbuf
, sz
) == NULL
) {
1666 #elif defined( __WXMAC__)
1669 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1673 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1674 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1675 strcpy( buf
, res
) ;
1678 if (getcwd(cbuf
, sz
) == NULL
) {
1683 if (_getcwd(buf
, sz
) == NULL
) {
1684 #elif defined( __WXMAC__)
1687 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1691 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1692 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1693 strcpy( buf
, res
) ;
1695 #elif(__VISAGECPP__)
1697 rc
= ::DosQueryCurrentDir( 0 // current drive
1703 if (getcwd(buf
, sz
) == NULL
) {
1711 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1720 static const size_t maxPathLen
= 1024;
1723 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1724 str
.UngetWriteBuf();
1729 bool wxSetWorkingDirectory(const wxString
& d
)
1731 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1732 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1733 #elif defined(__WXPM__)
1734 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1735 #elif defined(__WINDOWS__)
1738 return (bool)(SetCurrentDirectory(d
) != 0);
1740 // Must change drive, too.
1741 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1744 wxChar firstChar
= d
[0];
1748 firstChar
= firstChar
- 32;
1750 // To a drive number
1751 unsigned int driveNo
= firstChar
- 64;
1754 unsigned int noDrives
;
1755 _dos_setdrive(driveNo
, &noDrives
);
1758 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1766 // Get the OS directory if appropriate (such as the Windows directory).
1767 // On non-Windows platform, probably just return the empty string.
1768 wxString
wxGetOSDirectory()
1772 GetWindowsDirectory(buf
, 256);
1773 return wxString(buf
);
1775 return wxEmptyString
;
1779 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1781 size_t len
= wxStrlen(pszFileName
);
1785 return wxIsPathSeparator(pszFileName
[len
- 1]);
1788 // find a file in a list of directories, returns false if not found
1789 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1791 // we assume that it's not empty
1792 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1793 _T("empty file name in wxFindFileInPath"));
1795 // skip path separator in the beginning of the file name if present
1796 if ( wxIsPathSeparator(*pszFile
) )
1799 // copy the path (strtok will modify it)
1800 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1801 wxStrcpy(szPath
, pszPath
);
1804 wxChar
*pc
, *save_ptr
;
1805 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1807 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1809 // search for the file in this directory
1811 if ( !wxEndsWithPathSeparator(pc
) )
1812 strFile
+= wxFILE_SEP_PATH
;
1815 if ( FileExists(strFile
) ) {
1821 // suppress warning about unused variable save_ptr when wxStrtok() is a
1822 // macro which throws away its third argument
1827 return pc
!= NULL
; // if true => we breaked from the loop
1830 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1835 // it can be empty, but it shouldn't be NULL
1836 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1838 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1841 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1845 wxStat(filename
.fn_str(), &buf
);
1846 return buf
.st_mtime
;
1850 //------------------------------------------------------------------------
1851 // wild character routines
1852 //------------------------------------------------------------------------
1854 bool wxIsWild( const wxString
& pattern
)
1856 wxString tmp
= pattern
;
1857 wxChar
*pat
= WXSTRINGCAST(tmp
);
1860 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1870 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1872 #if defined(HAVE_FNMATCH_H)
1874 // this probably won't work well for multibyte chars in Unicode mode?
1876 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1878 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1882 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1885 * WARNING: this code is broken!
1888 wxString tmp1
= pat
;
1889 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1890 wxString tmp2
= text
;
1891 wxChar
*str
= WXSTRINGCAST(tmp2
);
1894 bool done
= FALSE
, ret_code
, ok
;
1895 // Below is for vi fans
1896 const wxChar OB
= wxT('{'), CB
= wxT('}');
1898 // dot_special means '.' only matches '.'
1899 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1902 while ((*pattern
!= wxT('\0')) && (!done
)
1903 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1907 if (*pattern
!= wxT('\0'))
1913 while ((*str
!=wxT('\0'))
1914 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1917 while (*str
!= wxT('\0'))
1919 while (*pattern
!= wxT('\0'))
1926 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1930 if (*pattern
== wxT('\\')) {
1932 if (*pattern
== wxT('\0')) {
1937 if (*(pattern
+ 1) == wxT('-')) {
1940 if (*pattern
== wxT(']')) {
1944 if (*pattern
== wxT('\\')) {
1946 if (*pattern
== wxT('\0')) {
1951 if ((*str
< c
) || (*str
> *pattern
)) {
1955 } else if (*pattern
!= *str
) {
1960 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
1961 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
1965 if (*pattern
!= wxT('\0')) {
1975 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1978 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
1979 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
1980 if (*pattern
== wxT('\\'))
1982 ok
= (*pattern
++ == *cp
++);
1984 if (*pattern
== wxT('\0')) {
1990 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
1991 if (*++pattern
== wxT('\\')) {
1992 if (*++pattern
== CB
)
1997 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
1998 if (*++pattern
== wxT('\\')) {
1999 if (*++pattern
== CB
|| *pattern
== wxT(','))
2004 if (*pattern
!= wxT('\0'))
2009 if (*str
== *pattern
) {
2016 while (*pattern
== wxT('*'))
2018 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2024 #pragma warning(default:4706) // assignment within conditional expression