1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filename.cpp
3 // Purpose: wxFileName - encapsulates a file path
4 // Author: Robert Roebling, Vadim Zeitlin
8 // Copyright: (c) 2000 Robert Roebling
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 Here are brief descriptions of the filename formats supported by this class:
15 wxPATH_UNIX: standard Unix format, used under Darwin as well, absolute file
17 /dir1/dir2/.../dirN/filename, "." and ".." stand for the
18 current and parent directory respectively, "~" is parsed as the
19 user HOME and "~username" as the HOME of that user
21 wxPATH_DOS: DOS/Windows format, absolute file names have the form:
22 drive:\dir1\dir2\...\dirN\filename.ext where drive is a single
23 letter. "." and ".." as for Unix but no "~".
25 There are also UNC names of the form \\share\fullpath
27 wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
29 volume:dir1:...:dirN:filename
30 and the relative file names are either
31 :dir1:...:dirN:filename
34 (although :filename works as well).
35 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
39 wxPATH_VMS: VMS native format, absolute file names have the form
40 <device>:[dir1.dir2.dir3]file.txt
42 <device>:[000000.dir1.dir2.dir3]file.txt
44 the <device> is the physical device (i.e. disk). 000000 is the
45 root directory on the device which can be omitted.
47 Note that VMS uses different separators unlike Unix:
48 : always after the device. If the path does not contain : than
49 the default (the device of the current directory) is assumed.
50 [ start of directory specification
51 . separator between directory and subdirectory
52 ] between directory and file
55 // ============================================================================
57 // ============================================================================
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
63 // For compilers that support precompilation, includes "wx.h".
64 #include "wx/wxprec.h"
72 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
74 #include "wx/dynarray.h"
81 #include "wx/filename.h"
82 #include "wx/private/filename.h"
83 #include "wx/tokenzr.h"
84 #include "wx/config.h" // for wxExpandEnvVars
85 #include "wx/dynlib.h"
88 #if defined(__WIN32__) && defined(__MINGW32__)
89 #include "wx/msw/gccpriv.h"
93 #include "wx/msw/private.h"
96 #if defined(__WXMAC__)
97 #include "wx/osx/private.h" // includes mac headers
100 // utime() is POSIX so should normally be available on all Unices
102 #include <sys/types.h>
104 #include <sys/stat.h>
114 #include <sys/types.h>
116 #include <sys/stat.h>
127 #include <sys/utime.h>
128 #include <sys/stat.h>
139 #define MAX_PATH _MAX_PATH
144 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
145 #endif // wxUSE_LONGLONG
148 // ----------------------------------------------------------------------------
150 // ----------------------------------------------------------------------------
152 // small helper class which opens and closes the file - we use it just to get
153 // a file handle for the given file name to pass it to some Win32 API function
154 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
165 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
167 m_hFile
= ::CreateFile
169 filename
.fn_str(), // name
170 mode
== Read
? GENERIC_READ
// access mask
172 FILE_SHARE_READ
| // sharing mode
173 FILE_SHARE_WRITE
, // (allow everything)
174 NULL
, // no secutity attr
175 OPEN_EXISTING
, // creation disposition
177 NULL
// no template file
180 if ( m_hFile
== INVALID_HANDLE_VALUE
)
183 wxLogSysError(_("Failed to open '%s' for reading"),
186 wxLogSysError(_("Failed to open '%s' for writing"),
193 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
195 if ( !::CloseHandle(m_hFile
) )
197 wxLogSysError(_("Failed to close file handle"));
202 // return true only if the file could be opened successfully
203 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
206 operator HANDLE() const { return m_hFile
; }
214 // ----------------------------------------------------------------------------
216 // ----------------------------------------------------------------------------
218 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
220 // convert between wxDateTime and FILETIME which is a 64-bit value representing
221 // the number of 100-nanosecond intervals since January 1, 1601.
223 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
225 FILETIME ftcopy
= ft
;
227 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
229 wxLogLastError(_T("FileTimeToLocalFileTime"));
233 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
235 wxLogLastError(_T("FileTimeToSystemTime"));
238 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
239 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
242 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
245 st
.wDay
= dt
.GetDay();
246 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
247 st
.wYear
= (WORD
)dt
.GetYear();
248 st
.wHour
= dt
.GetHour();
249 st
.wMinute
= dt
.GetMinute();
250 st
.wSecond
= dt
.GetSecond();
251 st
.wMilliseconds
= dt
.GetMillisecond();
254 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
256 wxLogLastError(_T("SystemTimeToFileTime"));
259 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
261 wxLogLastError(_T("LocalFileTimeToFileTime"));
265 #endif // wxUSE_DATETIME && __WIN32__
267 // return a string with the volume par
268 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
272 if ( !volume
.empty() )
274 format
= wxFileName::GetFormat(format
);
276 // Special Windows UNC paths hack, part 2: undo what we did in
277 // SplitPath() and make an UNC path if we have a drive which is not a
278 // single letter (hopefully the network shares can't be one letter only
279 // although I didn't find any authoritative docs on this)
280 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
282 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
284 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
286 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
294 // return true if the format used is the DOS/Windows one and the string looks
296 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
298 return format
== wxPATH_DOS
&&
299 path
.length() >= 4 && // "\\a" can't be a UNC path
300 path
[0u] == wxFILE_SEP_PATH_DOS
&&
301 path
[1u] == wxFILE_SEP_PATH_DOS
&&
302 path
[2u] != wxFILE_SEP_PATH_DOS
;
305 // ============================================================================
307 // ============================================================================
309 // ----------------------------------------------------------------------------
310 // wxFileName construction
311 // ----------------------------------------------------------------------------
313 void wxFileName::Assign( const wxFileName
&filepath
)
315 m_volume
= filepath
.GetVolume();
316 m_dirs
= filepath
.GetDirs();
317 m_name
= filepath
.GetName();
318 m_ext
= filepath
.GetExt();
319 m_relative
= filepath
.m_relative
;
320 m_hasExt
= filepath
.m_hasExt
;
323 void wxFileName::Assign(const wxString
& volume
,
324 const wxString
& path
,
325 const wxString
& name
,
330 // we should ignore paths which look like UNC shares because we already
331 // have the volume here and the UNC notation (\\server\path) is only valid
332 // for paths which don't start with a volume, so prevent SetPath() from
333 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
335 // note also that this is a rather ugly way to do what we want (passing
336 // some kind of flag telling to ignore UNC paths to SetPath() would be
337 // better) but this is the safest thing to do to avoid breaking backwards
338 // compatibility in 2.8
339 if ( IsUNCPath(path
, format
) )
341 // remove one of the 2 leading backslashes to ensure that it's not
342 // recognized as an UNC path by SetPath()
343 wxString
pathNonUNC(path
, 1, wxString::npos
);
344 SetPath(pathNonUNC
, format
);
346 else // no UNC complications
348 SetPath(path
, format
);
358 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
362 if ( pathOrig
.empty() )
370 format
= GetFormat( format
);
372 // 0) deal with possible volume part first
375 SplitVolume(pathOrig
, &volume
, &path
, format
);
376 if ( !volume
.empty() )
383 // 1) Determine if the path is relative or absolute.
384 wxChar leadingChar
= path
[0u];
389 m_relative
= leadingChar
== wxT(':');
391 // We then remove a leading ":". The reason is in our
392 // storage form for relative paths:
393 // ":dir:file.txt" actually means "./dir/file.txt" in
394 // DOS notation and should get stored as
395 // (relative) (dir) (file.txt)
396 // "::dir:file.txt" actually means "../dir/file.txt"
397 // stored as (relative) (..) (dir) (file.txt)
398 // This is important only for the Mac as an empty dir
399 // actually means <UP>, whereas under DOS, double
400 // slashes can be ignored: "\\\\" is the same as "\\".
406 // TODO: what is the relative path format here?
411 wxFAIL_MSG( _T("Unknown path format") );
412 // !! Fall through !!
415 // the paths of the form "~" or "~username" are absolute
416 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
420 m_relative
= !IsPathSeparator(leadingChar
, format
);
425 // 2) Break up the path into its members. If the original path
426 // was just "/" or "\\", m_dirs will be empty. We know from
427 // the m_relative field, if this means "nothing" or "root dir".
429 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
431 while ( tn
.HasMoreTokens() )
433 wxString token
= tn
.GetNextToken();
435 // Remove empty token under DOS and Unix, interpret them
439 if (format
== wxPATH_MAC
)
440 m_dirs
.Add( wxT("..") );
450 void wxFileName::Assign(const wxString
& fullpath
,
453 wxString volume
, path
, name
, ext
;
455 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
457 Assign(volume
, path
, name
, ext
, hasExt
, format
);
460 void wxFileName::Assign(const wxString
& fullpathOrig
,
461 const wxString
& fullname
,
464 // always recognize fullpath as directory, even if it doesn't end with a
466 wxString fullpath
= fullpathOrig
;
467 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
469 fullpath
+= GetPathSeparator(format
);
472 wxString volume
, path
, name
, ext
;
475 // do some consistency checks: the name should be really just the filename
476 // and the path should be really just a path
477 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
479 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
481 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
482 _T("the file name shouldn't contain the path") );
484 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
486 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
487 _T("the path shouldn't contain file name nor extension") );
489 Assign(volume
, path
, name
, ext
, hasExt
, format
);
492 void wxFileName::Assign(const wxString
& pathOrig
,
493 const wxString
& name
,
499 SplitVolume(pathOrig
, &volume
, &path
, format
);
501 Assign(volume
, path
, name
, ext
, format
);
504 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
506 Assign(dir
, wxEmptyString
, format
);
509 void wxFileName::Clear()
515 m_ext
= wxEmptyString
;
517 // we don't have any absolute path for now
525 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
527 return wxFileName(file
, format
);
531 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
534 fn
.AssignDir(dir
, format
);
538 // ----------------------------------------------------------------------------
540 // ----------------------------------------------------------------------------
542 bool wxFileName::FileExists() const
544 return wxFileName::FileExists( GetFullPath() );
547 bool wxFileName::FileExists( const wxString
&file
)
549 return ::wxFileExists( file
);
552 bool wxFileName::DirExists() const
554 return wxFileName::DirExists( GetPath() );
557 bool wxFileName::DirExists( const wxString
&dir
)
559 return ::wxDirExists( dir
);
562 // ----------------------------------------------------------------------------
563 // CWD and HOME stuff
564 // ----------------------------------------------------------------------------
566 void wxFileName::AssignCwd(const wxString
& volume
)
568 AssignDir(wxFileName::GetCwd(volume
));
572 wxString
wxFileName::GetCwd(const wxString
& volume
)
574 // if we have the volume, we must get the current directory on this drive
575 // and to do this we have to chdir to this volume - at least under Windows,
576 // I don't know how to get the current drive on another volume elsewhere
579 if ( !volume
.empty() )
582 SetCwd(volume
+ GetVolumeSeparator());
585 wxString cwd
= ::wxGetCwd();
587 if ( !volume
.empty() )
595 bool wxFileName::SetCwd() const
597 return wxFileName::SetCwd( GetPath() );
600 bool wxFileName::SetCwd( const wxString
&cwd
)
602 return ::wxSetWorkingDirectory( cwd
);
605 void wxFileName::AssignHomeDir()
607 AssignDir(wxFileName::GetHomeDir());
610 wxString
wxFileName::GetHomeDir()
612 return ::wxGetHomeDir();
616 // ----------------------------------------------------------------------------
617 // CreateTempFileName
618 // ----------------------------------------------------------------------------
620 #if wxUSE_FILE || wxUSE_FFILE
623 #if !defined wx_fdopen && defined HAVE_FDOPEN
624 #define wx_fdopen fdopen
627 // NB: GetTempFileName() under Windows creates the file, so using
628 // O_EXCL there would fail
630 #define wxOPEN_EXCL 0
632 #define wxOPEN_EXCL O_EXCL
636 #ifdef wxOpenOSFHandle
637 #define WX_HAVE_DELETE_ON_CLOSE
638 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
640 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
642 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
644 DWORD disposition
= OPEN_ALWAYS
;
646 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
647 FILE_FLAG_DELETE_ON_CLOSE
;
649 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
650 disposition
, attributes
, NULL
);
652 return wxOpenOSFHandle(h
, wxO_BINARY
);
654 #endif // wxOpenOSFHandle
657 // Helper to open the file
659 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
661 #ifdef WX_HAVE_DELETE_ON_CLOSE
663 return wxOpenWithDeleteOnClose(path
);
666 *deleteOnClose
= false;
668 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
673 // Helper to open the file and attach it to the wxFFile
675 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
678 *deleteOnClose
= false;
679 return file
->Open(path
, _T("w+b"));
681 int fd
= wxTempOpen(path
, deleteOnClose
);
684 file
->Attach(wx_fdopen(fd
, "w+b"));
685 return file
->IsOpened();
688 #endif // wxUSE_FFILE
692 #define WXFILEARGS(x, y) y
694 #define WXFILEARGS(x, y) x
696 #define WXFILEARGS(x, y) x, y
700 // Implementation of wxFileName::CreateTempFileName().
702 static wxString
wxCreateTempImpl(
703 const wxString
& prefix
,
704 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
705 bool *deleteOnClose
= NULL
)
707 #if wxUSE_FILE && wxUSE_FFILE
708 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
710 wxString path
, dir
, name
;
711 bool wantDeleteOnClose
= false;
715 // set the result to false initially
716 wantDeleteOnClose
= *deleteOnClose
;
717 *deleteOnClose
= false;
721 // easier if it alwasys points to something
722 deleteOnClose
= &wantDeleteOnClose
;
725 // use the directory specified by the prefix
726 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
730 dir
= wxFileName::GetTempDir();
733 #if defined(__WXWINCE__)
734 path
= dir
+ wxT("\\") + name
;
736 while (wxFileName::FileExists(path
))
738 path
= dir
+ wxT("\\") + name
;
743 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
744 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
745 wxStringBuffer(path
, MAX_PATH
+ 1)) )
747 wxLogLastError(_T("GetTempFileName"));
755 if ( !wxEndsWithPathSeparator(dir
) &&
756 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
758 path
+= wxFILE_SEP_PATH
;
763 #if defined(HAVE_MKSTEMP)
764 // scratch space for mkstemp()
765 path
+= _T("XXXXXX");
767 // we need to copy the path to the buffer in which mkstemp() can modify it
768 wxCharBuffer
buf(path
.fn_str());
770 // cast is safe because the string length doesn't change
771 int fdTemp
= mkstemp( (char*)(const char*) buf
);
774 // this might be not necessary as mkstemp() on most systems should have
775 // already done it but it doesn't hurt neither...
778 else // mkstemp() succeeded
780 path
= wxConvFile
.cMB2WX( (const char*) buf
);
783 // avoid leaking the fd
786 fileTemp
->Attach(fdTemp
);
795 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
797 ffileTemp
->Open(path
, _T("r+b"));
808 #else // !HAVE_MKSTEMP
812 path
+= _T("XXXXXX");
814 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
815 if ( !mktemp( (char*)(const char*) buf
) )
821 path
= wxConvFile
.cMB2WX( (const char*) buf
);
823 #else // !HAVE_MKTEMP (includes __DOS__)
824 // generate the unique file name ourselves
825 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
826 path
<< (unsigned int)getpid();
831 static const size_t numTries
= 1000;
832 for ( size_t n
= 0; n
< numTries
; n
++ )
834 // 3 hex digits is enough for numTries == 1000 < 4096
835 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
836 if ( !wxFileName::FileExists(pathTry
) )
845 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
847 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
849 #endif // Windows/!Windows
853 wxLogSysError(_("Failed to create a temporary file name"));
859 // open the file - of course, there is a race condition here, this is
860 // why we always prefer using mkstemp()...
862 if ( fileTemp
&& !fileTemp
->IsOpened() )
864 *deleteOnClose
= wantDeleteOnClose
;
865 int fd
= wxTempOpen(path
, deleteOnClose
);
867 fileTemp
->Attach(fd
);
874 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
876 *deleteOnClose
= wantDeleteOnClose
;
877 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
883 // FIXME: If !ok here should we loop and try again with another
884 // file name? That is the standard recourse if open(O_EXCL)
885 // fails, though of course it should be protected against
886 // possible infinite looping too.
888 wxLogError(_("Failed to open temporary file."));
898 static bool wxCreateTempImpl(
899 const wxString
& prefix
,
900 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
903 bool deleteOnClose
= true;
905 *name
= wxCreateTempImpl(prefix
,
906 WXFILEARGS(fileTemp
, ffileTemp
),
909 bool ok
= !name
->empty();
914 else if (ok
&& wxRemoveFile(*name
))
922 static void wxAssignTempImpl(
924 const wxString
& prefix
,
925 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
928 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
930 if ( tempname
.empty() )
932 // error, failed to get temp file name
937 fn
->Assign(tempname
);
942 void wxFileName::AssignTempFileName(const wxString
& prefix
)
944 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
948 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
950 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
953 #endif // wxUSE_FILE || wxUSE_FFILE
958 wxString
wxCreateTempFileName(const wxString
& prefix
,
962 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
965 bool wxCreateTempFile(const wxString
& prefix
,
969 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
972 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
974 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
979 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
981 return wxCreateTempFileName(prefix
, fileTemp
);
989 wxString
wxCreateTempFileName(const wxString
& prefix
,
993 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
996 bool wxCreateTempFile(const wxString
& prefix
,
1000 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1004 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1006 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1011 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1013 return wxCreateTempFileName(prefix
, fileTemp
);
1016 #endif // wxUSE_FFILE
1019 // ----------------------------------------------------------------------------
1020 // directory operations
1021 // ----------------------------------------------------------------------------
1023 // helper of GetTempDir(): check if the given directory exists and return it if
1024 // it does or an empty string otherwise
1028 wxString
CheckIfDirExists(const wxString
& dir
)
1030 return wxFileName::DirExists(dir
) ? dir
: wxString();
1033 } // anonymous namespace
1035 wxString
wxFileName::GetTempDir()
1037 // first try getting it from environment: this allows overriding the values
1038 // used by default if the user wants to create temporary files in another
1040 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1043 dir
= CheckIfDirExists(wxGetenv("TMP"));
1045 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1048 // if no environment variables are set, use the system default
1051 #if defined(__WXWINCE__)
1052 dir
= CheckIfDirExists(wxT("\\temp"));
1053 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1054 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1056 wxLogLastError(_T("GetTempPath"));
1058 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1059 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1060 #endif // systems with native way
1063 // fall back to hard coded value
1066 #ifdef __UNIX_LIKE__
1067 dir
= CheckIfDirExists("/tmp");
1069 #endif // __UNIX_LIKE__
1076 bool wxFileName::Mkdir( int perm
, int flags
) const
1078 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1081 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1083 if ( flags
& wxPATH_MKDIR_FULL
)
1085 // split the path in components
1086 wxFileName filename
;
1087 filename
.AssignDir(dir
);
1090 if ( filename
.HasVolume())
1092 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1095 wxArrayString dirs
= filename
.GetDirs();
1096 size_t count
= dirs
.GetCount();
1097 for ( size_t i
= 0; i
< count
; i
++ )
1099 if ( i
> 0 || filename
.IsAbsolute() )
1100 currPath
+= wxFILE_SEP_PATH
;
1101 currPath
+= dirs
[i
];
1103 if (!DirExists(currPath
))
1105 if (!wxMkdir(currPath
, perm
))
1107 // no need to try creating further directories
1117 return ::wxMkdir( dir
, perm
);
1120 bool wxFileName::Rmdir(int flags
) const
1122 return wxFileName::Rmdir( GetPath(), flags
);
1125 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1128 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1130 // SHFileOperation needs double null termination string
1131 // but without separator at the end of the path
1133 if ( path
.Last() == wxFILE_SEP_PATH
)
1137 SHFILEOPSTRUCT fileop
;
1138 wxZeroMemory(fileop
);
1139 fileop
.wFunc
= FO_DELETE
;
1140 fileop
.pFrom
= path
.fn_str();
1141 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1143 // FOF_NOERRORUI is not defined in WinCE
1144 fileop
.fFlags
|= FOF_NOERRORUI
;
1147 int ret
= SHFileOperation(&fileop
);
1150 // SHFileOperation may return non-Win32 error codes, so the error
1151 // message can be incorrect
1152 wxLogApiError(_T("SHFileOperation"), ret
);
1158 else if ( flags
& wxPATH_RMDIR_FULL
)
1160 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1161 #endif // !__WXMSW__
1164 if ( path
.Last() != wxFILE_SEP_PATH
)
1165 path
+= wxFILE_SEP_PATH
;
1169 if ( !d
.IsOpened() )
1174 // first delete all subdirectories
1175 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1178 wxFileName::Rmdir(path
+ filename
, flags
);
1179 cont
= d
.GetNext(&filename
);
1183 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1185 // delete all files too
1186 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1189 ::wxRemoveFile(path
+ filename
);
1190 cont
= d
.GetNext(&filename
);
1193 #endif // !__WXMSW__
1196 return ::wxRmdir(dir
);
1199 // ----------------------------------------------------------------------------
1200 // path normalization
1201 // ----------------------------------------------------------------------------
1203 bool wxFileName::Normalize(int flags
,
1204 const wxString
& cwd
,
1205 wxPathFormat format
)
1207 // deal with env vars renaming first as this may seriously change the path
1208 if ( flags
& wxPATH_NORM_ENV_VARS
)
1210 wxString pathOrig
= GetFullPath(format
);
1211 wxString path
= wxExpandEnvVars(pathOrig
);
1212 if ( path
!= pathOrig
)
1218 // the existing path components
1219 wxArrayString dirs
= GetDirs();
1221 // the path to prepend in front to make the path absolute
1224 format
= GetFormat(format
);
1226 // set up the directory to use for making the path absolute later
1227 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1231 curDir
.AssignCwd(GetVolume());
1233 else // cwd provided
1235 curDir
.AssignDir(cwd
);
1239 // handle ~ stuff under Unix only
1240 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
1242 if ( !dirs
.IsEmpty() )
1244 wxString dir
= dirs
[0u];
1245 if ( !dir
.empty() && dir
[0u] == _T('~') )
1247 // to make the path absolute use the home directory
1248 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1250 // if we are expanding the tilde, then this path
1251 // *should* be already relative (since we checked for
1252 // the tilde only in the first char of the first dir);
1253 // if m_relative==false, it's because it was initialized
1254 // from a string which started with /~; in that case
1255 // we reach this point but then need m_relative=true
1256 // for relative->absolute expansion later
1264 // transform relative path into abs one
1265 if ( curDir
.IsOk() )
1267 // this path may be relative because it doesn't have the volume name
1268 // and still have m_relative=true; in this case we shouldn't modify
1269 // our directory components but just set the current volume
1270 if ( !HasVolume() && curDir
.HasVolume() )
1272 SetVolume(curDir
.GetVolume());
1276 // yes, it was the case - we don't need curDir then
1281 // finally, prepend curDir to the dirs array
1282 wxArrayString dirsNew
= curDir
.GetDirs();
1283 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1285 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1286 // return for some reason an absolute path, then curDir maybe not be absolute!
1287 if ( curDir
.IsAbsolute(format
) )
1289 // we have prepended an absolute path and thus we are now an absolute
1293 // else if (flags & wxPATH_NORM_ABSOLUTE):
1294 // should we warn the user that we didn't manage to make the path absolute?
1297 // now deal with ".", ".." and the rest
1299 size_t count
= dirs
.GetCount();
1300 for ( size_t n
= 0; n
< count
; n
++ )
1302 wxString dir
= dirs
[n
];
1304 if ( flags
& wxPATH_NORM_DOTS
)
1306 if ( dir
== wxT(".") )
1312 if ( dir
== wxT("..") )
1314 if ( m_dirs
.IsEmpty() )
1316 wxLogError(_("The path '%s' contains too many \"..\"!"),
1317 GetFullPath().c_str());
1321 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1329 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1330 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1333 if (GetShortcutTarget(GetFullPath(format
), filename
))
1341 #if defined(__WIN32__)
1342 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1344 Assign(GetLongPath());
1348 // Change case (this should be kept at the end of the function, to ensure
1349 // that the path doesn't change any more after we normalize its case)
1350 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1352 m_volume
.MakeLower();
1356 // directory entries must be made lower case as well
1357 count
= m_dirs
.GetCount();
1358 for ( size_t i
= 0; i
< count
; i
++ )
1360 m_dirs
[i
].MakeLower();
1368 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1369 const wxString
& replacementFmtString
,
1370 wxPathFormat format
)
1372 // look into stringForm for the contents of the given environment variable
1374 if (envname
.empty() ||
1375 !wxGetEnv(envname
, &val
))
1380 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1381 // do not touch the file name and the extension
1383 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1384 stringForm
.Replace(val
, replacement
);
1386 // Now assign ourselves the modified path:
1387 Assign(stringForm
, GetFullName(), format
);
1393 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1395 wxString homedir
= wxGetHomeDir();
1396 if (homedir
.empty())
1399 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1400 // do not touch the file name and the extension
1402 stringForm
.Replace(homedir
, "~");
1404 // Now assign ourselves the modified path:
1405 Assign(stringForm
, GetFullName(), format
);
1410 // ----------------------------------------------------------------------------
1411 // get the shortcut target
1412 // ----------------------------------------------------------------------------
1414 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1415 // The .lnk file is a plain text file so it should be easy to
1416 // make it work. Hint from Google Groups:
1417 // "If you open up a lnk file, you'll see a
1418 // number, followed by a pound sign (#), followed by more text. The
1419 // number is the number of characters that follows the pound sign. The
1420 // characters after the pound sign are the command line (which _can_
1421 // include arguments) to be executed. Any path (e.g. \windows\program
1422 // files\myapp.exe) that includes spaces needs to be enclosed in
1423 // quotation marks."
1425 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1426 // The following lines are necessary under WinCE
1427 // #include "wx/msw/private.h"
1428 // #include <ole2.h>
1430 #if defined(__WXWINCE__)
1431 #include <shlguid.h>
1434 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1435 wxString
& targetFilename
,
1436 wxString
* arguments
) const
1438 wxString path
, file
, ext
;
1439 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1443 bool success
= false;
1445 // Assume it's not a shortcut if it doesn't end with lnk
1446 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1449 // create a ShellLink object
1450 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1451 IID_IShellLink
, (LPVOID
*) &psl
);
1453 if (SUCCEEDED(hres
))
1456 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1457 if (SUCCEEDED(hres
))
1459 WCHAR wsz
[MAX_PATH
];
1461 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1464 hres
= ppf
->Load(wsz
, 0);
1467 if (SUCCEEDED(hres
))
1470 // Wrong prototype in early versions
1471 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1472 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1474 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1476 targetFilename
= wxString(buf
);
1477 success
= (shortcutPath
!= targetFilename
);
1479 psl
->GetArguments(buf
, 2048);
1481 if (!args
.empty() && arguments
)
1493 #endif // __WIN32__ && !__WXWINCE__
1496 // ----------------------------------------------------------------------------
1497 // absolute/relative paths
1498 // ----------------------------------------------------------------------------
1500 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1502 // if our path doesn't start with a path separator, it's not an absolute
1507 if ( !GetVolumeSeparator(format
).empty() )
1509 // this format has volumes and an absolute path must have one, it's not
1510 // enough to have the full path to bean absolute file under Windows
1511 if ( GetVolume().empty() )
1518 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1520 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1522 // get cwd only once - small time saving
1523 wxString cwd
= wxGetCwd();
1524 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1525 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1527 bool withCase
= IsCaseSensitive(format
);
1529 // we can't do anything if the files live on different volumes
1530 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1536 // same drive, so we don't need our volume
1539 // remove common directories starting at the top
1540 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1541 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1544 fnBase
.m_dirs
.RemoveAt(0);
1547 // add as many ".." as needed
1548 size_t count
= fnBase
.m_dirs
.GetCount();
1549 for ( size_t i
= 0; i
< count
; i
++ )
1551 m_dirs
.Insert(wxT(".."), 0u);
1554 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1556 // a directory made relative with respect to itself is '.' under Unix
1557 // and DOS, by definition (but we don't have to insert "./" for the
1559 if ( m_dirs
.IsEmpty() && IsDir() )
1561 m_dirs
.Add(_T('.'));
1571 // ----------------------------------------------------------------------------
1572 // filename kind tests
1573 // ----------------------------------------------------------------------------
1575 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1577 wxFileName fn1
= *this,
1580 // get cwd only once - small time saving
1581 wxString cwd
= wxGetCwd();
1582 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1583 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1585 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1588 // TODO: compare inodes for Unix, this works even when filenames are
1589 // different but files are the same (symlinks) (VZ)
1595 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1597 // only Unix filenames are truely case-sensitive
1598 return GetFormat(format
) == wxPATH_UNIX
;
1602 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1604 // Inits to forbidden characters that are common to (almost) all platforms.
1605 wxString strForbiddenChars
= wxT("*?");
1607 // If asserts, wxPathFormat has been changed. In case of a new path format
1608 // addition, the following code might have to be updated.
1609 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1610 switch ( GetFormat(format
) )
1613 wxFAIL_MSG( wxT("Unknown path format") );
1614 // !! Fall through !!
1620 // On a Mac even names with * and ? are allowed (Tested with OS
1621 // 9.2.1 and OS X 10.2.5)
1622 strForbiddenChars
= wxEmptyString
;
1626 strForbiddenChars
+= wxT("\\/:\"<>|");
1633 return strForbiddenChars
;
1637 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1640 return wxEmptyString
;
1644 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1645 (GetFormat(format
) == wxPATH_VMS
) )
1647 sepVol
= wxFILE_SEP_DSK
;
1656 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1659 switch ( GetFormat(format
) )
1662 // accept both as native APIs do but put the native one first as
1663 // this is the one we use in GetFullPath()
1664 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1668 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1672 seps
= wxFILE_SEP_PATH_UNIX
;
1676 seps
= wxFILE_SEP_PATH_MAC
;
1680 seps
= wxFILE_SEP_PATH_VMS
;
1688 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1690 format
= GetFormat(format
);
1692 // under VMS the end of the path is ']', not the path separator used to
1693 // separate the components
1694 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1698 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1700 // wxString::Find() doesn't work as expected with NUL - it will always find
1701 // it, so test for it separately
1702 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1705 // ----------------------------------------------------------------------------
1706 // path components manipulation
1707 // ----------------------------------------------------------------------------
1709 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1713 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1718 const size_t len
= dir
.length();
1719 for ( size_t n
= 0; n
< len
; n
++ )
1721 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1723 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1732 void wxFileName::AppendDir( const wxString
& dir
)
1734 if ( IsValidDirComponent(dir
) )
1738 void wxFileName::PrependDir( const wxString
& dir
)
1743 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1745 if ( IsValidDirComponent(dir
) )
1746 m_dirs
.Insert(dir
, before
);
1749 void wxFileName::RemoveDir(size_t pos
)
1751 m_dirs
.RemoveAt(pos
);
1754 // ----------------------------------------------------------------------------
1756 // ----------------------------------------------------------------------------
1758 void wxFileName::SetFullName(const wxString
& fullname
)
1760 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1761 &m_name
, &m_ext
, &m_hasExt
);
1764 wxString
wxFileName::GetFullName() const
1766 wxString fullname
= m_name
;
1769 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1775 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1777 format
= GetFormat( format
);
1781 // return the volume with the path as well if requested
1782 if ( flags
& wxPATH_GET_VOLUME
)
1784 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1787 // the leading character
1792 fullpath
+= wxFILE_SEP_PATH_MAC
;
1797 fullpath
+= wxFILE_SEP_PATH_DOS
;
1801 wxFAIL_MSG( wxT("Unknown path format") );
1807 // normally the absolute file names start with a slash
1808 // with one exception: the ones like "~/foo.bar" don't
1810 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1812 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1818 // no leading character here but use this place to unset
1819 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1820 // as, if I understand correctly, there should never be a dot
1821 // before the closing bracket
1822 flags
&= ~wxPATH_GET_SEPARATOR
;
1825 if ( m_dirs
.empty() )
1827 // there is nothing more
1831 // then concatenate all the path components using the path separator
1832 if ( format
== wxPATH_VMS
)
1834 fullpath
+= wxT('[');
1837 const size_t dirCount
= m_dirs
.GetCount();
1838 for ( size_t i
= 0; i
< dirCount
; i
++ )
1843 if ( m_dirs
[i
] == wxT(".") )
1845 // skip appending ':', this shouldn't be done in this
1846 // case as "::" is interpreted as ".." under Unix
1850 // convert back from ".." to nothing
1851 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1852 fullpath
+= m_dirs
[i
];
1856 wxFAIL_MSG( wxT("Unexpected path format") );
1857 // still fall through
1861 fullpath
+= m_dirs
[i
];
1865 // TODO: What to do with ".." under VMS
1867 // convert back from ".." to nothing
1868 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1869 fullpath
+= m_dirs
[i
];
1873 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1874 fullpath
+= GetPathSeparator(format
);
1877 if ( format
== wxPATH_VMS
)
1879 fullpath
+= wxT(']');
1885 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1887 // we already have a function to get the path
1888 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1891 // now just add the file name and extension to it
1892 fullpath
+= GetFullName();
1897 // Return the short form of the path (returns identity on non-Windows platforms)
1898 wxString
wxFileName::GetShortPath() const
1900 wxString
path(GetFullPath());
1902 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1903 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
1907 if ( ::GetShortPathName
1910 wxStringBuffer(pathOut
, sz
),
1922 // Return the long form of the path (returns identity on non-Windows platforms)
1923 wxString
wxFileName::GetLongPath() const
1926 path
= GetFullPath();
1928 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1930 #if wxUSE_DYNLIB_CLASS
1931 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1933 // this is MT-safe as in the worst case we're going to resolve the function
1934 // twice -- but as the result is the same in both threads, it's ok
1935 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1936 if ( !s_pfnGetLongPathName
)
1938 static bool s_triedToLoad
= false;
1940 if ( !s_triedToLoad
)
1942 s_triedToLoad
= true;
1944 wxDynamicLibrary
dllKernel(_T("kernel32"));
1946 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1951 #endif // Unicode/ANSI
1953 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1955 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1956 dllKernel
.GetSymbol(GetLongPathName
);
1959 // note that kernel32.dll can be unloaded, it stays in memory
1960 // anyhow as all Win32 programs link to it and so it's safe to call
1961 // GetLongPathName() even after unloading it
1965 if ( s_pfnGetLongPathName
)
1967 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
1970 if ( (*s_pfnGetLongPathName
)
1973 wxStringBuffer(pathOut
, dwSize
),
1981 #endif // wxUSE_DYNLIB_CLASS
1983 // The OS didn't support GetLongPathName, or some other error.
1984 // We need to call FindFirstFile on each component in turn.
1986 WIN32_FIND_DATA findFileData
;
1990 pathOut
= GetVolume() +
1991 GetVolumeSeparator(wxPATH_DOS
) +
1992 GetPathSeparator(wxPATH_DOS
);
1994 pathOut
= wxEmptyString
;
1996 wxArrayString dirs
= GetDirs();
1997 dirs
.Add(GetFullName());
2001 size_t count
= dirs
.GetCount();
2002 for ( size_t i
= 0; i
< count
; i
++ )
2004 const wxString
& dir
= dirs
[i
];
2006 // We're using pathOut to collect the long-name path, but using a
2007 // temporary for appending the last path component which may be
2009 tmpPath
= pathOut
+ dir
;
2011 // We must not process "." or ".." here as they would be (unexpectedly)
2012 // replaced by the corresponding directory names so just leave them
2015 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2016 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2017 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2019 tmpPath
+= wxFILE_SEP_PATH
;
2024 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
2025 if (hFind
== INVALID_HANDLE_VALUE
)
2027 // Error: most likely reason is that path doesn't exist, so
2028 // append any unprocessed parts and return
2029 for ( i
+= 1; i
< count
; i
++ )
2030 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2035 pathOut
+= findFileData
.cFileName
;
2036 if ( (i
< (count
-1)) )
2037 pathOut
+= wxFILE_SEP_PATH
;
2043 #endif // Win32/!Win32
2048 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2050 if (format
== wxPATH_NATIVE
)
2052 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2053 format
= wxPATH_DOS
;
2054 #elif defined(__VMS)
2055 format
= wxPATH_VMS
;
2057 format
= wxPATH_UNIX
;
2063 #ifdef wxHAS_FILESYSTEM_VOLUMES
2066 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2068 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2070 wxString
vol(drive
);
2071 vol
+= wxFILE_SEP_DSK
;
2072 if ( flags
& wxPATH_GET_SEPARATOR
)
2073 vol
+= wxFILE_SEP_PATH
;
2078 #endif // wxHAS_FILESYSTEM_VOLUMES
2080 // ----------------------------------------------------------------------------
2081 // path splitting function
2082 // ----------------------------------------------------------------------------
2086 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2087 wxString
*pstrVolume
,
2089 wxPathFormat format
)
2091 format
= GetFormat(format
);
2093 wxString fullpath
= fullpathWithVolume
;
2095 // special Windows UNC paths hack: transform \\share\path into share:path
2096 if ( IsUNCPath(fullpath
, format
) )
2098 fullpath
.erase(0, 2);
2100 size_t posFirstSlash
=
2101 fullpath
.find_first_of(GetPathTerminators(format
));
2102 if ( posFirstSlash
!= wxString::npos
)
2104 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2106 // UNC paths are always absolute, right? (FIXME)
2107 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2111 // We separate the volume here
2112 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2114 wxString sepVol
= GetVolumeSeparator(format
);
2116 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2117 if ( posFirstColon
!= wxString::npos
)
2121 *pstrVolume
= fullpath
.Left(posFirstColon
);
2124 // remove the volume name and the separator from the full path
2125 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2130 *pstrPath
= fullpath
;
2134 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2135 wxString
*pstrVolume
,
2140 wxPathFormat format
)
2142 format
= GetFormat(format
);
2145 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2147 // find the positions of the last dot and last path separator in the path
2148 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2149 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2151 // check whether this dot occurs at the very beginning of a path component
2152 if ( (posLastDot
!= wxString::npos
) &&
2154 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2155 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
2157 // dot may be (and commonly -- at least under Unix -- is) the first
2158 // character of the filename, don't treat the entire filename as
2159 // extension in this case
2160 posLastDot
= wxString::npos
;
2163 // if we do have a dot and a slash, check that the dot is in the name part
2164 if ( (posLastDot
!= wxString::npos
) &&
2165 (posLastSlash
!= wxString::npos
) &&
2166 (posLastDot
< posLastSlash
) )
2168 // the dot is part of the path, not the start of the extension
2169 posLastDot
= wxString::npos
;
2172 // now fill in the variables provided by user
2175 if ( posLastSlash
== wxString::npos
)
2182 // take everything up to the path separator but take care to make
2183 // the path equal to something like '/', not empty, for the files
2184 // immediately under root directory
2185 size_t len
= posLastSlash
;
2187 // this rule does not apply to mac since we do not start with colons (sep)
2188 // except for relative paths
2189 if ( !len
&& format
!= wxPATH_MAC
)
2192 *pstrPath
= fullpath
.Left(len
);
2194 // special VMS hack: remove the initial bracket
2195 if ( format
== wxPATH_VMS
)
2197 if ( (*pstrPath
)[0u] == _T('[') )
2198 pstrPath
->erase(0, 1);
2205 // take all characters starting from the one after the last slash and
2206 // up to, but excluding, the last dot
2207 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2209 if ( posLastDot
== wxString::npos
)
2211 // take all until the end
2212 count
= wxString::npos
;
2214 else if ( posLastSlash
== wxString::npos
)
2218 else // have both dot and slash
2220 count
= posLastDot
- posLastSlash
- 1;
2223 *pstrName
= fullpath
.Mid(nStart
, count
);
2226 // finally deal with the extension here: we have an added complication that
2227 // extension may be empty (but present) as in "foo." where trailing dot
2228 // indicates the empty extension at the end -- and hence we must remember
2229 // that we have it independently of pstrExt
2230 if ( posLastDot
== wxString::npos
)
2240 // take everything after the dot
2242 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2249 void wxFileName::SplitPath(const wxString
& fullpath
,
2253 wxPathFormat format
)
2256 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2260 path
->Prepend(wxGetVolumeString(volume
, format
));
2265 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2267 wxFileName
fn(fullpath
);
2269 return fn
.GetFullPath();
2272 // ----------------------------------------------------------------------------
2274 // ----------------------------------------------------------------------------
2278 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2279 const wxDateTime
*dtMod
,
2280 const wxDateTime
*dtCreate
) const
2282 #if defined(__WIN32__)
2283 FILETIME ftAccess
, ftCreate
, ftWrite
;
2286 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2288 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2290 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2296 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2298 wxLogError(_("Setting directory access times is not supported "
2299 "under this OS version"));
2304 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2308 path
= GetFullPath();
2312 wxFileHandle
fh(path
, wxFileHandle::Write
, flags
);
2315 if ( ::SetFileTime(fh
,
2316 dtCreate
? &ftCreate
: NULL
,
2317 dtAccess
? &ftAccess
: NULL
,
2318 dtMod
? &ftWrite
: NULL
) )
2323 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2324 wxUnusedVar(dtCreate
);
2326 if ( !dtAccess
&& !dtMod
)
2328 // can't modify the creation time anyhow, don't try
2332 // if dtAccess or dtMod is not specified, use the other one (which must be
2333 // non NULL because of the test above) for both times
2335 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2336 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2337 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2341 #else // other platform
2342 wxUnusedVar(dtAccess
);
2344 wxUnusedVar(dtCreate
);
2347 wxLogSysError(_("Failed to modify file times for '%s'"),
2348 GetFullPath().c_str());
2353 bool wxFileName::Touch() const
2355 #if defined(__UNIX_LIKE__)
2356 // under Unix touching file is simple: just pass NULL to utime()
2357 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2362 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2365 #else // other platform
2366 wxDateTime dtNow
= wxDateTime::Now();
2368 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2372 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2374 wxDateTime
*dtCreate
) const
2376 #if defined(__WIN32__)
2377 // we must use different methods for the files and directories under
2378 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2379 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2382 FILETIME ftAccess
, ftCreate
, ftWrite
;
2385 // implemented in msw/dir.cpp
2386 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2387 FILETIME
*, FILETIME
*, FILETIME
*);
2389 // we should pass the path without the trailing separator to
2390 // wxGetDirectoryTimes()
2391 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2392 &ftAccess
, &ftCreate
, &ftWrite
);
2396 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2399 ok
= ::GetFileTime(fh
,
2400 dtCreate
? &ftCreate
: NULL
,
2401 dtAccess
? &ftAccess
: NULL
,
2402 dtMod
? &ftWrite
: NULL
) != 0;
2413 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2415 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2417 ConvertFileTimeToWx(dtMod
, ftWrite
);
2421 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2422 // no need to test for IsDir() here
2424 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2427 dtAccess
->Set(stBuf
.st_atime
);
2429 dtMod
->Set(stBuf
.st_mtime
);
2431 dtCreate
->Set(stBuf
.st_ctime
);
2435 #else // other platform
2436 wxUnusedVar(dtAccess
);
2438 wxUnusedVar(dtCreate
);
2441 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2442 GetFullPath().c_str());
2447 #endif // wxUSE_DATETIME
2450 // ----------------------------------------------------------------------------
2451 // file size functions
2452 // ----------------------------------------------------------------------------
2457 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2459 if (!wxFileExists(filename
))
2460 return wxInvalidSize
;
2462 #if defined(__WXPALMOS__)
2464 return wxInvalidSize
;
2465 #elif defined(__WIN32__)
2466 wxFileHandle
f(filename
, wxFileHandle::Read
);
2468 return wxInvalidSize
;
2470 DWORD lpFileSizeHigh
;
2471 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2472 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2473 return wxInvalidSize
;
2475 return wxULongLong(lpFileSizeHigh
, ret
);
2476 #else // ! __WIN32__
2478 #ifndef wxNEED_WX_UNISTD_H
2479 if (wxStat( filename
.fn_str() , &st
) != 0)
2481 if (wxStat( filename
, &st
) != 0)
2483 return wxInvalidSize
;
2484 return wxULongLong(st
.st_size
);
2489 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2490 const wxString
&nullsize
,
2493 static const double KILOBYTESIZE
= 1024.0;
2494 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2495 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2496 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2498 if (bs
== 0 || bs
== wxInvalidSize
)
2501 double bytesize
= bs
.ToDouble();
2502 if (bytesize
< KILOBYTESIZE
)
2503 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2504 if (bytesize
< MEGABYTESIZE
)
2505 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2506 if (bytesize
< GIGABYTESIZE
)
2507 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2508 if (bytesize
< TERABYTESIZE
)
2509 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2511 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2514 wxULongLong
wxFileName::GetSize() const
2516 return GetSize(GetFullPath());
2519 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2521 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2524 #endif // wxUSE_LONGLONG
2526 // ----------------------------------------------------------------------------
2527 // Mac-specific functions
2528 // ----------------------------------------------------------------------------
2530 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2535 class MacDefaultExtensionRecord
2538 MacDefaultExtensionRecord()
2544 // default copy ctor, assignment operator and dtor are ok
2546 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2550 m_creator
= creator
;
2558 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2560 bool gMacDefaultExtensionsInited
= false;
2562 #include "wx/arrimpl.cpp"
2564 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2566 MacDefaultExtensionArray gMacDefaultExtensions
;
2568 // load the default extensions
2569 const MacDefaultExtensionRecord gDefaults
[] =
2571 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2572 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2573 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2576 void MacEnsureDefaultExtensionsLoaded()
2578 if ( !gMacDefaultExtensionsInited
)
2580 // we could load the pc exchange prefs here too
2581 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2583 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2585 gMacDefaultExtensionsInited
= true;
2589 } // anonymous namespace
2591 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2594 FSCatalogInfo catInfo
;
2597 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2599 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2601 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2602 finfo
->fileType
= type
;
2603 finfo
->fileCreator
= creator
;
2604 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2611 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2614 FSCatalogInfo catInfo
;
2617 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2619 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2621 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2622 *type
= finfo
->fileType
;
2623 *creator
= finfo
->fileCreator
;
2630 bool wxFileName::MacSetDefaultTypeAndCreator()
2632 wxUint32 type
, creator
;
2633 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2636 return MacSetTypeAndCreator( type
, creator
) ;
2641 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2643 MacEnsureDefaultExtensionsLoaded() ;
2644 wxString extl
= ext
.Lower() ;
2645 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2647 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2649 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2650 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2657 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2659 MacEnsureDefaultExtensionsLoaded();
2660 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2661 gMacDefaultExtensions
.Add( rec
);
2664 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON