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