]> git.saurik.com Git - wxWidgets.git/blame - src/common/filefn.cpp
added wxSockAddress copy ctor which, in particular, fixes Clone() and fixed its opera...
[wxWidgets.git] / src / common / filefn.cpp
CommitLineData
c801d85f
KB
1/////////////////////////////////////////////////////////////////////////////
2// Name: filefn.cpp
3// Purpose: File- and directory-related functions
4// Author: Julian Smart
5// Modified by:
6// Created: 29/01/98
7// RCS-ID: $Id$
8// Copyright: (c) 1998 Julian Smart
3f4a0c5b 9// Licence: wxWindows license
c801d85f
KB
10/////////////////////////////////////////////////////////////////////////////
11
e90c1d2a
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
c801d85f 20#ifdef __GNUG__
7af89395 21 #pragma implementation "filefn.h"
c801d85f
KB
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26#include "wx/defs.h"
27
28#ifdef __BORLANDC__
7af89395 29 #pragma hdrstop
c801d85f
KB
30#endif
31
c801d85f 32#include "wx/utils.h"
3096bd2f 33#include "wx/intl.h"
32f31043 34#include "wx/file.h"
9e8d8607 35#include "wx/filename.h"
c801d85f 36
fd3f686c 37// there are just too many of those...
3f4a0c5b 38#ifdef __VISUALC__
fd3f686c
VZ
39 #pragma warning(disable:4706) // assignment within conditional expression
40#endif // VC++
41
c801d85f
KB
42#include <ctype.h>
43#include <stdio.h>
44#include <stdlib.h>
45#include <string.h>
46#if !defined(__WATCOMC__)
3f4a0c5b
VZ
47 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
48 #include <errno.h>
49 #endif
c801d85f 50#endif
3f4a0c5b 51
c801d85f 52#include <time.h>
3f4a0c5b 53
469e1e5c 54#ifndef __MWERKS__
7af89395
VZ
55 #include <sys/types.h>
56 #include <sys/stat.h>
469e1e5c 57#else
7af89395
VZ
58 #include <stat.h>
59 #include <unistd.h>
5b781a67 60 #include <unix.h>
469e1e5c 61#endif
c801d85f 62
aad5220b 63#ifdef __UNIX__
7af89395
VZ
64 #include <unistd.h>
65 #include <dirent.h>
aad5220b 66#endif
c801d85f 67
f6bcfd97 68#ifdef __WXPM__
c2ff79b1 69 #include <process.h>
f6bcfd97 70 #include "wx/os2/private.h"
c2ff79b1 71#endif
34138703 72#ifdef __WINDOWS__
a3ef5bf5 73#if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
7af89395
VZ
74 #include <direct.h>
75 #include <dos.h>
32f31043 76 #include <io.h>
7af89395
VZ
77#endif // __WINDOWS__
78#endif // native Win compiler
c801d85f
KB
79
80#ifdef __GNUWIN32__
161f4f73 81 #include <wchar.h>
7af89395
VZ
82 #ifndef __TWIN32__
83 #include <sys/unistd.h>
84 #endif
c801d85f
KB
85#endif
86
87#ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
88 // this (3.1 I believe) and how to test for it.
89 // If this works for Borland 4.0 as well, then no worries.
7af89395 90 #include <dir.h>
c801d85f
KB
91#endif
92
a3ef5bf5 93#ifdef __SALFORDC__
7af89395
VZ
94 #include <dir.h>
95 #include <unix.h>
a3ef5bf5
JS
96#endif
97
dfcb1ae0 98#include "wx/setup.h"
f5abe911 99#include "wx/log.h"
99cc00ed 100
7be1f0d9
JS
101// No, Cygwin doesn't appear to have fnmatch.h after all.
102#if defined(HAVE_FNMATCH_H)
7af89395 103 #include "fnmatch.h"
dfcb1ae0
KB
104#endif
105
34138703 106#ifdef __WINDOWS__
659d096c 107 #include <windows.h>
c801d85f
KB
108#endif
109
e90c1d2a
VZ
110// ----------------------------------------------------------------------------
111// constants
112// ----------------------------------------------------------------------------
113
c801d85f
KB
114#define _MAXPATHLEN 500
115
08942a0c 116extern wxChar *wxBuffer;
e7549107 117
da2b4b7a
GD
118#ifdef __WXMAC__
119# include "MoreFiles.h"
120# include "MoreFilesExtras.h"
121# include "FullPath.h"
122# include "FSpCompat.h"
17dff81c 123#endif
c801d85f 124
a339970a 125IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
8a0a092b 126
e90c1d2a
VZ
127// ----------------------------------------------------------------------------
128// private globals
129// ----------------------------------------------------------------------------
130
131static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
132
5d33ed2c
DW
133#if defined(__VISAGECPP__) && __IBMCPP__ >= 400
134//
32e768ae 135// VisualAge C++ V4.0 cannot have any external linkage const decs
5d33ed2c
DW
136// in headers included by more than one primary source
137//
138const off_t wxInvalidOffset = (off_t)-1;
139#endif
140
a339970a
VZ
141// ----------------------------------------------------------------------------
142// macros
143// ----------------------------------------------------------------------------
144
145// we need to translate Mac filenames before passing them to OS functions
334d2448 146#define OS_FILENAME(s) (s.fn_str())
a339970a 147
e90c1d2a
VZ
148// ============================================================================
149// implementation
150// ============================================================================
151
c801d85f
KB
152void wxPathList::Add (const wxString& path)
153{
50920146 154 wxStringList::Add (WXSTRINGCAST path);
c801d85f
KB
155}
156
157// Add paths e.g. from the PATH environment variable
158void wxPathList::AddEnvList (const wxString& envVariable)
159{
50920146 160 static const wxChar PATH_TOKS[] =
34138703 161#ifdef __WINDOWS__
223d09f6 162 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
c801d85f 163#else
223d09f6 164 wxT(" :;");
c801d85f
KB
165#endif
166
50920146 167 wxChar *val = wxGetenv (WXSTRINGCAST envVariable);
c801d85f
KB
168 if (val && *val)
169 {
50920146
OK
170 wxChar *s = copystring (val);
171 wxChar *save_ptr, *token = wxStrtok (s, PATH_TOKS, &save_ptr);
c801d85f
KB
172
173 if (token)
a17e237f 174 {
3f4a0c5b
VZ
175 Add (copystring (token));
176 while (token)
a17e237f 177 {
50920146 178 if ((token = wxStrtok ((wxChar *) NULL, PATH_TOKS, &save_ptr)) != NULL)
a17e237f
VZ
179 Add (wxString(token));
180 }
181 }
182
183 // suppress warning about unused variable save_ptr when wxStrtok() is a
184 // macro which throws away its third argument
185 save_ptr = token;
186
187 delete [] s;
c801d85f
KB
188 }
189}
190
191// Given a full filename (with path), ensure that that file can
192// be accessed again USING FILENAME ONLY by adding the path
193// to the list if not already there.
194void wxPathList::EnsureFileAccessible (const wxString& path)
195{
7af89395
VZ
196 wxString path_only(wxPathOnly(path));
197 if ( !path_only.IsEmpty() )
198 {
199 if ( !Member(path_only) )
200 Add(path_only);
201 }
c801d85f
KB
202}
203
204bool wxPathList::Member (const wxString& path)
205{
206 for (wxNode * node = First (); node != NULL; node = node->Next ())
207 {
50920146 208 wxString path2((wxChar *) node->Data ());
c801d85f 209 if (
17dff81c 210#if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
c801d85f 211 // Case INDEPENDENT
3f4a0c5b 212 path.CompareTo (path2, wxString::ignoreCase) == 0
c801d85f 213#else
3f4a0c5b
VZ
214 // Case sensitive File System
215 path.CompareTo (path2) == 0
c801d85f 216#endif
3f4a0c5b
VZ
217 )
218 return TRUE;
c801d85f
KB
219 }
220 return FALSE;
221}
222
223wxString wxPathList::FindValidPath (const wxString& file)
224{
e90c1d2a
VZ
225 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer, file)))
226 return wxString(wxFileFunctionsBuffer);
c801d85f 227
50920146 228 wxChar buf[_MAXPATHLEN];
e90c1d2a 229 wxStrcpy(buf, wxFileFunctionsBuffer);
c801d85f 230
50920146
OK
231 wxChar *filename = (wxChar*) NULL; /* shut up buggy egcs warning */
232 filename = IsAbsolutePath (buf) ? wxFileNameFromPath (buf) : (wxChar *)buf;
c801d85f
KB
233
234 for (wxNode * node = First (); node; node = node->Next ())
235 {
50920146 236 wxChar *path = (wxChar *) node->Data ();
e90c1d2a
VZ
237 wxStrcpy (wxFileFunctionsBuffer, path);
238 wxChar ch = wxFileFunctionsBuffer[wxStrlen(wxFileFunctionsBuffer)-1];
223d09f6
KB
239 if (ch != wxT('\\') && ch != wxT('/'))
240 wxStrcat (wxFileFunctionsBuffer, wxT("/"));
e90c1d2a 241 wxStrcat (wxFileFunctionsBuffer, filename);
34138703 242#ifdef __WINDOWS__
e90c1d2a 243 Unix2DosFilename (wxFileFunctionsBuffer);
c801d85f 244#endif
e90c1d2a 245 if (wxFileExists (wxFileFunctionsBuffer))
c801d85f 246 {
e90c1d2a 247 return wxString(wxFileFunctionsBuffer); // Found!
c801d85f 248 }
3f4a0c5b 249 } // for()
c801d85f 250
223d09f6 251 return wxString(wxT("")); // Not found
c801d85f
KB
252}
253
254wxString wxPathList::FindAbsoluteValidPath (const wxString& file)
255{
e90c1d2a
VZ
256 wxString f = FindValidPath(file);
257 if ( wxIsAbsolutePath(f) )
258 return f;
259
260 wxString buf;
261 wxGetWorkingDirectory(buf.GetWriteBuf(_MAXPATHLEN), _MAXPATHLEN - 1);
262 buf.UngetWriteBuf();
263 if ( !wxEndsWithPathSeparator(buf) )
c801d85f 264 {
e90c1d2a 265 buf += wxFILE_SEP_PATH;
c801d85f 266 }
e90c1d2a
VZ
267 buf += f;
268
269 return buf;
c801d85f
KB
270}
271
3f4a0c5b 272bool
c801d85f
KB
273wxFileExists (const wxString& filename)
274{
4c97e024
JS
275#ifdef __WINDOWS__
276 // GetFileAttributes can copy with network paths
277 DWORD ret = GetFileAttributes(filename);
278 DWORD isDir = (ret & FILE_ATTRIBUTE_DIRECTORY);
279 return ((ret != 0xffffffff) && (isDir == 0));
6b037754 280#else
a339970a
VZ
281 wxStructStat stbuf;
282 if ( !filename.empty() && wxStat (OS_FILENAME(filename), &stbuf) == 0 )
283 return TRUE;
a3ef5bf5 284
a339970a 285 return FALSE;
6b037754 286#endif
c801d85f
KB
287}
288
3f4a0c5b 289bool
c801d85f
KB
290wxIsAbsolutePath (const wxString& filename)
291{
2985ad5d
RR
292 if (filename != wxT(""))
293 {
e8e1d09e
GD
294#if defined(__WXMAC__) && !defined(__DARWIN__)
295 // Classic or Carbon CodeWarrior like
296 // Carbon with Apple DevTools is Unix like
297
2985ad5d
RR
298 // This seems wrong to me, but there is no fix. since
299 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
300 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
2985ad5d
RR
301 if (filename.Find(':') != wxNOT_FOUND && filename[0] != ':')
302 return TRUE ;
cd378f94 303#else
e8e1d09e
GD
304 // Unix like or Windows
305 if (filename[0] == wxT('/'))
306 return TRUE;
307#endif
c801d85f 308#ifdef __VMS__
e8e1d09e
GD
309 if ((filename[0] == wxT('[') && filename[1] != wxT('.')))
310 return TRUE;
c801d85f 311#endif
34138703 312#ifdef __WINDOWS__
e8e1d09e
GD
313 // MSDOS like
314 if (filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':')))
315 return TRUE;
c801d85f 316#endif
c801d85f 317 }
e8e1d09e 318 return FALSE ;
c801d85f
KB
319}
320
321/*
322 * Strip off any extension (dot something) from end of file,
323 * IF one exists. Inserts zero into buffer.
324 *
325 */
3f4a0c5b 326
50920146 327void wxStripExtension(wxChar *buffer)
c801d85f 328{
50920146 329 int len = wxStrlen(buffer);
c801d85f
KB
330 int i = len-1;
331 while (i > 0)
332 {
223d09f6 333 if (buffer[i] == wxT('.'))
c801d85f
KB
334 {
335 buffer[i] = 0;
336 break;
337 }
338 i --;
339 }
340}
341
47fa7969
JS
342void wxStripExtension(wxString& buffer)
343{
344 size_t len = buffer.Length();
345 size_t i = len-1;
346 while (i > 0)
347 {
223d09f6 348 if (buffer.GetChar(i) == wxT('.'))
47fa7969
JS
349 {
350 buffer = buffer.Left(i);
351 break;
352 }
353 i --;
354 }
355}
356
c801d85f 357// Destructive removal of /./ and /../ stuff
50920146 358wxChar *wxRealPath (wxChar *path)
c801d85f 359{
2049ba38 360#ifdef __WXMSW__
223d09f6 361 static const wxChar SEP = wxT('\\');
c801d85f
KB
362 Unix2DosFilename(path);
363#else
223d09f6 364 static const wxChar SEP = wxT('/');
c801d85f
KB
365#endif
366 if (path[0] && path[1]) {
367 /* MATTHEW: special case "/./x" */
50920146 368 wxChar *p;
223d09f6 369 if (path[2] == SEP && path[1] == wxT('.'))
c801d85f
KB
370 p = &path[0];
371 else
372 p = &path[2];
373 for (; *p; p++)
374 {
3f4a0c5b
VZ
375 if (*p == SEP)
376 {
223d09f6 377 if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
3f4a0c5b 378 {
50920146 379 wxChar *q;
3f4a0c5b 380 for (q = p - 1; q >= path && *q != SEP; q--);
223d09f6 381 if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
3f4a0c5b
VZ
382 && (q - 1 <= path || q[-1] != SEP))
383 {
50920146 384 wxStrcpy (q, p + 3);
223d09f6 385 if (path[0] == wxT('\0'))
3f4a0c5b
VZ
386 {
387 path[0] = SEP;
223d09f6 388 path[1] = wxT('\0');
3f4a0c5b 389 }
2049ba38 390#ifdef __WXMSW__
3f4a0c5b 391 /* Check that path[2] is NULL! */
223d09f6 392 else if (path[1] == wxT(':') && !path[2])
3f4a0c5b
VZ
393 {
394 path[2] = SEP;
223d09f6 395 path[3] = wxT('\0');
3f4a0c5b
VZ
396 }
397#endif
398 p = q - 1;
399 }
400 }
223d09f6 401 else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
50920146 402 wxStrcpy (p, p + 2);
3f4a0c5b 403 }
c801d85f
KB
404 }
405 }
406 return path;
407}
408
409// Must be destroyed
50920146 410wxChar *wxCopyAbsolutePath(const wxString& filename)
c801d85f 411{
223d09f6 412 if (filename == wxT(""))
50920146 413 return (wxChar *) NULL;
c801d85f 414
e90c1d2a 415 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename))) {
50920146 416 wxChar buf[_MAXPATHLEN];
223d09f6 417 buf[0] = wxT('\0');
7af89395 418 wxGetWorkingDirectory(buf, WXSIZEOF(buf));
50920146 419 wxChar ch = buf[wxStrlen(buf) - 1];
2049ba38 420#ifdef __WXMSW__
223d09f6
KB
421 if (ch != wxT('\\') && ch != wxT('/'))
422 wxStrcat(buf, wxT("\\"));
c801d85f 423#else
223d09f6
KB
424 if (ch != wxT('/'))
425 wxStrcat(buf, wxT("/"));
c801d85f 426#endif
e90c1d2a 427 wxStrcat(buf, wxFileFunctionsBuffer);
c801d85f
KB
428 return copystring( wxRealPath(buf) );
429 }
e90c1d2a 430 return copystring( wxFileFunctionsBuffer );
c801d85f
KB
431}
432
433/*-
434 Handles:
435 ~/ => home dir
436 ~user/ => user's home dir
437 If the environment variable a = "foo" and b = "bar" then:
438 Unix:
3f4a0c5b
VZ
439 $a => foo
440 $a$b => foobar
441 $a.c => foo.c
442 xxx$a => xxxfoo
443 ${a}! => foo!
444 $(b)! => bar!
445 \$a => \$a
c801d85f 446 MSDOS:
3f4a0c5b
VZ
447 $a ==> $a
448 $(a) ==> foo
449 $(a)$b ==> foo$b
450 $(a)$(b)==> foobar
451 test.$$ ==> test.$$
c801d85f
KB
452 */
453
454/* input name in name, pathname output to buf. */
455
50920146 456wxChar *wxExpandPath(wxChar *buf, const wxChar *name)
c801d85f 457{
50920146
OK
458 register wxChar *d, *s, *nm;
459 wxChar lnm[_MAXPATHLEN];
33ac7e6f 460 int q;
c801d85f
KB
461
462 // Some compilers don't like this line.
223d09f6 463// const wxChar trimchars[] = wxT("\n \t");
c801d85f 464
50920146 465 wxChar trimchars[4];
223d09f6
KB
466 trimchars[0] = wxT('\n');
467 trimchars[1] = wxT(' ');
468 trimchars[2] = wxT('\t');
c801d85f
KB
469 trimchars[3] = 0;
470
2049ba38 471#ifdef __WXMSW__
223d09f6 472 const wxChar SEP = wxT('\\');
c801d85f 473#else
223d09f6 474 const wxChar SEP = wxT('/');
c801d85f 475#endif
223d09f6
KB
476 buf[0] = wxT('\0');
477 if (name == NULL || *name == wxT('\0'))
3f4a0c5b 478 return buf;
c801d85f 479 nm = copystring(name); // Make a scratch copy
50920146 480 wxChar *nm_tmp = nm;
c801d85f
KB
481
482 /* Skip leading whitespace and cr */
50920146 483 while (wxStrchr((wxChar *)trimchars, *nm) != NULL)
3f4a0c5b 484 nm++;
c801d85f 485 /* And strip off trailing whitespace and cr */
50920146
OK
486 s = nm + (q = wxStrlen(nm)) - 1;
487 while (q-- && wxStrchr((wxChar *)trimchars, *s) != NULL)
223d09f6 488 *s = wxT('\0');
c801d85f
KB
489
490 s = nm;
491 d = lnm;
2049ba38 492#ifdef __WXMSW__
c801d85f
KB
493 q = FALSE;
494#else
223d09f6 495 q = nm[0] == wxT('\\') && nm[1] == wxT('~');
c801d85f
KB
496#endif
497
498 /* Expand inline environment variables */
c2ff79b1
DW
499#ifdef __VISAGECPP__
500 while (*d)
501 {
502 *d++ = *s;
223d09f6 503 if(*s == wxT('\\'))
c2ff79b1
DW
504 {
505 *(d - 1) = *++s;
506 if (*d)
507 {
508 s++;
509 continue;
510 }
511 else
512 break;
513 }
514 else
515#else
22394d24 516 while ((*d++ = *s) != 0) {
c2ff79b1 517# ifndef __WXMSW__
223d09f6 518 if (*s == wxT('\\')) {
3f4a0c5b
VZ
519 if ((*(d - 1) = *++s)) {
520 s++;
521 continue;
522 } else
523 break;
524 } else
c2ff79b1 525# endif
c801d85f 526#endif
2049ba38 527#ifdef __WXMSW__
223d09f6 528 if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
c801d85f 529#else
223d09f6 530 if (*s++ == wxT('$'))
3f4a0c5b
VZ
531#endif
532 {
50920146 533 register wxChar *start = d;
223d09f6 534 register int braces = (*s == wxT('{') || *s == wxT('('));
50920146 535 register wxChar *value;
22394d24 536 while ((*d++ = *s) != 0)
223d09f6 537 if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
3f4a0c5b
VZ
538 break;
539 else
540 s++;
541 *--d = 0;
50920146 542 value = wxGetenv(braces ? start + 1 : start);
3f4a0c5b 543 if (value) {
22394d24 544 for ((d = start - 1); (*d++ = *value++) != 0;);
3f4a0c5b
VZ
545 d--;
546 if (braces && *s)
547 s++;
548 }
549 }
c801d85f
KB
550 }
551
552 /* Expand ~ and ~user */
553 nm = lnm;
223d09f6
KB
554 s = wxT("");
555 if (nm[0] == wxT('~') && !q)
c801d85f 556 {
3f4a0c5b
VZ
557 /* prefix ~ */
558 if (nm[1] == SEP || nm[1] == 0)
559 { /* ~/filename */
f6bcfd97 560 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
223d09f6 561 if ((s = WXSTRINGCAST wxGetUserHome(wxT(""))) != NULL) {
3f4a0c5b
VZ
562 if (*++nm)
563 nm++;
564 }
c801d85f 565 } else
3f4a0c5b 566 { /* ~user/filename */
50920146
OK
567 register wxChar *nnm;
568 register wxChar *home;
3f4a0c5b
VZ
569 for (s = nm; *s && *s != SEP; s++);
570 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
c801d85f 571 was_sep = (*s == SEP);
3f4a0c5b
VZ
572 nnm = *s ? s + 1 : s;
573 *s = 0;
f6bcfd97 574 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
0e6667e2 575 if ((home = WXSTRINGCAST wxGetUserHome(wxString(nm + 1))) == NULL) {
c801d85f 576 if (was_sep) /* replace only if it was there: */
3f4a0c5b 577 *s = SEP;
223d09f6 578 s = wxT("");
3f4a0c5b
VZ
579 } else {
580 nm = nnm;
581 s = home;
582 }
583 }
c801d85f
KB
584 }
585
586 d = buf;
587 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
3f4a0c5b 588 /* Copy home dir */
223d09f6 589 while (wxT('\0') != (*d++ = *s++))
3f4a0c5b
VZ
590 /* loop */;
591 // Handle root home
592 if (d - 1 > buf && *(d - 2) != SEP)
593 *(d - 1) = SEP;
c801d85f
KB
594 }
595 s = nm;
22394d24 596 while ((*d++ = *s++) != 0);
c801d85f
KB
597 delete[] nm_tmp; // clean up alloc
598 /* Now clean up the buffer */
599 return wxRealPath(buf);
600}
601
c801d85f
KB
602/* Contract Paths to be build upon an environment variable
603 component:
604
605 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
606
607 The call wxExpandPath can convert these back!
608 */
50920146 609wxChar *
c801d85f
KB
610wxContractPath (const wxString& filename, const wxString& envname, const wxString& user)
611{
50920146 612 static wxChar dest[_MAXPATHLEN];
c801d85f 613
223d09f6 614 if (filename == wxT(""))
50920146 615 return (wxChar *) NULL;
c801d85f 616
50920146 617 wxStrcpy (dest, WXSTRINGCAST filename);
2049ba38 618#ifdef __WXMSW__
c801d85f
KB
619 Unix2DosFilename(dest);
620#endif
621
622 // Handle environment
0e6667e2 623 const wxChar *val = (const wxChar *) NULL;
50920146
OK
624 wxChar *tcp = (wxChar *) NULL;
625 if (envname != WXSTRINGCAST NULL && (val = wxGetenv (WXSTRINGCAST envname)) != NULL &&
626 (tcp = wxStrstr (dest, val)) != NULL)
c801d85f 627 {
e90c1d2a 628 wxStrcpy (wxFileFunctionsBuffer, tcp + wxStrlen (val));
223d09f6
KB
629 *tcp++ = wxT('$');
630 *tcp++ = wxT('{');
50920146 631 wxStrcpy (tcp, WXSTRINGCAST envname);
223d09f6 632 wxStrcat (tcp, wxT("}"));
e90c1d2a 633 wxStrcat (tcp, wxFileFunctionsBuffer);
c801d85f
KB
634 }
635
636 // Handle User's home (ignore root homes!)
637 size_t len = 0;
638 if ((val = wxGetUserHome (user)) != NULL &&
50920146
OK
639 (len = wxStrlen(val)) > 2 &&
640 wxStrncmp(dest, val, len) == 0)
c801d85f 641 {
223d09f6
KB
642 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
643 if (user != wxT(""))
e90c1d2a 644 wxStrcat(wxFileFunctionsBuffer, (const wxChar*) user);
2049ba38 645#ifdef __WXMSW__
e90c1d2a 646// strcat(wxFileFunctionsBuffer, "\\");
c801d85f 647#else
e90c1d2a 648// strcat(wxFileFunctionsBuffer, "/");
c801d85f 649#endif
e90c1d2a
VZ
650 wxStrcat(wxFileFunctionsBuffer, dest + len);
651 wxStrcpy (dest, wxFileFunctionsBuffer);
c801d85f
KB
652 }
653
654 return dest;
655}
656
657// Return just the filename, not the path
658// (basename)
50920146 659wxChar *wxFileNameFromPath (wxChar *path)
c801d85f 660{
e8e1d09e 661 if (path)
c801d85f 662 {
e8e1d09e
GD
663 register wxChar *tcp;
664
665 tcp = path + wxStrlen (path);
666 while (--tcp >= path)
3f4a0c5b 667 {
e8e1d09e
GD
668#if defined(__WXMAC__) && !defined(__DARWIN__)
669 // Classic or Carbon CodeWarrior like
670 // Carbon with Apple DevTools is Unix like
671 if (*tcp == wxT(':'))
672 return tcp + 1;
c801d85f 673#else
e8e1d09e
GD
674 // Unix like or Windows
675 if (*tcp == wxT('/') || *tcp == wxT('\\'))
676 return tcp + 1;
bedaf53e 677#endif
e8e1d09e
GD
678#ifdef __VMS__
679 if (*tcp == wxT(':') || *tcp == wxT(']'))
680 return tcp + 1;
c801d85f 681#endif
e8e1d09e 682 } /* while */
c2ff79b1 683#if defined(__WXMSW__) || defined(__WXPM__)
e8e1d09e
GD
684 // MSDOS like
685 if (wxIsalpha (*path) && *(path + 1) == wxT(':'))
686 return path + 2;
c801d85f
KB
687#endif
688 }
e8e1d09e 689 return path;
c801d85f
KB
690}
691
692wxString wxFileNameFromPath (const wxString& path1)
693{
e8e1d09e
GD
694 if (path1 != wxT(""))
695 {
696 wxChar *path = WXSTRINGCAST path1 ;
697 register wxChar *tcp;
698
699 tcp = path + wxStrlen (path);
700 while (--tcp >= path)
701 {
702#if defined(__WXMAC__) && !defined(__DARWIN__)
703 // Classic or Carbon CodeWarrior like
704 // Carbon with Apple DevTools is Unix like
705 if (*tcp == wxT(':') )
706 return wxString(tcp + 1);
c801d85f 707#else
e8e1d09e
GD
708 // Unix like or Windows
709 if (*tcp == wxT('/') || *tcp == wxT('\\'))
710 return wxString(tcp + 1);
c801d85f 711#endif
e8e1d09e
GD
712#ifdef __VMS__
713 if (*tcp == wxT(':') || *tcp == wxT(']'))
3f4a0c5b 714 return wxString(tcp + 1);
e8e1d09e
GD
715#endif
716 } /* while */
c2ff79b1 717#if defined(__WXMSW__) || defined(__WXPM__)
e8e1d09e
GD
718 // MSDOS like
719 if (wxIsalpha (*path) && *(path + 1) == wxT(':'))
3f4a0c5b 720 return wxString(path + 2);
c801d85f
KB
721#endif
722 }
e8e1d09e
GD
723 // Yes, this should return the path, not an empty string, otherwise
724 // we get "thing.txt" -> "".
725 return path1;
c801d85f
KB
726}
727
728// Return just the directory, or NULL if no directory
50920146
OK
729wxChar *
730wxPathOnly (wxChar *path)
c801d85f 731{
e8e1d09e 732 if (path && *path)
c801d85f 733 {
e8e1d09e
GD
734 static wxChar buf[_MAXPATHLEN];
735
736 // Local copy
737 wxStrcpy (buf, path);
738
739 int l = wxStrlen(path);
740 int i = l - 1;
741
742 // Search backward for a backward or forward slash
743 while (i > -1)
744 {
745#if defined(__WXMAC__) && !defined(__DARWIN__)
746 // Classic or Carbon CodeWarrior like
747 // Carbon with Apple DevTools is Unix like
748 if (path[i] == wxT(':') )
749 {
750 buf[i] = 0;
751 return buf;
752 }
bedaf53e 753#else
e8e1d09e
GD
754 // Unix like or Windows
755 if (path[i] == wxT('/') || path[i] == wxT('\\'))
756 {
757 buf[i] = 0;
758 return buf;
759 }
bedaf53e 760#endif
c801d85f 761#ifdef __VMS__
e8e1d09e
GD
762 if (path[i] == wxT(']'))
763 {
764 buf[i+1] = 0;
765 return buf;
766 }
a339970a 767#endif
e8e1d09e 768 i --;
c801d85f 769 }
e8e1d09e 770
c2ff79b1 771#if defined(__WXMSW__) || defined(__WXPM__)
e8e1d09e
GD
772 // Try Drive specifier
773 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
3f4a0c5b 774 {
e8e1d09e
GD
775 // A:junk --> A:. (since A:.\junk Not A:\junk)
776 buf[2] = wxT('.');
777 buf[3] = wxT('\0');
778 return buf;
3f4a0c5b 779 }
c801d85f
KB
780#endif
781 }
e8e1d09e 782 return (wxChar *) NULL;
c801d85f
KB
783}
784
785// Return just the directory, or NULL if no directory
786wxString wxPathOnly (const wxString& path)
787{
e8e1d09e 788 if (path != wxT(""))
c801d85f 789 {
e8e1d09e
GD
790 wxChar buf[_MAXPATHLEN];
791
792 // Local copy
793 wxStrcpy (buf, WXSTRINGCAST path);
794
795 int l = path.Length();
796 int i = l - 1;
797
798 // Search backward for a backward or forward slash
799 while (i > -1)
800 {
801#if defined(__WXMAC__) && !defined(__DARWIN__)
802 // Classic or Carbon CodeWarrior like
803 // Carbon with Apple DevTools is Unix like
804 if (path[i] == wxT(':') )
805 {
806 buf[i] = 0;
807 return wxString(buf);
808 }
bedaf53e 809#else
e8e1d09e
GD
810 // Unix like or Windows
811 if (path[i] == wxT('/') || path[i] == wxT('\\'))
812 {
813 buf[i] = 0;
814 return wxString(buf);
815 }
bedaf53e 816#endif
c801d85f 817#ifdef __VMS__
e8e1d09e
GD
818 if (path[i] == wxT(']'))
819 {
820 buf[i+1] = 0;
821 return wxString(buf);
822 }
a339970a 823#endif
e8e1d09e 824 i --;
c801d85f 825 }
e8e1d09e 826
c2ff79b1 827#if defined(__WXMSW__) || defined(__WXPM__)
e8e1d09e
GD
828 // Try Drive specifier
829 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
3f4a0c5b 830 {
e8e1d09e
GD
831 // A:junk --> A:. (since A:.\junk Not A:\junk)
832 buf[2] = wxT('.');
833 buf[3] = wxT('\0');
834 return wxString(buf);
3f4a0c5b 835 }
c801d85f
KB
836#endif
837 }
e8e1d09e 838 return wxString(wxT(""));
c801d85f
KB
839}
840
841// Utility for converting delimiters in DOS filenames to UNIX style
842// and back again - or we get nasty problems with delimiters.
843// Also, convert to lower case, since case is significant in UNIX.
844
da2b4b7a 845#if defined(__WXMAC__)
bedaf53e
SC
846wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
847{
a1c34a78
GD
848#ifdef __DARWIN__
849 FSRef theRef;
850 char thePath[FILENAME_MAX];
851
852 // convert the FSSpec to an FSRef
853 (void) FSpMakeFSRef( spec, &theRef );
854 // get the POSIX path associated with the FSRef
855 (void) FSRefMakePath( &theRef, (UInt8 *)thePath, sizeof(thePath) );
856
857 // create path string for return value
858 wxString result( thePath ) ;
859#else
bedaf53e
SC
860 Handle myPath ;
861 short length ;
862
a1c34a78 863 // get length of path and allocate handle
bedaf53e
SC
864 FSpGetFullPath( spec , &length , &myPath ) ;
865 ::SetHandleSize( myPath , length + 1 ) ;
866 ::HLock( myPath ) ;
867 (*myPath)[length] = 0 ;
a1c34a78 868 if ((length > 0) && ((*myPath)[length-1] == ':'))
bedaf53e 869 (*myPath)[length-1] = 0 ;
a1c34a78
GD
870
871 // create path string for return value
334d2448 872 wxString result( (char*) *myPath ) ;
a1c34a78
GD
873
874 // free allocated handle
bedaf53e
SC
875 ::HUnlock( myPath ) ;
876 ::DisposeHandle( myPath ) ;
a1c34a78
GD
877#endif
878
bedaf53e
SC
879 return result ;
880}
e7549107 881
bedaf53e
SC
882void wxMacFilename2FSSpec( const char *path , FSSpec *spec )
883{
334d2448 884#ifdef __DARWIN__
a1c34a78
GD
885 FSRef theRef;
886
887 // get the FSRef associated with the POSIX path
888 (void) FSPathMakeRef((const UInt8 *) path, &theRef, NULL);
889 // convert the FSRef to an FSSpec
890 (void) FSGetCatalogInfo(&theRef, kFSCatInfoNone, NULL, NULL, spec, NULL);
334d2448
GD
891#else
892 FSpLocationFromFullPath( strlen(path) , path , spec ) ;
893#endif
bedaf53e
SC
894}
895
a1c34a78
GD
896#ifndef __DARWIN__
897// Mac file names are POSIX (Unix style) under Darwin
898// therefore the conversion functions below are not needed
899
e7549107
SC
900static char sMacFileNameConversion[ 1000 ] ;
901
902wxString wxMac2UnixFilename (const char *str)
17dff81c 903{
f6bcfd97
BP
904 char *s = sMacFileNameConversion ;
905 strcpy( s , str ) ;
a1c34a78
GD
906 if (s)
907 {
908 memmove( s+1 , s ,strlen( s ) + 1) ;
909 if ( *s == ':' )
e7549107 910 *s = '.' ;
a1c34a78 911 else
e7549107 912 *s = '/' ;
a1c34a78
GD
913
914 while (*s)
915 {
e7549107 916 if (*s == ':')
a1c34a78 917 *s = '/';
e7549107 918 else
a1c34a78 919 *s = wxTolower(*s); // Case INDEPENDENT
e7549107 920 s++;
a1c34a78 921 }
e7549107 922 }
a1c34a78 923 return wxString(sMacFileNameConversion) ;
17dff81c
SC
924}
925
e7549107 926wxString wxUnix2MacFilename (const char *str)
17dff81c 927{
f6bcfd97
BP
928 char *s = sMacFileNameConversion ;
929 strcpy( s , str ) ;
a1c34a78 930 if (s)
e7549107 931 {
a1c34a78
GD
932 if ( *s == '.' )
933 {
934 // relative path , since it goes on with slash which is translated to a :
935 memmove( s , s+1 ,strlen( s ) ) ;
936 }
937 else if ( *s == '/' )
938 {
939 // absolute path -> on mac just start with the drive name
940 memmove( s , s+1 ,strlen( s ) ) ;
941 }
942 else
943 {
944 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
945 }
946 while (*s)
947 {
948 if (*s == '/' || *s == '\\')
949 {
950 // convert any back-directory situations
951 if ( *(s+1) == '.' && *(s+2) == '.' && ( (*(s+3) == '/' || *(s+3) == '\\') ) )
952 {
953 *s = ':';
954 memmove( s+1 , s+3 ,strlen( s+3 ) + 1 ) ;
955 }
956 else
957 *s = ':';
958 }
959 s++ ;
960 }
e7549107 961 }
a1c34a78 962 return wxString (sMacFileNameConversion) ;
17dff81c 963}
e7549107 964
e7549107
SC
965wxString wxMacFSSpec2UnixFilename( const FSSpec *spec )
966{
f6bcfd97 967 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec) ) ;
e7549107
SC
968}
969
e7549107
SC
970void wxUnixFilename2FSSpec( const char *path , FSSpec *spec )
971{
f6bcfd97
BP
972 wxString var = wxUnix2MacFilename( path ) ;
973 wxMacFilename2FSSpec( var , spec ) ;
e7549107 974}
a1c34a78 975#endif // ! __DARWIN__
12d67f8a 976
e8e1d09e
GD
977#endif // __WXMAC__
978
3f4a0c5b 979void
e7549107 980wxDos2UnixFilename (char *s)
c801d85f
KB
981{
982 if (s)
983 while (*s)
984 {
e7549107
SC
985 if (*s == '\\')
986 *s = '/';
987#ifdef __WXMSW__
3f4a0c5b 988 else
e7549107 989 *s = wxTolower (*s); // Case INDEPENDENT
c801d85f 990#endif
3f4a0c5b 991 s++;
c801d85f
KB
992 }
993}
994
3f4a0c5b 995void
f28538c5 996#if defined(__WXMSW__) || defined(__WXPM__)
5b735202 997wxUnix2DosFilename (wxChar *s)
46dc76ba 998#else
5b735202 999wxUnix2DosFilename (wxChar *WXUNUSED(s) )
46dc76ba 1000#endif
c801d85f
KB
1001{
1002// Yes, I really mean this to happen under DOS only! JACS
c2ff79b1 1003#if defined(__WXMSW__) || defined(__WXPM__)
c801d85f
KB
1004 if (s)
1005 while (*s)
1006 {
223d09f6
KB
1007 if (*s == wxT('/'))
1008 *s = wxT('\\');
3f4a0c5b 1009 s++;
c801d85f
KB
1010 }
1011#endif
1012}
1013
1014// Concatenate two files to form third
3f4a0c5b 1015bool
c801d85f
KB
1016wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
1017{
a339970a
VZ
1018 wxString outfile;
1019 if ( !wxGetTempFileName("cat", outfile) )
1020 return FALSE;
c801d85f 1021
c67daf87
UR
1022 FILE *fp1 = (FILE *) NULL;
1023 FILE *fp2 = (FILE *) NULL;
1024 FILE *fp3 = (FILE *) NULL;
c801d85f 1025 // Open the inputs and outputs
e987a489
VS
1026 if ((fp1 = wxFopen (OS_FILENAME( file1 ), wxT("rb"))) == NULL ||
1027 (fp2 = wxFopen (OS_FILENAME( file2 ), wxT("rb"))) == NULL ||
1028 (fp3 = wxFopen (OS_FILENAME( outfile ), wxT("wb"))) == NULL)
c801d85f
KB
1029 {
1030 if (fp1)
3f4a0c5b 1031 fclose (fp1);
c801d85f 1032 if (fp2)
3f4a0c5b 1033 fclose (fp2);
c801d85f 1034 if (fp3)
3f4a0c5b 1035 fclose (fp3);
c801d85f
KB
1036 return FALSE;
1037 }
1038
1039 int ch;
1040 while ((ch = getc (fp1)) != EOF)
1041 (void) putc (ch, fp3);
1042 fclose (fp1);
1043
1044 while ((ch = getc (fp2)) != EOF)
1045 (void) putc (ch, fp3);
1046 fclose (fp2);
1047
1048 fclose (fp3);
1049 bool result = wxRenameFile(outfile, file3);
c801d85f
KB
1050 return result;
1051}
1052
1053// Copy files
3f4a0c5b 1054bool
4658c44e 1055wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
c801d85f 1056{
04ef50df 1057#if defined(__WIN32__) && !defined(__WXMICROWIN__)
4658c44e
VZ
1058 // CopyFile() copies file attributes and modification time too, so use it
1059 // instead of our code if available
1060 //
1061 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
7a656506 1062 return ::CopyFile(file1, file2, !overwrite) != 0;
19193a2c
KB
1063#elif defined(__WXPM__)
1064 if (::DosCopy(file2, file2, overwrite ? DCPY_EXISTING : 0) == 0)
1065 return TRUE;
1066 else
1067 return FALSE;
4658c44e 1068#else // !Win32
32f31043
VZ
1069 wxStructStat fbuf;
1070
1071 // get permissions of file1
c3396917 1072 if ( wxStat(OS_FILENAME(file1), &fbuf) != 0 )
32f31043
VZ
1073 {
1074 // the file probably doesn't exist or we haven't the rights to read
1075 // from it anyhow
1076 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1077 file1.c_str());
1078 return FALSE;
1079 }
1080
1081 // open file1 for reading
1082 wxFile fileIn(file1, wxFile::read);
a339970a
VZ
1083 if ( !fileIn.IsOpened() )
1084 return FALSE;
c801d85f 1085
32f31043
VZ
1086 // remove file2, if it exists. This is needed for creating
1087 // file2 with the correct permissions in the next step
4658c44e 1088 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
32f31043
VZ
1089 {
1090 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1091 file2.c_str());
1092 return FALSE;
1093 }
1094
1095#ifdef __UNIX__
1096 // reset the umask as we want to create the file with exactly the same
1097 // permissions as the original one
1098 mode_t oldUmask = umask( 0 );
1099#endif // __UNIX__
1100
1101 // create file2 with the same permissions than file1 and open it for
1102 // writing
1103 wxFile fileOut;
4658c44e 1104 if ( !fileOut.Create(file2, overwrite, fbuf.st_mode & 0777) )
a339970a 1105 return FALSE;
c801d85f 1106
32f31043
VZ
1107#ifdef __UNIX__
1108 /// restore the old umask
1109 umask(oldUmask);
1110#endif // __UNIX__
1111
1112 // copy contents of file1 to file2
a339970a
VZ
1113 char buf[4096];
1114 size_t count;
1115 for ( ;; )
c7386783 1116 {
a339970a
VZ
1117 count = fileIn.Read(buf, WXSIZEOF(buf));
1118 if ( fileIn.Error() )
1119 return FALSE;
1120
1121 // end of file?
1122 if ( !count )
1123 break;
1124
1125 if ( fileOut.Write(buf, count) < count )
1126 return FALSE;
c7386783 1127 }
c801d85f 1128
abb74e97
VZ
1129 // we can expect fileIn to be closed successfully, but we should ensure
1130 // that fileOut was closed as some write errors (disk full) might not be
1131 // detected before doing this
1132 if ( !fileIn.Close() || !fileOut.Close() )
1133 return FALSE;
1134
5fde6fcc 1135#if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
abb74e97
VZ
1136 // no chmod in VA. Should be some permission API for HPFS386 partitions
1137 // however
c3396917 1138 if ( chmod(OS_FILENAME(file2), fbuf.st_mode) != 0 )
32f31043
VZ
1139 {
1140 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1141 file2.c_str());
1142 return FALSE;
1143 }
4658c44e
VZ
1144#endif // OS/2 || Mac
1145
a339970a 1146 return TRUE;
4658c44e 1147#endif // __WXMSW__ && __WIN32__
c801d85f
KB
1148}
1149
3f4a0c5b 1150bool
c801d85f
KB
1151wxRenameFile (const wxString& file1, const wxString& file2)
1152{
1153 // Normal system call
c3396917 1154 if ( wxRename (file1, file2) == 0 )
c801d85f 1155 return TRUE;
a339970a 1156
c801d85f
KB
1157 // Try to copy
1158 if (wxCopyFile(file1, file2)) {
1159 wxRemoveFile(file1);
1160 return TRUE;
1161 }
1162 // Give up
1163 return FALSE;
1164}
1165
1166bool wxRemoveFile(const wxString& file)
1167{
161f4f73
VZ
1168#if defined(__VISUALC__) \
1169 || defined(__BORLANDC__) \
1170 || defined(__WATCOMC__) \
1171 || defined(__GNUWIN32__)
a339970a 1172 int res = wxRemove(file);
c801d85f 1173#else
a339970a 1174 int res = unlink(OS_FILENAME(file));
c801d85f 1175#endif
a339970a
VZ
1176
1177 return res == 0;
c801d85f
KB
1178}
1179
1a33c3ba 1180bool wxMkdir(const wxString& dir, int perm)
c801d85f 1181{
5fde6fcc 1182#if defined(__WXMAC__) && !defined(__UNIX__)
bedaf53e 1183 return (mkdir( dir , 0 ) == 0);
7708abe9 1184#else // !Mac
50920146 1185 const wxChar *dirname = dir.c_str();
1a33c3ba 1186
c2ff79b1 1187 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
7708abe9 1188 // for the GNU compiler
8cb172b4 1189#if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__) || defined(__WXMICROWIN__)
50920146 1190 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
f6bcfd97
BP
1191#elif defined(__WXPM__)
1192 if (::DosCreateDir((PSZ)dirname, NULL) != 0) // enhance for EAB's??
6fdbbb00 1193#else // !MSW and !OS/2 VAC++
19193a2c 1194 (void)perm;
f6bcfd97 1195 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
7708abe9 1196#endif // !MSW/MSW
1a33c3ba
VZ
1197 {
1198 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1199
1200 return FALSE;
1201 }
1202
1203 return TRUE;
e7549107 1204#endif // Mac/!Mac
c801d85f
KB
1205}
1206
1207bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1208{
1209#ifdef __VMS__
acdc3b6b 1210 return FALSE; //to be changed since rmdir exists in VMS7.x
f6bcfd97
BP
1211#elif defined(__WXPM__)
1212 return (::DosDeleteDir((PSZ)dir.c_str()) == 0);
c801d85f 1213#else
a3ef5bf5
JS
1214
1215#ifdef __SALFORDC__
1216 return FALSE; // What to do?
1217#else
a339970a 1218 return (wxRmDir(OS_FILENAME(dir)) == 0);
c801d85f
KB
1219#endif
1220
1221#endif
1222}
1223
c801d85f 1224// does the path exists? (may have or not '/' or '\\' at the end)
50920146 1225bool wxPathExists(const wxChar *pszPathName)
c801d85f 1226{
f6bcfd97
BP
1227 wxString strPath(pszPathName);
1228#ifdef __WINDOWS__
1229 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1230 // so remove all trailing backslashes from the path - but don't do this for
1231 // the pathes "d:\" (which are different from "d:") nor for just "\"
1232 while ( wxEndsWithPathSeparator(strPath) )
1233 {
1234 size_t len = strPath.length();
cc4a1ce1 1235 if ( len == 1 || (len == 3 && strPath[len - 2] == _T(':')) )
f6bcfd97 1236 break;
c801d85f 1237
f6bcfd97
BP
1238 strPath.Truncate(len - 1);
1239 }
1240#endif // __WINDOWS__
1241
4c97e024
JS
1242#ifdef __WINDOWS__
1243 // Stat can't cope with network paths
1244 DWORD ret = GetFileAttributes(strPath.c_str());
1245 DWORD isDir = (ret & FILE_ATTRIBUTE_DIRECTORY);
1246 return ((ret != 0xffffffff) && (isDir != 0));
1247#else
1248
f6bcfd97 1249 wxStructStat st;
71c97a89 1250#ifndef __VISAGECPP__
f6bcfd97
BP
1251 return wxStat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 &&
1252 ((st.st_mode & S_IFMT) == S_IFDIR);
71c97a89
DW
1253#else
1254 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1255 return wxStat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 &&
1256 (st.st_mode == S_IFDIR);
1257#endif
1258
4c97e024 1259#endif
c801d85f
KB
1260}
1261
1262// Get a temporary filename, opening and closing the file.
50920146 1263wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
c801d85f 1264{
04ef50df 1265#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
c801d85f 1266
3f4a0c5b 1267#ifndef __WIN32__
50920146 1268 wxChar tmp[144];
c801d85f
KB
1269 ::GetTempFileName(0, WXSTRINGCAST prefix, 0, tmp);
1270#else
50920146
OK
1271 wxChar tmp[MAX_PATH];
1272 wxChar tmpPath[MAX_PATH];
c801d85f
KB
1273 ::GetTempPath(MAX_PATH, tmpPath);
1274 ::GetTempFileName(tmpPath, WXSTRINGCAST prefix, 0, tmp);
1275#endif
50920146 1276 if (buf) wxStrcpy(buf, tmp);
c801d85f
KB
1277 else buf = copystring(tmp);
1278 return buf;
1279
1280#else
3f4a0c5b 1281 static short last_temp = 0; // cache last to speed things a bit
c801d85f 1282 // At most 1000 temp files to a process! We use a ring count.
50920146 1283 wxChar tmp[100]; // FIXME static buffer
c801d85f
KB
1284
1285 for (short suffix = last_temp + 1; suffix != last_temp; ++suffix %= 1000)
1286 {
223d09f6 1287 wxSprintf (tmp, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix, (int) getpid (), (int) suffix);
c801d85f 1288 if (!wxFileExists( tmp ))
3f4a0c5b
VZ
1289 {
1290 // Touch the file to create it (reserve name)
50920146 1291 FILE *fd = fopen (wxFNCONV(tmp), "w");
3f4a0c5b
VZ
1292 if (fd)
1293 fclose (fd);
1294 last_temp = suffix;
c801d85f 1295 if (buf)
50920146 1296 wxStrcpy( buf, tmp);
3f4a0c5b
VZ
1297 else
1298 buf = copystring( tmp );
1299 return buf;
1300 }
c801d85f 1301 }
f5abe911 1302 wxLogError( _("wxWindows: error finding temporary file name.\n") );
c801d85f 1303 if (buf) buf[0] = 0;
50920146 1304 return (wxChar *) NULL;
c801d85f
KB
1305#endif
1306}
1307
c0ab6adf
JS
1308bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1309{
1310 wxChar buf2[512];
1311 if (wxGetTempFileName(prefix, buf2) != (wxChar*) NULL)
1312 {
1313 buf = buf2;
1314 return TRUE;
1315 }
1316 else
1317 return FALSE;
1318}
1319
c801d85f
KB
1320// Get first file name matching given wild card.
1321
a1c34a78 1322#if defined(__UNIX__)
c801d85f
KB
1323
1324// Get first file name matching given wild card.
1325// Flags are reserved for future use.
1326
acdc3b6b 1327#if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
7af89395
VZ
1328 static DIR *gs_dirStream = (DIR *) NULL;
1329 static wxString gs_strFileSpec;
1330 static int gs_findFlags = 0;
c801d85f
KB
1331#endif
1332
50920146 1333wxString wxFindFirstFile(const wxChar *spec, int flags)
c801d85f 1334{
7af89395 1335 wxString result;
03c046d1
JJ
1336#ifdef __VMS
1337 wxChar *specvms = NULL;
1338#endif
a339970a 1339
acdc3b6b 1340#if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
7af89395
VZ
1341 if (gs_dirStream)
1342 closedir(gs_dirStream); // edz 941103: better housekeping
c801d85f 1343
7af89395 1344 gs_findFlags = flags;
c801d85f 1345
7af89395 1346 gs_strFileSpec = spec;
c801d85f 1347
7af89395
VZ
1348 // Find path only so we can concatenate
1349 // found file onto path
1350 wxString path(wxPathOnly(gs_strFileSpec));
c801d85f 1351
7af89395 1352 // special case: path is really "/"
223d09f6 1353 if ( !path && gs_strFileSpec[0u] == wxT('/') )
03c046d1
JJ
1354#ifdef __VMS
1355 {
a339970a
VZ
1356 wxStrcpy( specvms , wxT( "[000000]" ) );
1357 gs_strFileSpec = specvms;
1358 wxString path_vms(wxPathOnly(gs_strFileSpec));
1359 path = path_vms;
03c046d1
JJ
1360 }
1361#else
1362 path = wxT('/');
1363#endif
1364 // path is empty => Local directory
7af89395 1365 if ( !path )
03c046d1
JJ
1366#ifdef __VMS
1367 {
a339970a
VZ
1368 wxStrcpy( specvms , wxT( "[]" ) );
1369 gs_strFileSpec = specvms;
1370 wxString path_vms1(wxPathOnly(gs_strFileSpec));
1371 path = path_vms1;
03c046d1
JJ
1372 }
1373#else
1374 path = wxT('.');
1375#endif
a339970a 1376
50920146 1377 gs_dirStream = opendir(path.fn_str());
7af89395
VZ
1378 if ( !gs_dirStream )
1379 {
1380 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1381 path.c_str());
1382 }
1383 else
1384 {
1385 result = wxFindNextFile();
1386 }
acdc3b6b 1387#endif // !VMS6.x or earlier
c801d85f 1388
7af89395 1389 return result;
c801d85f
KB
1390}
1391
7af89395 1392wxString wxFindNextFile()
c801d85f 1393{
7af89395 1394 wxString result;
c801d85f 1395
acdc3b6b 1396#if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
223d09f6 1397 wxCHECK_MSG( gs_dirStream, result, wxT("must call wxFindFirstFile first") );
7af89395
VZ
1398
1399 // Find path only so we can concatenate
1400 // found file onto path
1401 wxString path(wxPathOnly(gs_strFileSpec));
1402 wxString name(wxFileNameFromPath(gs_strFileSpec));
1403
1404 /* MATTHEW: special case: path is really "/" */
223d09f6
KB
1405 if ( !path && gs_strFileSpec[0u] == wxT('/'))
1406 path = wxT('/');
7af89395
VZ
1407
1408 // Do the reading
1409 struct dirent *nextDir;
1410 for ( nextDir = readdir(gs_dirStream);
1411 nextDir != NULL;
1412 nextDir = readdir(gs_dirStream) )
1413 {
bf9e3e73 1414 if (wxMatchWild(name, nextDir->d_name, FALSE) && // RR: added FALSE to find hidden files
f6bcfd97
BP
1415 strcmp(nextDir->d_name, ".") &&
1416 strcmp(nextDir->d_name, "..") )
7af89395
VZ
1417 {
1418 result.Empty();
1419 if ( !path.IsEmpty() )
1420 {
1421 result = path;
223d09f6
KB
1422 if ( path != wxT('/') )
1423 result += wxT('/');
7af89395 1424 }
c801d85f 1425
7af89395 1426 result += nextDir->d_name;
c801d85f 1427
7af89395
VZ
1428 // Only return "." and ".." when they match
1429 bool isdir;
1430 if ( (strcmp(nextDir->d_name, ".") == 0) ||
1431 (strcmp(nextDir->d_name, "..") == 0))
1432 {
1433 if ( (gs_findFlags & wxDIR) != 0 )
1434 isdir = TRUE;
1435 else
1436 continue;
1437 }
1438 else
1439 isdir = wxDirExists(result);
c801d85f 1440
7af89395
VZ
1441 // and only return directories when flags & wxDIR
1442 if ( !gs_findFlags ||
1443 ((gs_findFlags & wxDIR) && isdir) ||
1444 ((gs_findFlags & wxFILE) && !isdir) )
1445 {
1446 return result;
1447 }
1448 }
1449 }
c801d85f 1450
7af89395 1451 result.Empty(); // not found
c801d85f 1452
7af89395
VZ
1453 closedir(gs_dirStream);
1454 gs_dirStream = (DIR *) NULL;
acdc3b6b 1455#endif // !VMS6.2 or earlier
c801d85f 1456
7af89395 1457 return result;
c801d85f
KB
1458}
1459
7c74e7fe
SC
1460#elif defined(__WXMAC__)
1461
1462struct MacDirectoryIterator
1463{
f6bcfd97
BP
1464 CInfoPBRec m_CPB ;
1465 wxInt16 m_index ;
1466 long m_dirId ;
1467 Str255 m_name ;
7c74e7fe
SC
1468} ;
1469
1470static int g_iter_flags ;
1471
1472static MacDirectoryIterator g_iter ;
eea0ecad 1473wxString g_iter_spec ;
7c74e7fe
SC
1474
1475wxString wxFindFirstFile(const wxChar *spec, int flags)
1476{
1477 wxString result;
1478
eea0ecad
SC
1479 g_iter_spec = spec ;
1480 g_iter_spec.MakeUpper() ;
7c74e7fe
SC
1481 g_iter_flags = flags; /* MATTHEW: [5] Remember flags */
1482
1483 // Find path only so we can concatenate found file onto path
1484 wxString path(wxPathOnly(spec));
f6bcfd97
BP
1485 FSSpec fsspec ;
1486
a1c34a78 1487 wxMacFilename2FSSpec( path , &fsspec ) ;
f6bcfd97
BP
1488 g_iter.m_CPB.hFileInfo.ioVRefNum = fsspec.vRefNum ;
1489 g_iter.m_CPB.hFileInfo.ioNamePtr = g_iter.m_name ;
1490 g_iter.m_index = 0 ;
1491
1492 Boolean isDir ;
1493 FSpGetDirectoryID( &fsspec , &g_iter.m_dirId , &isDir ) ;
1494 if ( !isDir )
1495 return wxEmptyString ;
1496
1497 return wxFindNextFile( ) ;
7c74e7fe
SC
1498}
1499
1500wxString wxFindNextFile()
1501{
1502 wxString result;
1503
f6bcfd97 1504 short err = noErr ;
eea0ecad
SC
1505 wxString name ;
1506
1507 while(1)
f6bcfd97 1508 {
eea0ecad
SC
1509 while ( err == noErr )
1510 {
1511 g_iter.m_index++ ;
1512 g_iter.m_CPB.dirInfo.ioFDirIndex = g_iter.m_index;
1513 g_iter.m_CPB.dirInfo.ioDrDirID = g_iter.m_dirId; /* we need to do this every time */
1514 err = PBGetCatInfoSync((CInfoPBPtr)&g_iter.m_CPB);
1515 if ( err != noErr )
1516 break ;
f6bcfd97 1517
eea0ecad
SC
1518 if ( ( g_iter.m_CPB.dirInfo.ioFlAttrib & ioDirMask) != 0 && (g_iter_flags & wxDIR) ) // we have a directory
1519 break ;
f6bcfd97 1520
eea0ecad
SC
1521 if ( ( g_iter.m_CPB.dirInfo.ioFlAttrib & ioDirMask) == 0 && !(g_iter_flags & wxFILE ) )
1522 continue ;
f6bcfd97 1523
eea0ecad
SC
1524 // hit !
1525 break ;
1526 }
1527 if ( err != noErr )
1528 {
1529 return wxEmptyString ;
1530 }
1531 FSSpec spec ;
f6bcfd97 1532
eea0ecad
SC
1533 FSMakeFSSpecCompat(g_iter.m_CPB.hFileInfo.ioVRefNum,
1534 g_iter.m_dirId,
1535 g_iter.m_name,
1536 &spec) ;
f6bcfd97 1537
eea0ecad
SC
1538 wxString name = wxMacFSSpec2MacFilename( &spec ) ;
1539 if ( g_iter_spec.Right(4)==(":*.*") || g_iter_spec.Right(2)==(":*") || name.Upper().Matches(g_iter_spec) )
1540 return name ;
1541 }
1542 return wxEmptyString ;
7c74e7fe
SC
1543}
1544
2049ba38 1545#elif defined(__WXMSW__)
c801d85f
KB
1546
1547#ifdef __WIN32__
7af89395
VZ
1548 static HANDLE gs_hFileStruct = INVALID_HANDLE_VALUE;
1549 static WIN32_FIND_DATA gs_findDataStruct;
1550#else // Win16
1551 #ifdef __BORLANDC__
1552 static struct ffblk gs_findDataStruct;
1553 #else
1554 static struct _find_t gs_findDataStruct;
1555 #endif // Borland
1556#endif // Win32/16
1557
1558static wxString gs_strFileSpec;
1559static int gs_findFlags = 0;
1560
50920146 1561wxString wxFindFirstFile(const wxChar *spec, int flags)
c801d85f 1562{
7af89395
VZ
1563 wxString result;
1564
1565 gs_strFileSpec = spec;
1566 gs_findFlags = flags; /* MATTHEW: [5] Remember flags */
1567
1568 // Find path only so we can concatenate found file onto path
1569 wxString path(wxPathOnly(gs_strFileSpec));
1570 if ( !path.IsEmpty() )
223d09f6 1571 result << path << wxT('\\');
c801d85f
KB
1572
1573#ifdef __WIN32__
7af89395
VZ
1574 if ( gs_hFileStruct != INVALID_HANDLE_VALUE )
1575 FindClose(gs_hFileStruct);
c801d85f 1576
7af89395 1577 gs_hFileStruct = ::FindFirstFile(WXSTRINGCAST spec, &gs_findDataStruct);
c801d85f 1578
7af89395
VZ
1579 if ( gs_hFileStruct == INVALID_HANDLE_VALUE )
1580 {
7af89395 1581 result.Empty();
c801d85f 1582
7af89395
VZ
1583 return result;
1584 }
c801d85f 1585
7af89395
VZ
1586 bool isdir = !!(gs_findDataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1587
1588 if (isdir && !(flags & wxDIR))
1589 return wxFindNextFile();
1590 else if (!isdir && flags && !(flags & wxFILE))
1591 return wxFindNextFile();
c801d85f 1592
7af89395
VZ
1593 result += gs_findDataStruct.cFileName;
1594
1595 return result;
f6bcfd97 1596#else // !Win32
7af89395 1597 int flag = _A_NORMAL;
f6bcfd97 1598 if (flags & wxDIR)
7af89395 1599 flag = _A_SUBDIR;
c801d85f
KB
1600
1601#ifdef __BORLANDC__
7af89395 1602 if (findfirst(WXSTRINGCAST spec, &gs_findDataStruct, flag) == 0)
c801d85f 1603#else
7af89395 1604 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
c801d85f 1605#endif
7af89395 1606 {
7af89395 1607 char attrib;
c801d85f
KB
1608
1609#ifdef __BORLANDC__
7af89395 1610 attrib = gs_findDataStruct.ff_attrib;
c801d85f 1611#else
7af89395 1612 attrib = gs_findDataStruct.attrib;
c801d85f
KB
1613#endif
1614
7af89395
VZ
1615 if (attrib & _A_SUBDIR) {
1616 if (!(gs_findFlags & wxDIR))
1617 return wxFindNextFile();
1618 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
3f4a0c5b 1619 return wxFindNextFile();
c801d85f 1620
7af89395 1621 result +=
c801d85f 1622#ifdef __BORLANDC__
7af89395 1623 gs_findDataStruct.ff_name
c801d85f 1624#else
7af89395 1625 gs_findDataStruct.name
c801d85f 1626#endif
7af89395
VZ
1627 ;
1628 }
7af89395
VZ
1629
1630 return result;
f6bcfd97 1631#endif // __WIN32__
c801d85f
KB
1632}
1633
32e768ae 1634
7af89395 1635wxString wxFindNextFile()
c801d85f 1636{
7af89395 1637 wxString result;
3f4a0c5b 1638
7af89395
VZ
1639 // Find path only so we can concatenate found file onto path
1640 wxString path(wxPathOnly(gs_strFileSpec));
1641
1642try_again:
c801d85f
KB
1643
1644#ifdef __WIN32__
7af89395 1645 if (gs_hFileStruct == INVALID_HANDLE_VALUE)
59fcb8f8 1646 return result;
c801d85f 1647
7af89395
VZ
1648 bool success = (FindNextFile(gs_hFileStruct, &gs_findDataStruct) != 0);
1649 if (!success)
1650 {
1651 FindClose(gs_hFileStruct);
1652 gs_hFileStruct = INVALID_HANDLE_VALUE;
1653 }
1654 else
1655 {
1656 bool isdir = !!(gs_findDataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
c801d85f 1657
7af89395
VZ
1658 if (isdir && !(gs_findFlags & wxDIR))
1659 goto try_again;
1660 else if (!isdir && gs_findFlags && !(gs_findFlags & wxFILE))
1661 goto try_again;
c801d85f 1662
7af89395 1663 if ( !path.IsEmpty() )
223d09f6 1664 result << path << wxT('\\');
7af89395
VZ
1665 result << gs_findDataStruct.cFileName;
1666 }
1667
1668 return result;
1669#else // Win16
c801d85f
KB
1670
1671#ifdef __BORLANDC__
7af89395 1672 if (findnext(&gs_findDataStruct) == 0)
c801d85f 1673#else
7af89395 1674 if (_dos_findnext(&gs_findDataStruct) == 0)
c801d85f 1675#endif
7af89395
VZ
1676 {
1677 /* MATTHEW: [5] Check directory flag */
1678 char attrib;
c801d85f
KB
1679
1680#ifdef __BORLANDC__
7af89395 1681 attrib = gs_findDataStruct.ff_attrib;
c801d85f 1682#else
7af89395 1683 attrib = gs_findDataStruct.attrib;
c801d85f
KB
1684#endif
1685
7af89395
VZ
1686 if (attrib & _A_SUBDIR) {
1687 if (!(gs_findFlags & wxDIR))
1688 goto try_again;
1689 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1690 goto try_again;
c801d85f
KB
1691
1692
7af89395 1693 result +=
c801d85f 1694#ifdef __BORLANDC__
7af89395 1695 gs_findDataStruct.ff_name
c801d85f 1696#else
7af89395 1697 gs_findDataStruct.name
c801d85f 1698#endif
7af89395
VZ
1699 ;
1700 }
7af89395
VZ
1701
1702 return result;
f6bcfd97 1703#endif // Win32/16
c801d85f
KB
1704}
1705
32e768ae
DW
1706#elif defined(__WXPM__)
1707
1708wxString wxFindFirstFile(const wxChar *spec, int flags)
1709{
1710 wxString result;
1711
1712 /*
1713 // TODO: figure something out here for OS/2
1714 gs_strFileSpec = spec;
1715 gs_findFlags = flags;
1716
1717 // Find path only so we can concatenate found file onto path
1718 wxString path(wxPathOnly(gs_strFileSpec));
1719 if ( !path.IsEmpty() )
1720 result << path << wxT('\\');
1721
1722 int flag = _A_NORMAL;
1723 if (flags & wxDIR)
1724 flag = _A_SUBDIR;
1725
1726 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1727 {
1728 char attrib;
1729 attrib = gs_findDataStruct.attrib;
1730
1731 if (attrib & _A_SUBDIR) {
1732 if (!(gs_findFlags & wxDIR))
1733 return wxFindNextFile();
1734 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1735 return wxFindNextFile();
1736
1737 result += gs_findDataStruct.name;
1738 }
1739 */
1740 return result;
1741}
1742
1743wxString wxFindNextFile()
1744{
1745 wxString result;
1746 // TODO:
1747 return result;
1748}
1749
1750#endif // Unix/Windows/OS/2
c801d85f
KB
1751
1752// Get current working directory.
1753// If buf is NULL, allocates space using new, else
1754// copies into buf.
50920146 1755wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
c801d85f
KB
1756{
1757 if (!buf)
50920146
OK
1758 buf = new wxChar[sz+1];
1759#if wxUSE_UNICODE
1760 char *cbuf = new char[sz+1];
1761#ifdef _MSC_VER
1762 if (_getcwd(cbuf, sz) == NULL) {
e8e1d09e 1763#elif defined(__WXMAC__) && !defined(__DARWIN__)
f6bcfd97
BP
1764 enum
1765 {
1766 SFSaveDisk = 0x214, CurDirStore = 0x398
1767 };
1768 FSSpec cwdSpec ;
1769
1770 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1771 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1772 strcpy( buf , res ) ;
1773 if (0) {
50920146
OK
1774#else
1775 if (getcwd(cbuf, sz) == NULL) {
1776#endif
1777 delete [] cbuf;
7c74e7fe 1778#else // wxUnicode
3f4a0c5b 1779#ifdef _MSC_VER
c801d85f 1780 if (_getcwd(buf, sz) == NULL) {
e8e1d09e 1781#elif defined(__WXMAC__) && !defined(__DARWIN__)
19193a2c
KB
1782 FSSpec cwdSpec ;
1783 FCBPBRec pb;
1784 OSErr error;
1785 Str255 fileName ;
1786 pb.ioNamePtr = (StringPtr) &fileName;
1787 pb.ioVRefNum = 0;
1788 pb.ioRefNum = LMGetCurApRefNum();
1789 pb.ioFCBIndx = 0;
1790 error = PBGetFCBInfoSync(&pb);
1791 if ( error == noErr )
1792 {
1793 cwdSpec.vRefNum = pb.ioFCBVRefNum;
1794 cwdSpec.parID = pb.ioFCBParID;
1795 cwdSpec.name[0] = 0 ;
1796 wxString res = wxMacFSSpec2MacFilename( &cwdSpec ) ;
1797
1798 strcpy( buf , res ) ;
f056ea60 1799 buf[res.length()]=0 ;
19193a2c
KB
1800 }
1801 else
1802 buf[0] = 0 ;
1803 /*
1804 this version will not always give back the application directory on mac
1805 enum
1806 {
1807 SFSaveDisk = 0x214, CurDirStore = 0x398
1808 };
1809 FSSpec cwdSpec ;
1810
1811 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1812 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1813 strcpy( buf , res ) ;
1814 */
1815 if (0) {
1816#elif defined(__VISAGECPP__) || (defined (__OS2__) && defined (__WATCOMC__))
f6bcfd97
BP
1817 APIRET rc;
1818 rc = ::DosQueryCurrentDir( 0 // current drive
1819 ,buf
1820 ,(PULONG)&sz
1821 );
1822 if (rc != 0) {
c801d85f
KB
1823#else
1824 if (getcwd(buf, sz) == NULL) {
1825#endif
50920146 1826#endif
223d09f6
KB
1827 buf[0] = wxT('.');
1828 buf[1] = wxT('\0');
50920146
OK
1829 }
1830#if wxUSE_UNICODE
1831 else {
dcf924a3 1832 wxConvFile.MB2WC(buf, cbuf, sz);
50920146 1833 delete [] cbuf;
c801d85f 1834 }
50920146 1835#endif
c801d85f
KB
1836 return buf;
1837}
1838
7af89395
VZ
1839wxString wxGetCwd()
1840{
eac2aeb0
VZ
1841 static const size_t maxPathLen = 1024;
1842
1843 wxString str;
1844 wxGetWorkingDirectory(str.GetWriteBuf(maxPathLen), maxPathLen);
1845 str.UngetWriteBuf();
1846
1847 return str;
7af89395
VZ
1848}
1849
c801d85f
KB
1850bool wxSetWorkingDirectory(const wxString& d)
1851{
f6bcfd97 1852#if defined( __UNIX__ ) || defined( __WXMAC__ )
e90c1d2a 1853 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
f6bcfd97
BP
1854#elif defined(__WXPM__)
1855 return (::DosSetCurrentDir((PSZ)d.c_str()) == 0);
34138703 1856#elif defined(__WINDOWS__)
c801d85f
KB
1857
1858#ifdef __WIN32__
1859 return (bool)(SetCurrentDirectory(d) != 0);
1860#else
1861 // Must change drive, too.
1862 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1863 if (isDriveSpec)
1864 {
50920146 1865 wxChar firstChar = d[0];
c801d85f
KB
1866
1867 // To upper case
1868 if (firstChar > 90)
1869 firstChar = firstChar - 32;
1870
1871 // To a drive number
1872 unsigned int driveNo = firstChar - 64;
1873 if (driveNo > 0)
1874 {
1875 unsigned int noDrives;
1876 _dos_setdrive(driveNo, &noDrives);
1877 }
1878 }
1879 bool success = (chdir(WXSTRINGCAST d) == 0);
1880
1881 return success;
1882#endif
1883
1884#endif
1885}
1886
631f1bfe
JS
1887// Get the OS directory if appropriate (such as the Windows directory).
1888// On non-Windows platform, probably just return the empty string.
1889wxString wxGetOSDirectory()
1890{
04ef50df 1891#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
50920146 1892 wxChar buf[256];
631f1bfe
JS
1893 GetWindowsDirectory(buf, 256);
1894 return wxString(buf);
1895#else
1896 return wxEmptyString;
1897#endif
1898}
1899
a907da15 1900bool wxEndsWithPathSeparator(const wxChar *pszFileName)
c801d85f 1901{
a907da15 1902 size_t len = wxStrlen(pszFileName);
c801d85f
KB
1903 if ( len == 0 )
1904 return FALSE;
1905 else
1906 return wxIsPathSeparator(pszFileName[len - 1]);
1907}
1908
1909// find a file in a list of directories, returns false if not found
50920146 1910bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
c801d85f 1911{
a17e237f
VZ
1912 // we assume that it's not empty
1913 wxCHECK_MSG( !wxIsEmpty(pszFile), FALSE,
f6bcfd97 1914 _T("empty file name in wxFindFileInPath"));
a17e237f
VZ
1915
1916 // skip path separator in the beginning of the file name if present
1917 if ( wxIsPathSeparator(*pszFile) )
1918 pszFile++;
1919
1920 // copy the path (strtok will modify it)
1921 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1922 wxStrcpy(szPath, pszPath);
1923
1924 wxString strFile;
1925 wxChar *pc, *save_ptr;
1926 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1927 pc != NULL;
1928 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1929 {
1930 // search for the file in this directory
1931 strFile = pc;
1932 if ( !wxEndsWithPathSeparator(pc) )
1933 strFile += wxFILE_SEP_PATH;
1934 strFile += pszFile;
1935
1936 if ( FileExists(strFile) ) {
1937 *pStr = strFile;
1938 break;
1939 }
c801d85f 1940 }
c801d85f 1941
a17e237f
VZ
1942 // suppress warning about unused variable save_ptr when wxStrtok() is a
1943 // macro which throws away its third argument
1944 save_ptr = pc;
1945
1946 delete [] szPath;
c801d85f 1947
a17e237f 1948 return pc != NULL; // if true => we breaked from the loop
c801d85f
KB
1949}
1950
50920146 1951void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
3826db3e
VZ
1952 wxString *pstrPath,
1953 wxString *pstrName,
1954 wxString *pstrExt)
1955{
d37fd2fa 1956 // it can be empty, but it shouldn't be NULL
223d09f6 1957 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
3826db3e 1958
9e8d8607 1959 wxFileName::SplitPath(pszFileName, pstrPath, pstrName, pstrExt);
3826db3e 1960}
7f555861 1961
a47ce4a7
VS
1962time_t WXDLLEXPORT wxFileModificationTime(const wxString& filename)
1963{
f6bcfd97 1964 wxStructStat buf;
a47ce4a7 1965
f6bcfd97 1966 wxStat(filename.fn_str(), &buf);
a47ce4a7
VS
1967 return buf.st_mtime;
1968}
1969
1970
7f555861
JS
1971//------------------------------------------------------------------------
1972// wild character routines
1973//------------------------------------------------------------------------
1974
1975bool wxIsWild( const wxString& pattern )
1976{
1977 wxString tmp = pattern;
50920146 1978 wxChar *pat = WXSTRINGCAST(tmp);
7f555861 1979 while (*pat) {
3f4a0c5b 1980 switch (*pat++) {
223d09f6 1981 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
3f4a0c5b 1982 return TRUE;
223d09f6 1983 case wxT('\\'):
3f4a0c5b
VZ
1984 if (!*pat++)
1985 return FALSE;
1986 }
7f555861
JS
1987 }
1988 return FALSE;
1989};
1990
b112d152 1991bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
99cc00ed 1992
7be1f0d9 1993#if defined(HAVE_FNMATCH_H)
dfcb1ae0 1994{
50920146 1995// this probably won't work well for multibyte chars in Unicode mode?
b112d152 1996 if(dot_special)
50920146 1997 return fnmatch(pat.fn_str(), text.fn_str(), FNM_PERIOD) == 0;
b112d152 1998 else
50920146 1999 return fnmatch(pat.fn_str(), text.fn_str(), 0) == 0;
dfcb1ae0
KB
2000}
2001#else
2002
7be1f0d9
JS
2003// #pragma error Broken implementation of wxMatchWild() -- needs fixing!
2004
dfcb1ae0
KB
2005 /*
2006 * WARNING: this code is broken!
2007 */
7f555861
JS
2008{
2009 wxString tmp1 = pat;
50920146 2010 wxChar *pattern = WXSTRINGCAST(tmp1);
7f555861 2011 wxString tmp2 = text;
50920146
OK
2012 wxChar *str = WXSTRINGCAST(tmp2);
2013 wxChar c;
2014 wxChar *cp;
7f555861
JS
2015 bool done = FALSE, ret_code, ok;
2016 // Below is for vi fans
223d09f6 2017 const wxChar OB = wxT('{'), CB = wxT('}');
7f555861
JS
2018
2019 // dot_special means '.' only matches '.'
223d09f6 2020 if (dot_special && *str == wxT('.') && *pattern != *str)
3f4a0c5b 2021 return FALSE;
7f555861 2022
223d09f6
KB
2023 while ((*pattern != wxT('\0')) && (!done)
2024 && (((*str==wxT('\0'))&&((*pattern==OB)||(*pattern==wxT('*'))))||(*str!=wxT('\0')))) {
3f4a0c5b 2025 switch (*pattern) {
223d09f6 2026 case wxT('\\'):
3f4a0c5b 2027 pattern++;
223d09f6 2028 if (*pattern != wxT('\0'))
3f4a0c5b
VZ
2029 pattern++;
2030 break;
223d09f6 2031 case wxT('*'):
3f4a0c5b
VZ
2032 pattern++;
2033 ret_code = FALSE;
223d09f6 2034 while ((*str!=wxT('\0'))
33ac7e6f 2035 && ((ret_code=wxMatchWild(pattern, str++, FALSE)) == 0))
3f4a0c5b
VZ
2036 /*loop*/;
2037 if (ret_code) {
223d09f6 2038 while (*str != wxT('\0'))
3f4a0c5b 2039 str++;
223d09f6 2040 while (*pattern != wxT('\0'))
3f4a0c5b
VZ
2041 pattern++;
2042 }
2043 break;
223d09f6 2044 case wxT('['):
3f4a0c5b
VZ
2045 pattern++;
2046 repeat:
223d09f6 2047 if ((*pattern == wxT('\0')) || (*pattern == wxT(']'))) {
3f4a0c5b
VZ
2048 done = TRUE;
2049 break;
2050 }
223d09f6 2051 if (*pattern == wxT('\\')) {
3f4a0c5b 2052 pattern++;
223d09f6 2053 if (*pattern == wxT('\0')) {
3f4a0c5b
VZ
2054 done = TRUE;
2055 break;
2056 }
2057 }
223d09f6 2058 if (*(pattern + 1) == wxT('-')) {
3f4a0c5b
VZ
2059 c = *pattern;
2060 pattern += 2;
223d09f6 2061 if (*pattern == wxT(']')) {
3f4a0c5b
VZ
2062 done = TRUE;
2063 break;
2064 }
223d09f6 2065 if (*pattern == wxT('\\')) {
3f4a0c5b 2066 pattern++;
223d09f6 2067 if (*pattern == wxT('\0')) {
3f4a0c5b
VZ
2068 done = TRUE;
2069 break;
2070 }
2071 }
2072 if ((*str < c) || (*str > *pattern)) {
2073 pattern++;
2074 goto repeat;
2075 }
2076 } else if (*pattern != *str) {
2077 pattern++;
2078 goto repeat;
2079 }
2080 pattern++;
223d09f6
KB
2081 while ((*pattern != wxT(']')) && (*pattern != wxT('\0'))) {
2082 if ((*pattern == wxT('\\')) && (*(pattern + 1) != wxT('\0')))
3f4a0c5b
VZ
2083 pattern++;
2084 pattern++;
2085 }
223d09f6 2086 if (*pattern != wxT('\0')) {
3f4a0c5b
VZ
2087 pattern++, str++;
2088 }
2089 break;
223d09f6 2090 case wxT('?'):
3f4a0c5b
VZ
2091 pattern++;
2092 str++;
2093 break;
2094 case OB:
2095 pattern++;
223d09f6 2096 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
3f4a0c5b
VZ
2097 cp = str;
2098 ok = TRUE;
223d09f6
KB
2099 while (ok && (*cp != wxT('\0')) && (*pattern != wxT('\0'))
2100 && (*pattern != wxT(',')) && (*pattern != CB)) {
2101 if (*pattern == wxT('\\'))
3f4a0c5b
VZ
2102 pattern++;
2103 ok = (*pattern++ == *cp++);
2104 }
223d09f6 2105 if (*pattern == wxT('\0')) {
3f4a0c5b
VZ
2106 ok = FALSE;
2107 done = TRUE;
2108 break;
2109 } else if (ok) {
2110 str = cp;
223d09f6
KB
2111 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
2112 if (*++pattern == wxT('\\')) {
3f4a0c5b
VZ
2113 if (*++pattern == CB)
2114 pattern++;
2115 }
2116 }
2117 } else {
223d09f6
KB
2118 while (*pattern!=CB && *pattern!=wxT(',') && *pattern!=wxT('\0')) {
2119 if (*++pattern == wxT('\\')) {
2120 if (*++pattern == CB || *pattern == wxT(','))
3f4a0c5b
VZ
2121 pattern++;
2122 }
2123 }
2124 }
223d09f6 2125 if (*pattern != wxT('\0'))
3f4a0c5b
VZ
2126 pattern++;
2127 }
2128 break;
2129 default:
2130 if (*str == *pattern) {
2131 str++, pattern++;
2132 } else {
2133 done = TRUE;
2134 }
2135 }
7f555861 2136 }
223d09f6 2137 while (*pattern == wxT('*'))
3f4a0c5b 2138 pattern++;
223d09f6 2139 return ((*str == wxT('\0')) && (*pattern == wxT('\0')));
7f555861 2140};
fd3f686c 2141
dfcb1ae0 2142#endif
7f555861 2143
3f4a0c5b 2144#ifdef __VISUALC__
fd3f686c 2145 #pragma warning(default:4706) // assignment within conditional expression
53c6e7cc 2146#endif // VC++