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