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>
70 #include "wx/os2/private.h"
73 #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
115 extern wxChar
*wxBuffer
;
117 #if defined(__WXMAC__) && !defined(__UNIX__)
118 #include "morefile.h"
119 #include "moreextr.h"
120 #include "fullpath.h"
121 #include "fspcompa.h"
124 IMPLEMENT_DYNAMIC_CLASS(wxPathList
, wxStringList
)
126 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 static wxChar wxFileFunctionsBuffer
[4*_MAXPATHLEN
];
132 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
134 // VisualAge C++ V4.0 cannot have any external linkage const decs
135 // in headers included by more than one primary source
137 const off_t wxInvalidOffset
= (off_t
)-1;
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
144 // we need to translate Mac filenames before passing them to OS functions
145 #define OS_FILENAME(s) (s.fn_str())
147 // ============================================================================
149 // ============================================================================
151 void wxPathList::Add (const wxString
& path
)
153 wxStringList::Add (WXSTRINGCAST path
);
156 // Add paths e.g. from the PATH environment variable
157 void wxPathList::AddEnvList (const wxString
& envVariable
)
159 static const wxChar PATH_TOKS
[] =
161 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
166 wxChar
*val
= wxGetenv (WXSTRINGCAST envVariable
);
169 wxChar
*s
= copystring (val
);
170 wxChar
*save_ptr
, *token
= wxStrtok (s
, PATH_TOKS
, &save_ptr
);
174 Add (copystring (token
));
177 if ((token
= wxStrtok ((wxChar
*) NULL
, PATH_TOKS
, &save_ptr
)) != NULL
)
178 Add (wxString(token
));
182 // suppress warning about unused variable save_ptr when wxStrtok() is a
183 // macro which throws away its third argument
190 // Given a full filename (with path), ensure that that file can
191 // be accessed again USING FILENAME ONLY by adding the path
192 // to the list if not already there.
193 void wxPathList::EnsureFileAccessible (const wxString
& path
)
195 wxString
path_only(wxPathOnly(path
));
196 if ( !path_only
.IsEmpty() )
198 if ( !Member(path_only
) )
203 bool wxPathList::Member (const wxString
& path
)
205 for (wxNode
* node
= First (); node
!= NULL
; node
= node
->Next ())
207 wxString
path2((wxChar
*) node
->Data ());
209 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
211 path
.CompareTo (path2
, wxString::ignoreCase
) == 0
213 // Case sensitive File System
214 path
.CompareTo (path2
) == 0
222 wxString
wxPathList::FindValidPath (const wxString
& file
)
224 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer
, file
)))
225 return wxString(wxFileFunctionsBuffer
);
227 wxChar buf
[_MAXPATHLEN
];
228 wxStrcpy(buf
, wxFileFunctionsBuffer
);
230 wxChar
*filename
= (wxChar
*) NULL
; /* shut up buggy egcs warning */
231 filename
= IsAbsolutePath (buf
) ? wxFileNameFromPath (buf
) : (wxChar
*)buf
;
233 for (wxNode
* node
= First (); node
; node
= node
->Next ())
235 wxChar
*path
= (wxChar
*) node
->Data ();
236 wxStrcpy (wxFileFunctionsBuffer
, path
);
237 wxChar ch
= wxFileFunctionsBuffer
[wxStrlen(wxFileFunctionsBuffer
)-1];
238 if (ch
!= wxT('\\') && ch
!= wxT('/'))
239 wxStrcat (wxFileFunctionsBuffer
, wxT("/"));
240 wxStrcat (wxFileFunctionsBuffer
, filename
);
242 Unix2DosFilename (wxFileFunctionsBuffer
);
244 if (wxFileExists (wxFileFunctionsBuffer
))
246 return wxString(wxFileFunctionsBuffer
); // Found!
250 return wxString(wxT("")); // Not found
253 wxString
wxPathList::FindAbsoluteValidPath (const wxString
& file
)
255 wxString f
= FindValidPath(file
);
256 if ( wxIsAbsolutePath(f
) )
260 wxGetWorkingDirectory(buf
.GetWriteBuf(_MAXPATHLEN
), _MAXPATHLEN
- 1);
262 if ( !wxEndsWithPathSeparator(buf
) )
264 buf
+= wxFILE_SEP_PATH
;
272 wxFileExists (const wxString
& filename
)
274 #ifdef __GNUWIN32__ // (fix a B20 bug)
275 return GetFileAttributes(filename
) != 0xFFFFFFFF;
278 if ( !filename
.empty() && wxStat (OS_FILENAME(filename
), &stbuf
) == 0 )
286 wxIsAbsolutePath (const wxString
& filename
)
289 if (filename
!= wxT(""))
291 if( filename
.Find(':') != wxNOT_FOUND
&& filename
[0] != ':' )
296 if (filename
!= wxT(""))
298 if (filename
[0] == wxT('/')
300 || (filename
[0] == wxT('[') && filename
[1] != wxT('.'))
304 || filename
[0] == wxT('\\') || (wxIsalpha (filename
[0]) && filename
[1] == wxT(':'))
314 * Strip off any extension (dot something) from end of file,
315 * IF one exists. Inserts zero into buffer.
319 void wxStripExtension(wxChar
*buffer
)
321 int len
= wxStrlen(buffer
);
325 if (buffer
[i
] == wxT('.'))
334 void wxStripExtension(wxString
& buffer
)
336 size_t len
= buffer
.Length();
340 if (buffer
.GetChar(i
) == wxT('.'))
342 buffer
= buffer
.Left(i
);
349 // Destructive removal of /./ and /../ stuff
350 wxChar
*wxRealPath (wxChar
*path
)
353 static const wxChar SEP
= wxT('\\');
354 Unix2DosFilename(path
);
356 static const wxChar SEP
= wxT('/');
358 if (path
[0] && path
[1]) {
359 /* MATTHEW: special case "/./x" */
361 if (path
[2] == SEP
&& path
[1] == wxT('.'))
369 if (p
[1] == wxT('.') && p
[2] == wxT('.') && (p
[3] == SEP
|| p
[3] == wxT('\0')))
372 for (q
= p
- 1; q
>= path
&& *q
!= SEP
; q
--);
373 if (q
[0] == SEP
&& (q
[1] != wxT('.') || q
[2] != wxT('.') || q
[3] != SEP
)
374 && (q
- 1 <= path
|| q
[-1] != SEP
))
377 if (path
[0] == wxT('\0'))
383 /* Check that path[2] is NULL! */
384 else if (path
[1] == wxT(':') && !path
[2])
393 else if (p
[1] == wxT('.') && (p
[2] == SEP
|| p
[2] == wxT('\0')))
402 wxChar
*wxCopyAbsolutePath(const wxString
& filename
)
404 if (filename
== wxT(""))
405 return (wxChar
*) NULL
;
407 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer
, filename
))) {
408 wxChar buf
[_MAXPATHLEN
];
410 wxGetWorkingDirectory(buf
, WXSIZEOF(buf
));
411 wxChar ch
= buf
[wxStrlen(buf
) - 1];
413 if (ch
!= wxT('\\') && ch
!= wxT('/'))
414 wxStrcat(buf
, wxT("\\"));
417 wxStrcat(buf
, wxT("/"));
419 wxStrcat(buf
, wxFileFunctionsBuffer
);
420 return copystring( wxRealPath(buf
) );
422 return copystring( wxFileFunctionsBuffer
);
428 ~user/ => user's home dir
429 If the environment variable a = "foo" and b = "bar" then:
446 /* input name in name, pathname output to buf. */
448 wxChar
*wxExpandPath(wxChar
*buf
, const wxChar
*name
)
450 register wxChar
*d
, *s
, *nm
;
451 wxChar lnm
[_MAXPATHLEN
];
454 // Some compilers don't like this line.
455 // const wxChar trimchars[] = wxT("\n \t");
458 trimchars
[0] = wxT('\n');
459 trimchars
[1] = wxT(' ');
460 trimchars
[2] = wxT('\t');
464 const wxChar SEP
= wxT('\\');
466 const wxChar SEP
= wxT('/');
469 if (name
== NULL
|| *name
== wxT('\0'))
471 nm
= copystring(name
); // Make a scratch copy
474 /* Skip leading whitespace and cr */
475 while (wxStrchr((wxChar
*)trimchars
, *nm
) != NULL
)
477 /* And strip off trailing whitespace and cr */
478 s
= nm
+ (q
= wxStrlen(nm
)) - 1;
479 while (q
-- && wxStrchr((wxChar
*)trimchars
, *s
) != NULL
)
487 q
= nm
[0] == wxT('\\') && nm
[1] == wxT('~');
490 /* Expand inline environment variables */
508 while ((*d
++ = *s
) != 0) {
510 if (*s
== wxT('\\')) {
511 if ((*(d
- 1) = *++s
)) {
520 if (*s
++ == wxT('$') && (*s
== wxT('{') || *s
== wxT(')')))
522 if (*s
++ == wxT('$'))
525 register wxChar
*start
= d
;
526 register int braces
= (*s
== wxT('{') || *s
== wxT('('));
527 register wxChar
*value
;
528 while ((*d
++ = *s
) != 0)
529 if (braces
? (*s
== wxT('}') || *s
== wxT(')')) : !(wxIsalnum(*s
) || *s
== wxT('_')) )
534 value
= wxGetenv(braces
? start
+ 1 : start
);
536 for ((d
= start
- 1); (*d
++ = *value
++) != 0;);
544 /* Expand ~ and ~user */
547 if (nm
[0] == wxT('~') && !q
)
550 if (nm
[1] == SEP
|| nm
[1] == 0)
552 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
553 if ((s
= WXSTRINGCAST
wxGetUserHome(wxT(""))) != NULL
) {
558 { /* ~user/filename */
559 register wxChar
*nnm
;
560 register wxChar
*home
;
561 for (s
= nm
; *s
&& *s
!= SEP
; s
++);
562 int was_sep
; /* MATTHEW: Was there a separator, or NULL? */
563 was_sep
= (*s
== SEP
);
564 nnm
= *s
? s
+ 1 : s
;
566 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
567 if ((home
= WXSTRINGCAST
wxGetUserHome(wxString(nm
+ 1))) == NULL
) {
568 if (was_sep
) /* replace only if it was there: */
579 if (s
&& *s
) { /* MATTHEW: s could be NULL if user '~' didn't exist */
581 while (wxT('\0') != (*d
++ = *s
++))
584 if (d
- 1 > buf
&& *(d
- 2) != SEP
)
588 while ((*d
++ = *s
++) != 0);
589 delete[] nm_tmp
; // clean up alloc
590 /* Now clean up the buffer */
591 return wxRealPath(buf
);
594 /* Contract Paths to be build upon an environment variable
597 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
599 The call wxExpandPath can convert these back!
602 wxContractPath (const wxString
& filename
, const wxString
& envname
, const wxString
& user
)
604 static wxChar dest
[_MAXPATHLEN
];
606 if (filename
== wxT(""))
607 return (wxChar
*) NULL
;
609 wxStrcpy (dest
, WXSTRINGCAST filename
);
611 Unix2DosFilename(dest
);
614 // Handle environment
615 const wxChar
*val
= (const wxChar
*) NULL
;
616 wxChar
*tcp
= (wxChar
*) NULL
;
617 if (envname
!= WXSTRINGCAST NULL
&& (val
= wxGetenv (WXSTRINGCAST envname
)) != NULL
&&
618 (tcp
= wxStrstr (dest
, val
)) != NULL
)
620 wxStrcpy (wxFileFunctionsBuffer
, tcp
+ wxStrlen (val
));
623 wxStrcpy (tcp
, WXSTRINGCAST envname
);
624 wxStrcat (tcp
, wxT("}"));
625 wxStrcat (tcp
, wxFileFunctionsBuffer
);
628 // Handle User's home (ignore root homes!)
630 if ((val
= wxGetUserHome (user
)) != NULL
&&
631 (len
= wxStrlen(val
)) > 2 &&
632 wxStrncmp(dest
, val
, len
) == 0)
634 wxStrcpy(wxFileFunctionsBuffer
, wxT("~"));
636 wxStrcat(wxFileFunctionsBuffer
, (const wxChar
*) user
);
638 // strcat(wxFileFunctionsBuffer, "\\");
640 // strcat(wxFileFunctionsBuffer, "/");
642 wxStrcat(wxFileFunctionsBuffer
, dest
+ len
);
643 wxStrcpy (dest
, wxFileFunctionsBuffer
);
649 // Return just the filename, not the path
651 wxChar
*wxFileNameFromPath (wxChar
*path
)
655 register wxChar
*tcp
;
657 tcp
= path
+ wxStrlen (path
);
658 while (--tcp
>= path
)
661 if (*tcp
== wxT(':') )
663 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
665 || *tcp
== wxT(':') || *tcp
== wxT(']'))
672 #if defined(__WXMSW__) || defined(__WXPM__)
673 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
680 wxString
wxFileNameFromPath (const wxString
& path1
)
682 if (path1
!= wxT(""))
685 wxChar
*path
= WXSTRINGCAST path1
;
686 register wxChar
*tcp
;
688 tcp
= path
+ wxStrlen (path
);
689 while (--tcp
>= path
)
692 if (*tcp
== wxT(':') )
694 if (*tcp
== wxT('/') || *tcp
== wxT('\\')
696 || *tcp
== wxT(':') || *tcp
== wxT(']'))
701 return wxString(tcp
+ 1);
703 #if defined(__WXMSW__) || defined(__WXPM__)
704 if (wxIsalpha (*path
) && *(path
+ 1) == wxT(':'))
705 return wxString(path
+ 2);
708 // Yes, this should return the path, not an empty string, otherwise
709 // we get "thing.txt" -> "".
713 // Return just the directory, or NULL if no directory
715 wxPathOnly (wxChar
*path
)
719 static wxChar buf
[_MAXPATHLEN
];
722 wxStrcpy (buf
, path
);
724 int l
= wxStrlen(path
);
729 // Search backward for a backward or forward slash
730 while (!done
&& i
> -1)
734 if (path
[i
] == wxT(':') )
736 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
741 if ( path
[i
] == wxT(']') )
752 #if defined(__WXMSW__) || defined(__WXPM__)
753 // Try Drive specifier
754 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
756 // A:junk --> A:. (since A:.\junk Not A:\junk)
764 return (wxChar
*) NULL
;
767 // Return just the directory, or NULL if no directory
768 wxString
wxPathOnly (const wxString
& path
)
772 wxChar buf
[_MAXPATHLEN
];
775 wxStrcpy (buf
, WXSTRINGCAST path
);
777 int l
= path
.Length();
782 // Search backward for a backward or forward slash
783 while (!done
&& i
> -1)
787 if (path
[i
] == wxT(':') )
789 if (path
[i
] == wxT('/') || path
[i
] == wxT('\\') || path
[i
] == wxT(']'))
794 if ( path
[i
] == wxT(']') )
800 return wxString(buf
);
805 #if defined(__WXMSW__) || defined(__WXPM__)
806 // Try Drive specifier
807 if (wxIsalpha (buf
[0]) && buf
[1] == wxT(':'))
809 // A:junk --> A:. (since A:.\junk Not A:\junk)
812 return wxString(buf
);
817 return wxString(wxT(""));
820 // Utility for converting delimiters in DOS filenames to UNIX style
821 // and back again - or we get nasty problems with delimiters.
822 // Also, convert to lower case, since case is significant in UNIX.
824 #if defined(__WXMAC__) && !defined(__UNIX__)
825 wxString
wxMacFSSpec2MacFilename( const FSSpec
*spec
)
830 FSpGetFullPath( spec
, &length
, &myPath
) ;
831 ::SetHandleSize( myPath
, length
+ 1 ) ;
833 (*myPath
)[length
] = 0 ;
834 if ( length
> 0 && (*myPath
)[length
-1] ==':' )
835 (*myPath
)[length
-1] = 0 ;
837 wxString
result( (char*) *myPath
) ;
838 ::HUnlock( myPath
) ;
839 ::DisposeHandle( myPath
) ;
843 void wxMacFilename2FSSpec( const char *path
, FSSpec
*spec
)
845 FSpLocationFromFullPath( strlen(path
) , path
, spec
) ;
849 static char sMacFileNameConversion[ 1000 ] ;
851 wxString wxMac2UnixFilename (const char *str)
853 char *s = sMacFileNameConversion ;
857 memmove( s+1 , s ,strlen( s ) + 1) ;
868 *s = wxTolower (*s); // Case INDEPENDENT
872 return wxString (sMacFileNameConversion) ;
875 wxString wxUnix2MacFilename (const char *str)
877 char *s = sMacFileNameConversion ;
883 // relative path , since it goes on with slash which is translated to a :
884 memmove( s , s+1 ,strlen( s ) ) ;
886 else if ( *s == '/' )
888 // absolute path -> on mac just start with the drive name
889 memmove( s , s+1 ,strlen( s ) ) ;
893 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
897 if (*s == '/' || *s == '\\')
899 // convert any back-directory situations
900 if ( *(s+1) == '.' && *(s+2) == '.' && ( (*(s+3) == '/' || *(s+3) == '\\') ) )
903 memmove( s+1 , s+3 ,strlen( s+3 ) + 1 ) ;
912 return wxString (sMacFileNameConversion) ;
915 wxString wxMacFSSpec2UnixFilename( const FSSpec *spec )
917 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec) ) ;
920 void wxMacFilename2FSSpec( const char *path , FSSpec *spec )
922 FSpLocationFromFullPath( strlen(path ) , path , spec ) ;
925 void wxUnixFilename2FSSpec( const char *path , FSSpec *spec )
927 wxString var = wxUnix2MacFilename( path ) ;
928 wxMacFilename2FSSpec( var , spec ) ;
933 wxDos2UnixFilename (char *s
)
942 *s
= wxTolower (*s
); // Case INDEPENDENT
949 #if defined(__WXMSW__) || defined(__WXPM__)
950 wxUnix2DosFilename (wxChar
*s
)
952 wxUnix2DosFilename (wxChar
*WXUNUSED(s
) )
955 // Yes, I really mean this to happen under DOS only! JACS
956 #if defined(__WXMSW__) || defined(__WXPM__)
967 // Concatenate two files to form third
969 wxConcatFiles (const wxString
& file1
, const wxString
& file2
, const wxString
& file3
)
972 if ( !wxGetTempFileName("cat", outfile
) )
975 FILE *fp1
= (FILE *) NULL
;
976 FILE *fp2
= (FILE *) NULL
;
977 FILE *fp3
= (FILE *) NULL
;
978 // Open the inputs and outputs
979 if ((fp1
= wxFopen (OS_FILENAME( file1
), wxT("rb"))) == NULL
||
980 (fp2
= wxFopen (OS_FILENAME( file2
), wxT("rb"))) == NULL
||
981 (fp3
= wxFopen (OS_FILENAME( outfile
), wxT("wb"))) == NULL
)
993 while ((ch
= getc (fp1
)) != EOF
)
994 (void) putc (ch
, fp3
);
997 while ((ch
= getc (fp2
)) != EOF
)
998 (void) putc (ch
, fp3
);
1002 bool result
= wxRenameFile(outfile
, file3
);
1008 wxCopyFile (const wxString
& file1
, const wxString
& file2
, bool overwrite
)
1010 #if defined(__WIN32__)
1011 // CopyFile() copies file attributes and modification time too, so use it
1012 // instead of our code if available
1014 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1015 return ::CopyFile(file1
, file2
, !overwrite
) != 0;
1019 // get permissions of file1
1020 if ( wxStat(OS_FILENAME(file1
), &fbuf
) != 0 )
1022 // the file probably doesn't exist or we haven't the rights to read
1024 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1029 // open file1 for reading
1030 wxFile
fileIn(file1
, wxFile::read
);
1031 if ( !fileIn
.IsOpened() )
1034 // remove file2, if it exists. This is needed for creating
1035 // file2 with the correct permissions in the next step
1036 if ( wxFileExists(file2
) && (!overwrite
|| !wxRemoveFile(file2
)))
1038 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1044 // reset the umask as we want to create the file with exactly the same
1045 // permissions as the original one
1046 mode_t oldUmask
= umask( 0 );
1049 // create file2 with the same permissions than file1 and open it for
1052 if ( !fileOut
.Create(file2
, overwrite
, fbuf
.st_mode
& 0777) )
1056 /// restore the old umask
1060 // copy contents of file1 to file2
1065 count
= fileIn
.Read(buf
, WXSIZEOF(buf
));
1066 if ( fileIn
.Error() )
1073 if ( fileOut
.Write(buf
, count
) < count
)
1077 // we can expect fileIn to be closed successfully, but we should ensure
1078 // that fileOut was closed as some write errors (disk full) might not be
1079 // detected before doing this
1080 if ( !fileIn
.Close() || !fileOut
.Close() )
1083 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1084 // no chmod in VA. Should be some permission API for HPFS386 partitions
1086 if ( chmod(OS_FILENAME(file2
), fbuf
.st_mode
) != 0 )
1088 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1092 #endif // OS/2 || Mac
1095 #endif // __WXMSW__ && __WIN32__
1099 wxRenameFile (const wxString
& file1
, const wxString
& file2
)
1101 // Normal system call
1102 if ( wxRename (file1
, file2
) == 0 )
1106 if (wxCopyFile(file1
, file2
)) {
1107 wxRemoveFile(file1
);
1114 bool wxRemoveFile(const wxString
& file
)
1116 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1117 int res
= wxRemove(file
);
1119 int res
= unlink(OS_FILENAME(file
));
1125 bool wxMkdir(const wxString
& dir
, int perm
)
1127 #if defined(__WXMAC__) && !defined(__UNIX__)
1128 return (mkdir( dir
, 0 ) == 0);
1130 const wxChar
*dirname
= dir
.c_str();
1132 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1133 // for the GNU compiler
1134 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1135 if ( mkdir(wxFNCONV(dirname
), perm
) != 0 )
1136 #elif defined(__WXPM__)
1137 if (::DosCreateDir((PSZ
)dirname
, NULL
) != 0) // enhance for EAB's??
1138 #else // !MSW and !OS/2 VAC++
1140 if ( wxMkDir(wxFNSTRINGCAST
wxFNCONV(dirname
)) != 0 )
1143 wxLogSysError(_("Directory '%s' couldn't be created"), dirname
);
1152 bool wxRmdir(const wxString
& dir
, int WXUNUSED(flags
))
1155 return FALSE
; //to be changed since rmdir exists in VMS7.x
1156 #elif defined(__WXPM__)
1157 return (::DosDeleteDir((PSZ
)dir
.c_str()) == 0);
1161 return FALSE
; // What to do?
1163 return (wxRmDir(OS_FILENAME(dir
)) == 0);
1169 // does the path exists? (may have or not '/' or '\\' at the end)
1170 bool wxPathExists(const wxChar
*pszPathName
)
1172 wxString
strPath(pszPathName
);
1174 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1175 // so remove all trailing backslashes from the path - but don't do this for
1176 // the pathes "d:\" (which are different from "d:") nor for just "\"
1177 while ( wxEndsWithPathSeparator(strPath
) )
1179 size_t len
= strPath
.length();
1180 if ( len
== 1 || strPath
[len
- 1] == _T(':') )
1183 strPath
.Truncate(len
- 1);
1185 #endif // __WINDOWS__
1188 #ifndef __VISAGECPP__
1189 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1190 ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
1192 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1193 return wxStat(wxFNSTRINGCAST strPath
.fn_str(), &st
) == 0 &&
1194 (st
.st_mode
== S_IFDIR
);
1199 // Get a temporary filename, opening and closing the file.
1200 wxChar
*wxGetTempFileName(const wxString
& prefix
, wxChar
*buf
)
1206 ::GetTempFileName(0, WXSTRINGCAST prefix
, 0, tmp
);
1208 wxChar tmp
[MAX_PATH
];
1209 wxChar tmpPath
[MAX_PATH
];
1210 ::GetTempPath(MAX_PATH
, tmpPath
);
1211 ::GetTempFileName(tmpPath
, WXSTRINGCAST prefix
, 0, tmp
);
1213 if (buf
) wxStrcpy(buf
, tmp
);
1214 else buf
= copystring(tmp
);
1218 static short last_temp
= 0; // cache last to speed things a bit
1219 // At most 1000 temp files to a process! We use a ring count.
1220 wxChar tmp
[100]; // FIXME static buffer
1222 for (short suffix
= last_temp
+ 1; suffix
!= last_temp
; ++suffix
%= 1000)
1224 wxSprintf (tmp
, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix
, (int) getpid (), (int) suffix
);
1225 if (!wxFileExists( tmp
))
1227 // Touch the file to create it (reserve name)
1228 FILE *fd
= fopen (wxFNCONV(tmp
), "w");
1233 wxStrcpy( buf
, tmp
);
1235 buf
= copystring( tmp
);
1239 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1240 if (buf
) buf
[0] = 0;
1241 return (wxChar
*) NULL
;
1245 bool wxGetTempFileName(const wxString
& prefix
, wxString
& buf
)
1248 if (wxGetTempFileName(prefix
, buf2
) != (wxChar
*) NULL
)
1257 // Get first file name matching given wild card.
1261 // Get first file name matching given wild card.
1262 // Flags are reserved for future use.
1264 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1265 static DIR *gs_dirStream
= (DIR *) NULL
;
1266 static wxString gs_strFileSpec
;
1267 static int gs_findFlags
= 0;
1270 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1274 wxChar
*specvms
= NULL
;
1277 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1279 closedir(gs_dirStream
); // edz 941103: better housekeping
1281 gs_findFlags
= flags
;
1283 gs_strFileSpec
= spec
;
1285 // Find path only so we can concatenate
1286 // found file onto path
1287 wxString
path(wxPathOnly(gs_strFileSpec
));
1289 // special case: path is really "/"
1290 if ( !path
&& gs_strFileSpec
[0u] == wxT('/') )
1293 wxStrcpy( specvms
, wxT( "[000000]" ) );
1294 gs_strFileSpec
= specvms
;
1295 wxString
path_vms(wxPathOnly(gs_strFileSpec
));
1301 // path is empty => Local directory
1305 wxStrcpy( specvms
, wxT( "[]" ) );
1306 gs_strFileSpec
= specvms
;
1307 wxString
path_vms1(wxPathOnly(gs_strFileSpec
));
1314 gs_dirStream
= opendir(path
.fn_str());
1315 if ( !gs_dirStream
)
1317 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1322 result
= wxFindNextFile();
1324 #endif // !VMS6.x or earlier
1329 wxString
wxFindNextFile()
1333 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1334 wxCHECK_MSG( gs_dirStream
, result
, wxT("must call wxFindFirstFile first") );
1336 // Find path only so we can concatenate
1337 // found file onto path
1338 wxString
path(wxPathOnly(gs_strFileSpec
));
1339 wxString
name(wxFileNameFromPath(gs_strFileSpec
));
1341 /* MATTHEW: special case: path is really "/" */
1342 if ( !path
&& gs_strFileSpec
[0u] == wxT('/'))
1346 struct dirent
*nextDir
;
1347 for ( nextDir
= readdir(gs_dirStream
);
1349 nextDir
= readdir(gs_dirStream
) )
1351 if (wxMatchWild(name
, nextDir
->d_name
, FALSE
) && // RR: added FALSE to find hidden files
1352 strcmp(nextDir
->d_name
, ".") &&
1353 strcmp(nextDir
->d_name
, "..") )
1356 if ( !path
.IsEmpty() )
1359 if ( path
!= wxT('/') )
1363 result
+= nextDir
->d_name
;
1365 // Only return "." and ".." when they match
1367 if ( (strcmp(nextDir
->d_name
, ".") == 0) ||
1368 (strcmp(nextDir
->d_name
, "..") == 0))
1370 if ( (gs_findFlags
& wxDIR
) != 0 )
1376 isdir
= wxDirExists(result
);
1378 // and only return directories when flags & wxDIR
1379 if ( !gs_findFlags
||
1380 ((gs_findFlags
& wxDIR
) && isdir
) ||
1381 ((gs_findFlags
& wxFILE
) && !isdir
) )
1388 result
.Empty(); // not found
1390 closedir(gs_dirStream
);
1391 gs_dirStream
= (DIR *) NULL
;
1392 #endif // !VMS6.2 or earlier
1397 #elif defined(__WXMAC__)
1399 struct MacDirectoryIterator
1407 static int g_iter_flags
;
1409 static MacDirectoryIterator g_iter
;
1411 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1415 g_iter_flags
= flags
; /* MATTHEW: [5] Remember flags */
1417 // Find path only so we can concatenate found file onto path
1418 wxString
path(wxPathOnly(spec
));
1419 if ( !path
.IsEmpty() )
1420 result
<< path
<< wxT('\\');
1424 wxMacFilename2FSSpec( result
, &fsspec
) ;
1425 g_iter
.m_CPB
.hFileInfo
.ioVRefNum
= fsspec
.vRefNum
;
1426 g_iter
.m_CPB
.hFileInfo
.ioNamePtr
= g_iter
.m_name
;
1427 g_iter
.m_index
= 0 ;
1430 FSpGetDirectoryID( &fsspec
, &g_iter
.m_dirId
, &isDir
) ;
1432 return wxEmptyString
;
1434 return wxFindNextFile( ) ;
1437 wxString
wxFindNextFile()
1443 while ( err
== noErr
)
1446 g_iter
.m_CPB
.dirInfo
.ioFDirIndex
= g_iter
.m_index
;
1447 g_iter
.m_CPB
.dirInfo
.ioDrDirID
= g_iter
.m_dirId
; /* we need to do this every time */
1448 err
= PBGetCatInfoSync((CInfoPBPtr
)&g_iter
.m_CPB
);
1452 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) != 0 && (g_iter_flags
& wxDIR
) ) // we have a directory
1455 if ( ( g_iter
.m_CPB
.dirInfo
.ioFlAttrib
& ioDirMask
) == 0 && !(g_iter_flags
& wxFILE
) )
1463 return wxEmptyString
;
1467 FSMakeFSSpecCompat(g_iter
.m_CPB
.hFileInfo
.ioVRefNum
,
1472 return wxMacFSSpec2MacFilename( &spec
) ;
1475 #elif defined(__WXMSW__)
1478 static HANDLE gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1479 static WIN32_FIND_DATA gs_findDataStruct
;
1482 static struct ffblk gs_findDataStruct
;
1484 static struct _find_t gs_findDataStruct
;
1488 static wxString gs_strFileSpec
;
1489 static int gs_findFlags
= 0;
1491 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1495 gs_strFileSpec
= spec
;
1496 gs_findFlags
= flags
; /* MATTHEW: [5] Remember flags */
1498 // Find path only so we can concatenate found file onto path
1499 wxString
path(wxPathOnly(gs_strFileSpec
));
1500 if ( !path
.IsEmpty() )
1501 result
<< path
<< wxT('\\');
1504 if ( gs_hFileStruct
!= INVALID_HANDLE_VALUE
)
1505 FindClose(gs_hFileStruct
);
1507 gs_hFileStruct
= ::FindFirstFile(WXSTRINGCAST spec
, &gs_findDataStruct
);
1509 if ( gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1516 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1518 if (isdir
&& !(flags
& wxDIR
))
1519 return wxFindNextFile();
1520 else if (!isdir
&& flags
&& !(flags
& wxFILE
))
1521 return wxFindNextFile();
1523 result
+= gs_findDataStruct
.cFileName
;
1527 int flag
= _A_NORMAL
;
1532 if (findfirst(WXSTRINGCAST spec
, &gs_findDataStruct
, flag
) == 0)
1534 if (_dos_findfirst(WXSTRINGCAST spec
, flag
, &gs_findDataStruct
) == 0)
1540 attrib
= gs_findDataStruct
.ff_attrib
;
1542 attrib
= gs_findDataStruct
.attrib
;
1545 if (attrib
& _A_SUBDIR
) {
1546 if (!(gs_findFlags
& wxDIR
))
1547 return wxFindNextFile();
1548 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1549 return wxFindNextFile();
1553 gs_findDataStruct
.ff_name
1555 gs_findDataStruct
.name
1565 wxString
wxFindNextFile()
1569 // Find path only so we can concatenate found file onto path
1570 wxString
path(wxPathOnly(gs_strFileSpec
));
1575 if (gs_hFileStruct
== INVALID_HANDLE_VALUE
)
1578 bool success
= (FindNextFile(gs_hFileStruct
, &gs_findDataStruct
) != 0);
1581 FindClose(gs_hFileStruct
);
1582 gs_hFileStruct
= INVALID_HANDLE_VALUE
;
1586 bool isdir
= !!(gs_findDataStruct
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
1588 if (isdir
&& !(gs_findFlags
& wxDIR
))
1590 else if (!isdir
&& gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1593 if ( !path
.IsEmpty() )
1594 result
<< path
<< wxT('\\');
1595 result
<< gs_findDataStruct
.cFileName
;
1602 if (findnext(&gs_findDataStruct
) == 0)
1604 if (_dos_findnext(&gs_findDataStruct
) == 0)
1607 /* MATTHEW: [5] Check directory flag */
1611 attrib
= gs_findDataStruct
.ff_attrib
;
1613 attrib
= gs_findDataStruct
.attrib
;
1616 if (attrib
& _A_SUBDIR
) {
1617 if (!(gs_findFlags
& wxDIR
))
1619 } else if (gs_findFlags
&& !(gs_findFlags
& wxFILE
))
1625 gs_findDataStruct
.ff_name
1627 gs_findDataStruct
.name
1636 #elif defined(__WXPM__)
1638 wxString
wxFindFirstFile(const wxChar
*spec
, int flags
)
1643 // TODO: figure something out here for OS/2
1644 gs_strFileSpec = spec;
1645 gs_findFlags = flags;
1647 // Find path only so we can concatenate found file onto path
1648 wxString path(wxPathOnly(gs_strFileSpec));
1649 if ( !path.IsEmpty() )
1650 result << path << wxT('\\');
1652 int flag = _A_NORMAL;
1656 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1659 attrib = gs_findDataStruct.attrib;
1661 if (attrib & _A_SUBDIR) {
1662 if (!(gs_findFlags & wxDIR))
1663 return wxFindNextFile();
1664 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1665 return wxFindNextFile();
1667 result += gs_findDataStruct.name;
1673 wxString
wxFindNextFile()
1680 #endif // Unix/Windows/OS/2
1682 // Get current working directory.
1683 // If buf is NULL, allocates space using new, else
1685 wxChar
*wxGetWorkingDirectory(wxChar
*buf
, int sz
)
1688 buf
= new wxChar
[sz
+1];
1690 char *cbuf
= new char[sz
+1];
1692 if (_getcwd(cbuf
, sz
) == NULL
) {
1693 #elif defined(__WXMAC__) && !defined(__UNIX__)
1696 SFSaveDisk
= 0x214, CurDirStore
= 0x398
1700 FSMakeFSSpec( - *(short *) SFSaveDisk
, *(long *) CurDirStore
, NULL
, &cwdSpec
) ;
1701 wxString res
= wxMacFSSpec2UnixFilename( &cwdSpec
) ;
1702 strcpy( buf
, res
) ;
1705 if (getcwd(cbuf
, sz
) == NULL
) {
1710 if (_getcwd(buf
, sz
) == NULL
) {
1711 #elif defined(__WXMAC__) && !defined(__UNIX__)
1716 pb
.ioNamePtr
= (StringPtr
) &fileName
;
1718 pb
.ioRefNum
= LMGetCurApRefNum();
1720 error
= PBGetFCBInfoSync(&pb
);
1721 if ( error
== noErr
)
1723 cwdSpec
.vRefNum
= pb
.ioFCBVRefNum
;
1724 cwdSpec
.parID
= pb
.ioFCBParID
;
1725 cwdSpec
.name
[0] = 0 ;
1726 wxString res
= wxMacFSSpec2MacFilename( &cwdSpec
) ;
1728 strcpy( buf
, res
) ;
1729 buf
[res
.length()-1]=0 ;
1734 this version will not always give back the application directory on mac
1737 SFSaveDisk = 0x214, CurDirStore = 0x398
1741 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1742 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1743 strcpy( buf , res ) ;
1746 #elif(__VISAGECPP__)
1748 rc
= ::DosQueryCurrentDir( 0 // current drive
1754 if (getcwd(buf
, sz
) == NULL
) {
1762 wxConvFile
.MB2WC(buf
, cbuf
, sz
);
1771 static const size_t maxPathLen
= 1024;
1774 wxGetWorkingDirectory(str
.GetWriteBuf(maxPathLen
), maxPathLen
);
1775 str
.UngetWriteBuf();
1780 bool wxSetWorkingDirectory(const wxString
& d
)
1782 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1783 return (chdir(wxFNSTRINGCAST d
.fn_str()) == 0);
1784 #elif defined(__WXPM__)
1785 return (::DosSetCurrentDir((PSZ
)d
.c_str()) == 0);
1786 #elif defined(__WINDOWS__)
1789 return (bool)(SetCurrentDirectory(d
) != 0);
1791 // Must change drive, too.
1792 bool isDriveSpec
= ((strlen(d
) > 1) && (d
[1] == ':'));
1795 wxChar firstChar
= d
[0];
1799 firstChar
= firstChar
- 32;
1801 // To a drive number
1802 unsigned int driveNo
= firstChar
- 64;
1805 unsigned int noDrives
;
1806 _dos_setdrive(driveNo
, &noDrives
);
1809 bool success
= (chdir(WXSTRINGCAST d
) == 0);
1817 // Get the OS directory if appropriate (such as the Windows directory).
1818 // On non-Windows platform, probably just return the empty string.
1819 wxString
wxGetOSDirectory()
1823 GetWindowsDirectory(buf
, 256);
1824 return wxString(buf
);
1826 return wxEmptyString
;
1830 bool wxEndsWithPathSeparator(const wxChar
*pszFileName
)
1832 size_t len
= wxStrlen(pszFileName
);
1836 return wxIsPathSeparator(pszFileName
[len
- 1]);
1839 // find a file in a list of directories, returns false if not found
1840 bool wxFindFileInPath(wxString
*pStr
, const wxChar
*pszPath
, const wxChar
*pszFile
)
1842 // we assume that it's not empty
1843 wxCHECK_MSG( !wxIsEmpty(pszFile
), FALSE
,
1844 _T("empty file name in wxFindFileInPath"));
1846 // skip path separator in the beginning of the file name if present
1847 if ( wxIsPathSeparator(*pszFile
) )
1850 // copy the path (strtok will modify it)
1851 wxChar
*szPath
= new wxChar
[wxStrlen(pszPath
) + 1];
1852 wxStrcpy(szPath
, pszPath
);
1855 wxChar
*pc
, *save_ptr
;
1856 for ( pc
= wxStrtok(szPath
, wxPATH_SEP
, &save_ptr
);
1858 pc
= wxStrtok((wxChar
*) NULL
, wxPATH_SEP
, &save_ptr
) )
1860 // search for the file in this directory
1862 if ( !wxEndsWithPathSeparator(pc
) )
1863 strFile
+= wxFILE_SEP_PATH
;
1866 if ( FileExists(strFile
) ) {
1872 // suppress warning about unused variable save_ptr when wxStrtok() is a
1873 // macro which throws away its third argument
1878 return pc
!= NULL
; // if true => we breaked from the loop
1881 void WXDLLEXPORT
wxSplitPath(const wxChar
*pszFileName
,
1886 // it can be empty, but it shouldn't be NULL
1887 wxCHECK_RET( pszFileName
, wxT("NULL file name in wxSplitPath") );
1889 wxFileName::SplitPath(pszFileName
, pstrPath
, pstrName
, pstrExt
);
1892 time_t WXDLLEXPORT
wxFileModificationTime(const wxString
& filename
)
1896 wxStat(filename
.fn_str(), &buf
);
1897 return buf
.st_mtime
;
1901 //------------------------------------------------------------------------
1902 // wild character routines
1903 //------------------------------------------------------------------------
1905 bool wxIsWild( const wxString
& pattern
)
1907 wxString tmp
= pattern
;
1908 wxChar
*pat
= WXSTRINGCAST(tmp
);
1911 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1921 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1923 #if defined(HAVE_FNMATCH_H)
1925 // this probably won't work well for multibyte chars in Unicode mode?
1927 return fnmatch(pat
.fn_str(), text
.fn_str(), FNM_PERIOD
) == 0;
1929 return fnmatch(pat
.fn_str(), text
.fn_str(), 0) == 0;
1933 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1936 * WARNING: this code is broken!
1939 wxString tmp1
= pat
;
1940 wxChar
*pattern
= WXSTRINGCAST(tmp1
);
1941 wxString tmp2
= text
;
1942 wxChar
*str
= WXSTRINGCAST(tmp2
);
1945 bool done
= FALSE
, ret_code
, ok
;
1946 // Below is for vi fans
1947 const wxChar OB
= wxT('{'), CB
= wxT('}');
1949 // dot_special means '.' only matches '.'
1950 if (dot_special
&& *str
== wxT('.') && *pattern
!= *str
)
1953 while ((*pattern
!= wxT('\0')) && (!done
)
1954 && (((*str
==wxT('\0'))&&((*pattern
==OB
)||(*pattern
==wxT('*'))))||(*str
!=wxT('\0')))) {
1958 if (*pattern
!= wxT('\0'))
1964 while ((*str
!=wxT('\0'))
1965 && ((ret_code
=wxMatchWild(pattern
, str
++, FALSE
)) == 0))
1968 while (*str
!= wxT('\0'))
1970 while (*pattern
!= wxT('\0'))
1977 if ((*pattern
== wxT('\0')) || (*pattern
== wxT(']'))) {
1981 if (*pattern
== wxT('\\')) {
1983 if (*pattern
== wxT('\0')) {
1988 if (*(pattern
+ 1) == wxT('-')) {
1991 if (*pattern
== wxT(']')) {
1995 if (*pattern
== wxT('\\')) {
1997 if (*pattern
== wxT('\0')) {
2002 if ((*str
< c
) || (*str
> *pattern
)) {
2006 } else if (*pattern
!= *str
) {
2011 while ((*pattern
!= wxT(']')) && (*pattern
!= wxT('\0'))) {
2012 if ((*pattern
== wxT('\\')) && (*(pattern
+ 1) != wxT('\0')))
2016 if (*pattern
!= wxT('\0')) {
2026 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2029 while (ok
&& (*cp
!= wxT('\0')) && (*pattern
!= wxT('\0'))
2030 && (*pattern
!= wxT(',')) && (*pattern
!= CB
)) {
2031 if (*pattern
== wxT('\\'))
2033 ok
= (*pattern
++ == *cp
++);
2035 if (*pattern
== wxT('\0')) {
2041 while ((*pattern
!= CB
) && (*pattern
!= wxT('\0'))) {
2042 if (*++pattern
== wxT('\\')) {
2043 if (*++pattern
== CB
)
2048 while (*pattern
!=CB
&& *pattern
!=wxT(',') && *pattern
!=wxT('\0')) {
2049 if (*++pattern
== wxT('\\')) {
2050 if (*++pattern
== CB
|| *pattern
== wxT(','))
2055 if (*pattern
!= wxT('\0'))
2060 if (*str
== *pattern
) {
2067 while (*pattern
== wxT('*'))
2069 return ((*str
== wxT('\0')) && (*pattern
== wxT('\0')));
2075 #pragma warning(default:4706) // assignment within conditional expression