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