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"
80 #include "wx/filename.h"
81 #include "wx/private/filename.h"
82 #include "wx/tokenzr.h"
83 #include "wx/config.h" // for wxExpandEnvVars
84 #include "wx/dynlib.h"
86 #if defined(__WIN32__) && defined(__MINGW32__)
87 #include "wx/msw/gccpriv.h"
91 #include "wx/msw/private.h"
94 #if defined(__WXMAC__)
95 #include "wx/mac/private.h" // includes mac headers
98 // utime() is POSIX so should normally be available on all Unices
100 #include <sys/types.h>
102 #include <sys/stat.h>
112 #include <sys/types.h>
114 #include <sys/stat.h>
125 #include <sys/utime.h>
126 #include <sys/stat.h>
137 #define MAX_PATH _MAX_PATH
141 wxULongLong wxInvalidSize
= (unsigned)-1;
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
148 // small helper class which opens and closes the file - we use it just to get
149 // a file handle for the given file name to pass it to some Win32 API function
150 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
161 wxFileHandle(const wxString
& filename
, OpenMode mode
)
163 m_hFile
= ::CreateFile
166 mode
== Read
? GENERIC_READ
// access mask
168 FILE_SHARE_READ
| // sharing mode
169 FILE_SHARE_WRITE
, // (allow everything)
170 NULL
, // no secutity attr
171 OPEN_EXISTING
, // creation disposition
173 NULL
// no template file
176 if ( m_hFile
== INVALID_HANDLE_VALUE
)
178 wxLogSysError(_("Failed to open '%s' for %s"),
180 mode
== Read
? _("reading") : _("writing"));
186 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
188 if ( !::CloseHandle(m_hFile
) )
190 wxLogSysError(_("Failed to close file handle"));
195 // return true only if the file could be opened successfully
196 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
199 operator HANDLE() const { return m_hFile
; }
207 // ----------------------------------------------------------------------------
209 // ----------------------------------------------------------------------------
211 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
213 // convert between wxDateTime and FILETIME which is a 64-bit value representing
214 // the number of 100-nanosecond intervals since January 1, 1601.
216 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
218 FILETIME ftcopy
= ft
;
220 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
222 wxLogLastError(_T("FileTimeToLocalFileTime"));
226 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
228 wxLogLastError(_T("FileTimeToSystemTime"));
231 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
232 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
235 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
238 st
.wDay
= dt
.GetDay();
239 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
240 st
.wYear
= (WORD
)dt
.GetYear();
241 st
.wHour
= dt
.GetHour();
242 st
.wMinute
= dt
.GetMinute();
243 st
.wSecond
= dt
.GetSecond();
244 st
.wMilliseconds
= dt
.GetMillisecond();
247 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
249 wxLogLastError(_T("SystemTimeToFileTime"));
252 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
254 wxLogLastError(_T("LocalFileTimeToFileTime"));
258 #endif // wxUSE_DATETIME && __WIN32__
260 // return a string with the volume par
261 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
265 if ( !volume
.empty() )
267 format
= wxFileName::GetFormat(format
);
269 // Special Windows UNC paths hack, part 2: undo what we did in
270 // SplitPath() and make an UNC path if we have a drive which is not a
271 // single letter (hopefully the network shares can't be one letter only
272 // although I didn't find any authoritative docs on this)
273 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
275 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
277 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
279 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
287 // return true if the format used is the DOS/Windows one and the string looks
289 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
291 return format
== wxPATH_DOS
&&
292 path
.length() >= 4 && // "\\a" can't be a UNC path
293 path
[0u] == wxFILE_SEP_PATH_DOS
&&
294 path
[1u] == wxFILE_SEP_PATH_DOS
&&
295 path
[2u] != wxFILE_SEP_PATH_DOS
;
298 // ============================================================================
300 // ============================================================================
302 // ----------------------------------------------------------------------------
303 // wxFileName construction
304 // ----------------------------------------------------------------------------
306 void wxFileName::Assign( const wxFileName
&filepath
)
308 m_volume
= filepath
.GetVolume();
309 m_dirs
= filepath
.GetDirs();
310 m_name
= filepath
.GetName();
311 m_ext
= filepath
.GetExt();
312 m_relative
= filepath
.m_relative
;
313 m_hasExt
= filepath
.m_hasExt
;
316 void wxFileName::Assign(const wxString
& volume
,
317 const wxString
& path
,
318 const wxString
& name
,
323 // we should ignore paths which look like UNC shares because we already
324 // have the volume here and the UNC notation (\\server\path) is only valid
325 // for paths which don't start with a volume, so prevent SetPath() from
326 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
328 // note also that this is a rather ugly way to do what we want (passing
329 // some kind of flag telling to ignore UNC paths to SetPath() would be
330 // better) but this is the safest thing to do to avoid breaking backwards
331 // compatibility in 2.8
332 if ( IsUNCPath(path
, format
) )
334 // remove one of the 2 leading backslashes to ensure that it's not
335 // recognized as an UNC path by SetPath()
336 wxString
pathNonUNC(path
, 1, wxString::npos
);
337 SetPath(pathNonUNC
, format
);
339 else // no UNC complications
341 SetPath(path
, format
);
351 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
355 if ( pathOrig
.empty() )
363 format
= GetFormat( format
);
365 // 0) deal with possible volume part first
368 SplitVolume(pathOrig
, &volume
, &path
, format
);
369 if ( !volume
.empty() )
376 // 1) Determine if the path is relative or absolute.
377 wxChar leadingChar
= path
[0u];
382 m_relative
= leadingChar
== wxT(':');
384 // We then remove a leading ":". The reason is in our
385 // storage form for relative paths:
386 // ":dir:file.txt" actually means "./dir/file.txt" in
387 // DOS notation and should get stored as
388 // (relative) (dir) (file.txt)
389 // "::dir:file.txt" actually means "../dir/file.txt"
390 // stored as (relative) (..) (dir) (file.txt)
391 // This is important only for the Mac as an empty dir
392 // actually means <UP>, whereas under DOS, double
393 // slashes can be ignored: "\\\\" is the same as "\\".
399 // TODO: what is the relative path format here?
404 wxFAIL_MSG( _T("Unknown path format") );
405 // !! Fall through !!
408 // the paths of the form "~" or "~username" are absolute
409 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
413 m_relative
= !IsPathSeparator(leadingChar
, format
);
418 // 2) Break up the path into its members. If the original path
419 // was just "/" or "\\", m_dirs will be empty. We know from
420 // the m_relative field, if this means "nothing" or "root dir".
422 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
424 while ( tn
.HasMoreTokens() )
426 wxString token
= tn
.GetNextToken();
428 // Remove empty token under DOS and Unix, interpret them
432 if (format
== wxPATH_MAC
)
433 m_dirs
.Add( wxT("..") );
443 void wxFileName::Assign(const wxString
& fullpath
,
446 wxString volume
, path
, name
, ext
;
448 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
450 Assign(volume
, path
, name
, ext
, hasExt
, format
);
453 void wxFileName::Assign(const wxString
& fullpathOrig
,
454 const wxString
& fullname
,
457 // always recognize fullpath as directory, even if it doesn't end with a
459 wxString fullpath
= fullpathOrig
;
460 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
462 fullpath
+= GetPathSeparator(format
);
465 wxString volume
, path
, name
, ext
;
468 // do some consistency checks in debug mode: the name should be really just
469 // the filename and the path should be really just a path
471 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
473 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
475 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
476 _T("the file name shouldn't contain the path") );
478 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
480 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
481 _T("the path shouldn't contain file name nor extension") );
483 #else // !__WXDEBUG__
484 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
485 &name
, &ext
, &hasExt
, format
);
486 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
487 #endif // __WXDEBUG__/!__WXDEBUG__
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()
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
, 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
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
746 wxLogLastError(_T("GetTempFileName"));
754 if ( !wxEndsWithPathSeparator(dir
) &&
755 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
757 path
+= wxFILE_SEP_PATH
;
762 #if defined(HAVE_MKSTEMP)
763 // scratch space for mkstemp()
764 path
+= _T("XXXXXX");
766 // we need to copy the path to the buffer in which mkstemp() can modify it
767 wxCharBuffer
buf( wxConvFile
.cWX2MB( path
) );
769 // cast is safe because the string length doesn't change
770 int fdTemp
= mkstemp( (char*)(const char*) buf
);
773 // this might be not necessary as mkstemp() on most systems should have
774 // already done it but it doesn't hurt neither...
777 else // mkstemp() succeeded
779 path
= wxConvFile
.cMB2WX( (const char*) buf
);
782 // avoid leaking the fd
785 fileTemp
->Attach(fdTemp
);
794 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
796 ffileTemp
->Open(path
, _T("r+b"));
807 #else // !HAVE_MKSTEMP
811 path
+= _T("XXXXXX");
813 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
814 if ( !mktemp( (char*)(const char*) buf
) )
820 path
= wxConvFile
.cMB2WX( (const char*) buf
);
822 #else // !HAVE_MKTEMP (includes __DOS__)
823 // generate the unique file name ourselves
824 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
825 path
<< (unsigned int)getpid();
830 static const size_t numTries
= 1000;
831 for ( size_t n
= 0; n
< numTries
; n
++ )
833 // 3 hex digits is enough for numTries == 1000 < 4096
834 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
835 if ( !wxFileName::FileExists(pathTry
) )
844 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
846 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
848 #endif // Windows/!Windows
852 wxLogSysError(_("Failed to create a temporary file name"));
858 // open the file - of course, there is a race condition here, this is
859 // why we always prefer using mkstemp()...
861 if ( fileTemp
&& !fileTemp
->IsOpened() )
863 *deleteOnClose
= wantDeleteOnClose
;
864 int fd
= wxTempOpen(path
, deleteOnClose
);
866 fileTemp
->Attach(fd
);
873 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
875 *deleteOnClose
= wantDeleteOnClose
;
876 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
882 // FIXME: If !ok here should we loop and try again with another
883 // file name? That is the standard recourse if open(O_EXCL)
884 // fails, though of course it should be protected against
885 // possible infinite looping too.
887 wxLogError(_("Failed to open temporary file."));
897 static bool wxCreateTempImpl(
898 const wxString
& prefix
,
899 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
902 bool deleteOnClose
= true;
904 *name
= wxCreateTempImpl(prefix
,
905 WXFILEARGS(fileTemp
, ffileTemp
),
908 bool ok
= !name
->empty();
913 else if (ok
&& wxRemoveFile(*name
))
921 static void wxAssignTempImpl(
923 const wxString
& prefix
,
924 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
927 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
929 if ( tempname
.empty() )
931 // error, failed to get temp file name
936 fn
->Assign(tempname
);
941 void wxFileName::AssignTempFileName(const wxString
& prefix
)
943 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
947 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
949 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
952 #endif // wxUSE_FILE || wxUSE_FFILE
957 wxString
wxCreateTempFileName(const wxString
& prefix
,
961 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
964 bool wxCreateTempFile(const wxString
& prefix
,
968 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
971 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
973 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
978 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
980 return wxCreateTempFileName(prefix
, fileTemp
);
988 wxString
wxCreateTempFileName(const wxString
& prefix
,
992 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
995 bool wxCreateTempFile(const wxString
& prefix
,
999 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1003 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1005 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1010 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1012 return wxCreateTempFileName(prefix
, fileTemp
);
1015 #endif // wxUSE_FFILE
1018 // ----------------------------------------------------------------------------
1019 // directory operations
1020 // ----------------------------------------------------------------------------
1022 wxString
wxFileName::GetTempDir()
1025 dir
= wxGetenv(_T("TMPDIR"));
1028 dir
= wxGetenv(_T("TMP"));
1031 dir
= wxGetenv(_T("TEMP"));
1035 #if defined(__WXWINCE__)
1038 // FIXME. Create \temp dir?
1039 if (DirExists(wxT("\\temp")))
1040 dir
= wxT("\\temp");
1042 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1046 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1048 wxLogLastError(_T("GetTempPath"));
1053 // GetTempFileName() fails if we pass it an empty string
1062 #if defined(__DOS__) || defined(__OS2__)
1064 #elif defined(__WXMAC__)
1065 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1075 bool wxFileName::Mkdir( int perm
, int flags
)
1077 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1080 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1082 if ( flags
& wxPATH_MKDIR_FULL
)
1084 // split the path in components
1085 wxFileName filename
;
1086 filename
.AssignDir(dir
);
1089 if ( filename
.HasVolume())
1091 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1094 wxArrayString dirs
= filename
.GetDirs();
1095 size_t count
= dirs
.GetCount();
1096 for ( size_t i
= 0; i
< count
; i
++ )
1099 #if defined(__WXMAC__) && !defined(__DARWIN__)
1100 // relative pathnames are exactely the other way round under mac...
1101 !filename
.IsAbsolute()
1103 filename
.IsAbsolute()
1106 currPath
+= wxFILE_SEP_PATH
;
1107 currPath
+= dirs
[i
];
1109 if (!DirExists(currPath
))
1111 if (!wxMkdir(currPath
, perm
))
1113 // no need to try creating further directories
1123 return ::wxMkdir( dir
, perm
);
1126 bool wxFileName::Rmdir()
1128 return wxFileName::Rmdir( GetPath() );
1131 bool wxFileName::Rmdir( const wxString
&dir
)
1133 return ::wxRmdir( dir
);
1136 // ----------------------------------------------------------------------------
1137 // path normalization
1138 // ----------------------------------------------------------------------------
1140 bool wxFileName::Normalize(int flags
,
1141 const wxString
& cwd
,
1142 wxPathFormat format
)
1144 // deal with env vars renaming first as this may seriously change the path
1145 if ( flags
& wxPATH_NORM_ENV_VARS
)
1147 wxString pathOrig
= GetFullPath(format
);
1148 wxString path
= wxExpandEnvVars(pathOrig
);
1149 if ( path
!= pathOrig
)
1156 // the existing path components
1157 wxArrayString dirs
= GetDirs();
1159 // the path to prepend in front to make the path absolute
1162 format
= GetFormat(format
);
1164 // set up the directory to use for making the path absolute later
1165 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1169 curDir
.AssignCwd(GetVolume());
1171 else // cwd provided
1173 curDir
.AssignDir(cwd
);
1177 // handle ~ stuff under Unix only
1178 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
1180 if ( !dirs
.IsEmpty() )
1182 wxString dir
= dirs
[0u];
1183 if ( !dir
.empty() && dir
[0u] == _T('~') )
1185 // to make the path absolute use the home directory
1186 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1188 // if we are expanding the tilde, then this path
1189 // *should* be already relative (since we checked for
1190 // the tilde only in the first char of the first dir);
1191 // if m_relative==false, it's because it was initialized
1192 // from a string which started with /~; in that case
1193 // we reach this point but then need m_relative=true
1194 // for relative->absolute expansion later
1202 // transform relative path into abs one
1203 if ( curDir
.IsOk() )
1205 // this path may be relative because it doesn't have the volume name
1206 // and still have m_relative=true; in this case we shouldn't modify
1207 // our directory components but just set the current volume
1208 if ( !HasVolume() && curDir
.HasVolume() )
1210 SetVolume(curDir
.GetVolume());
1214 // yes, it was the case - we don't need curDir then
1219 // finally, prepend curDir to the dirs array
1220 wxArrayString dirsNew
= curDir
.GetDirs();
1221 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1223 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1224 // return for some reason an absolute path, then curDir maybe not be absolute!
1225 if ( curDir
.IsAbsolute(format
) )
1227 // we have prepended an absolute path and thus we are now an absolute
1231 // else if (flags & wxPATH_NORM_ABSOLUTE):
1232 // should we warn the user that we didn't manage to make the path absolute?
1235 // now deal with ".", ".." and the rest
1237 size_t count
= dirs
.GetCount();
1238 for ( size_t n
= 0; n
< count
; n
++ )
1240 wxString dir
= dirs
[n
];
1242 if ( flags
& wxPATH_NORM_DOTS
)
1244 if ( dir
== wxT(".") )
1250 if ( dir
== wxT("..") )
1252 if ( m_dirs
.IsEmpty() )
1254 wxLogError(_("The path '%s' contains too many \"..\"!"),
1255 GetFullPath().c_str());
1259 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1264 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1272 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1273 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1276 if (GetShortcutTarget(GetFullPath(format
), filename
))
1278 // Repeat this since we may now have a new path
1279 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1281 filename
.MakeLower();
1289 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1291 // VZ: expand env vars here too?
1293 m_volume
.MakeLower();
1298 #if defined(__WIN32__)
1299 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1301 Assign(GetLongPath());
1308 // ----------------------------------------------------------------------------
1309 // get the shortcut target
1310 // ----------------------------------------------------------------------------
1312 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1313 // The .lnk file is a plain text file so it should be easy to
1314 // make it work. Hint from Google Groups:
1315 // "If you open up a lnk file, you'll see a
1316 // number, followed by a pound sign (#), followed by more text. The
1317 // number is the number of characters that follows the pound sign. The
1318 // characters after the pound sign are the command line (which _can_
1319 // include arguments) to be executed. Any path (e.g. \windows\program
1320 // files\myapp.exe) that includes spaces needs to be enclosed in
1321 // quotation marks."
1323 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1324 // The following lines are necessary under WinCE
1325 // #include "wx/msw/private.h"
1326 // #include <ole2.h>
1328 #if defined(__WXWINCE__)
1329 #include <shlguid.h>
1332 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1333 wxString
& targetFilename
,
1334 wxString
* arguments
)
1336 wxString path
, file
, ext
;
1337 wxSplitPath(shortcutPath
, & path
, & file
, & ext
);
1341 bool success
= false;
1343 // Assume it's not a shortcut if it doesn't end with lnk
1344 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1347 // create a ShellLink object
1348 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1349 IID_IShellLink
, (LPVOID
*) &psl
);
1351 if (SUCCEEDED(hres
))
1354 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1355 if (SUCCEEDED(hres
))
1357 WCHAR wsz
[MAX_PATH
];
1359 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1362 hres
= ppf
->Load(wsz
, 0);
1365 if (SUCCEEDED(hres
))
1368 // Wrong prototype in early versions
1369 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1370 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1372 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1374 targetFilename
= wxString(buf
);
1375 success
= (shortcutPath
!= targetFilename
);
1377 psl
->GetArguments(buf
, 2048);
1379 if (!args
.empty() && arguments
)
1391 #endif // __WIN32__ && !__WXWINCE__
1394 // ----------------------------------------------------------------------------
1395 // absolute/relative paths
1396 // ----------------------------------------------------------------------------
1398 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1400 // if our path doesn't start with a path separator, it's not an absolute
1405 if ( !GetVolumeSeparator(format
).empty() )
1407 // this format has volumes and an absolute path must have one, it's not
1408 // enough to have the full path to bean absolute file under Windows
1409 if ( GetVolume().empty() )
1416 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1418 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1420 // get cwd only once - small time saving
1421 wxString cwd
= wxGetCwd();
1422 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1423 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1425 bool withCase
= IsCaseSensitive(format
);
1427 // we can't do anything if the files live on different volumes
1428 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1434 // same drive, so we don't need our volume
1437 // remove common directories starting at the top
1438 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1439 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1442 fnBase
.m_dirs
.RemoveAt(0);
1445 // add as many ".." as needed
1446 size_t count
= fnBase
.m_dirs
.GetCount();
1447 for ( size_t i
= 0; i
< count
; i
++ )
1449 m_dirs
.Insert(wxT(".."), 0u);
1452 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1454 // a directory made relative with respect to itself is '.' under Unix
1455 // and DOS, by definition (but we don't have to insert "./" for the
1457 if ( m_dirs
.IsEmpty() && IsDir() )
1459 m_dirs
.Add(_T('.'));
1469 // ----------------------------------------------------------------------------
1470 // filename kind tests
1471 // ----------------------------------------------------------------------------
1473 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1475 wxFileName fn1
= *this,
1478 // get cwd only once - small time saving
1479 wxString cwd
= wxGetCwd();
1480 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1481 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1483 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1486 // TODO: compare inodes for Unix, this works even when filenames are
1487 // different but files are the same (symlinks) (VZ)
1493 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1495 // only Unix filenames are truely case-sensitive
1496 return GetFormat(format
) == wxPATH_UNIX
;
1500 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1502 // Inits to forbidden characters that are common to (almost) all platforms.
1503 wxString strForbiddenChars
= wxT("*?");
1505 // If asserts, wxPathFormat has been changed. In case of a new path format
1506 // addition, the following code might have to be updated.
1507 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1508 switch ( GetFormat(format
) )
1511 wxFAIL_MSG( wxT("Unknown path format") );
1512 // !! Fall through !!
1518 // On a Mac even names with * and ? are allowed (Tested with OS
1519 // 9.2.1 and OS X 10.2.5)
1520 strForbiddenChars
= wxEmptyString
;
1524 strForbiddenChars
+= wxT("\\/:\"<>|");
1531 return strForbiddenChars
;
1535 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1538 return wxEmptyString
;
1542 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1543 (GetFormat(format
) == wxPATH_VMS
) )
1545 sepVol
= wxFILE_SEP_DSK
;
1554 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1557 switch ( GetFormat(format
) )
1560 // accept both as native APIs do but put the native one first as
1561 // this is the one we use in GetFullPath()
1562 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1566 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1570 seps
= wxFILE_SEP_PATH_UNIX
;
1574 seps
= wxFILE_SEP_PATH_MAC
;
1578 seps
= wxFILE_SEP_PATH_VMS
;
1586 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1588 format
= GetFormat(format
);
1590 // under VMS the end of the path is ']', not the path separator used to
1591 // separate the components
1592 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1596 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1598 // wxString::Find() doesn't work as expected with NUL - it will always find
1599 // it, so test for it separately
1600 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1603 // ----------------------------------------------------------------------------
1604 // path components manipulation
1605 // ----------------------------------------------------------------------------
1607 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1611 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1616 const size_t len
= dir
.length();
1617 for ( size_t n
= 0; n
< len
; n
++ )
1619 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1621 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1630 void wxFileName::AppendDir( const wxString
& dir
)
1632 if ( IsValidDirComponent(dir
) )
1636 void wxFileName::PrependDir( const wxString
& dir
)
1641 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1643 if ( IsValidDirComponent(dir
) )
1644 m_dirs
.Insert(dir
, before
);
1647 void wxFileName::RemoveDir(size_t pos
)
1649 m_dirs
.RemoveAt(pos
);
1652 // ----------------------------------------------------------------------------
1654 // ----------------------------------------------------------------------------
1656 void wxFileName::SetFullName(const wxString
& fullname
)
1658 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1659 &m_name
, &m_ext
, &m_hasExt
);
1662 wxString
wxFileName::GetFullName() const
1664 wxString fullname
= m_name
;
1667 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1673 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1675 format
= GetFormat( format
);
1679 // return the volume with the path as well if requested
1680 if ( flags
& wxPATH_GET_VOLUME
)
1682 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1685 // the leading character
1690 fullpath
+= wxFILE_SEP_PATH_MAC
;
1695 fullpath
+= wxFILE_SEP_PATH_DOS
;
1699 wxFAIL_MSG( wxT("Unknown path format") );
1705 // normally the absolute file names start with a slash
1706 // with one exception: the ones like "~/foo.bar" don't
1708 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1710 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1716 // no leading character here but use this place to unset
1717 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1718 // as, if I understand correctly, there should never be a dot
1719 // before the closing bracket
1720 flags
&= ~wxPATH_GET_SEPARATOR
;
1723 if ( m_dirs
.empty() )
1725 // there is nothing more
1729 // then concatenate all the path components using the path separator
1730 if ( format
== wxPATH_VMS
)
1732 fullpath
+= wxT('[');
1735 const size_t dirCount
= m_dirs
.GetCount();
1736 for ( size_t i
= 0; i
< dirCount
; i
++ )
1741 if ( m_dirs
[i
] == wxT(".") )
1743 // skip appending ':', this shouldn't be done in this
1744 // case as "::" is interpreted as ".." under Unix
1748 // convert back from ".." to nothing
1749 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1750 fullpath
+= m_dirs
[i
];
1754 wxFAIL_MSG( wxT("Unexpected path format") );
1755 // still fall through
1759 fullpath
+= m_dirs
[i
];
1763 // TODO: What to do with ".." under VMS
1765 // convert back from ".." to nothing
1766 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1767 fullpath
+= m_dirs
[i
];
1771 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1772 fullpath
+= GetPathSeparator(format
);
1775 if ( format
== wxPATH_VMS
)
1777 fullpath
+= wxT(']');
1783 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1785 // we already have a function to get the path
1786 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1789 // now just add the file name and extension to it
1790 fullpath
+= GetFullName();
1795 // Return the short form of the path (returns identity on non-Windows platforms)
1796 wxString
wxFileName::GetShortPath() const
1798 wxString
path(GetFullPath());
1800 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1801 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1805 if ( ::GetShortPathName
1808 wxStringBuffer(pathOut
, sz
),
1820 // Return the long form of the path (returns identity on non-Windows platforms)
1821 wxString
wxFileName::GetLongPath() const
1824 path
= GetFullPath();
1826 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1828 #if wxUSE_DYNAMIC_LOADER
1829 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1831 // this is MT-safe as in the worst case we're going to resolve the function
1832 // twice -- but as the result is the same in both threads, it's ok
1833 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1834 if ( !s_pfnGetLongPathName
)
1836 static bool s_triedToLoad
= false;
1838 if ( !s_triedToLoad
)
1840 s_triedToLoad
= true;
1842 wxDynamicLibrary
dllKernel(_T("kernel32"));
1844 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1849 #endif // Unicode/ANSI
1851 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1853 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1854 dllKernel
.GetSymbol(GetLongPathName
);
1857 // note that kernel32.dll can be unloaded, it stays in memory
1858 // anyhow as all Win32 programs link to it and so it's safe to call
1859 // GetLongPathName() even after unloading it
1863 if ( s_pfnGetLongPathName
)
1865 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1868 if ( (*s_pfnGetLongPathName
)
1871 wxStringBuffer(pathOut
, dwSize
),
1879 #endif // wxUSE_DYNAMIC_LOADER
1881 // The OS didn't support GetLongPathName, or some other error.
1882 // We need to call FindFirstFile on each component in turn.
1884 WIN32_FIND_DATA findFileData
;
1888 pathOut
= GetVolume() +
1889 GetVolumeSeparator(wxPATH_DOS
) +
1890 GetPathSeparator(wxPATH_DOS
);
1892 pathOut
= wxEmptyString
;
1894 wxArrayString dirs
= GetDirs();
1895 dirs
.Add(GetFullName());
1899 size_t count
= dirs
.GetCount();
1900 for ( size_t i
= 0; i
< count
; i
++ )
1902 // We're using pathOut to collect the long-name path, but using a
1903 // temporary for appending the last path component which may be
1905 tmpPath
= pathOut
+ dirs
[i
];
1907 if ( tmpPath
.empty() )
1910 // can't see this being necessary? MF
1911 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1913 // Can't pass a drive and root dir to FindFirstFile,
1914 // so continue to next dir
1915 tmpPath
+= wxFILE_SEP_PATH
;
1920 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1921 if (hFind
== INVALID_HANDLE_VALUE
)
1923 // Error: most likely reason is that path doesn't exist, so
1924 // append any unprocessed parts and return
1925 for ( i
+= 1; i
< count
; i
++ )
1926 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1931 pathOut
+= findFileData
.cFileName
;
1932 if ( (i
< (count
-1)) )
1933 pathOut
+= wxFILE_SEP_PATH
;
1939 #endif // Win32/!Win32
1944 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1946 if (format
== wxPATH_NATIVE
)
1948 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1949 format
= wxPATH_DOS
;
1950 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1951 format
= wxPATH_MAC
;
1952 #elif defined(__VMS)
1953 format
= wxPATH_VMS
;
1955 format
= wxPATH_UNIX
;
1961 // ----------------------------------------------------------------------------
1962 // path splitting function
1963 // ----------------------------------------------------------------------------
1967 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
1968 wxString
*pstrVolume
,
1970 wxPathFormat format
)
1972 format
= GetFormat(format
);
1974 wxString fullpath
= fullpathWithVolume
;
1976 // special Windows UNC paths hack: transform \\share\path into share:path
1977 if ( IsUNCPath(fullpath
, format
) )
1979 fullpath
.erase(0, 2);
1981 size_t posFirstSlash
=
1982 fullpath
.find_first_of(GetPathTerminators(format
));
1983 if ( posFirstSlash
!= wxString::npos
)
1985 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1987 // UNC paths are always absolute, right? (FIXME)
1988 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1992 // We separate the volume here
1993 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1995 wxString sepVol
= GetVolumeSeparator(format
);
1997 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1998 if ( posFirstColon
!= wxString::npos
)
2002 *pstrVolume
= fullpath
.Left(posFirstColon
);
2005 // remove the volume name and the separator from the full path
2006 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2011 *pstrPath
= fullpath
;
2015 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2016 wxString
*pstrVolume
,
2021 wxPathFormat format
)
2023 format
= GetFormat(format
);
2026 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2028 // find the positions of the last dot and last path separator in the path
2029 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2030 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2032 // check whether this dot occurs at the very beginning of a path component
2033 if ( (posLastDot
!= wxString::npos
) &&
2035 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2036 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
2038 // dot may be (and commonly -- at least under Unix -- is) the first
2039 // character of the filename, don't treat the entire filename as
2040 // extension in this case
2041 posLastDot
= wxString::npos
;
2044 // if we do have a dot and a slash, check that the dot is in the name part
2045 if ( (posLastDot
!= wxString::npos
) &&
2046 (posLastSlash
!= wxString::npos
) &&
2047 (posLastDot
< posLastSlash
) )
2049 // the dot is part of the path, not the start of the extension
2050 posLastDot
= wxString::npos
;
2053 // now fill in the variables provided by user
2056 if ( posLastSlash
== wxString::npos
)
2063 // take everything up to the path separator but take care to make
2064 // the path equal to something like '/', not empty, for the files
2065 // immediately under root directory
2066 size_t len
= posLastSlash
;
2068 // this rule does not apply to mac since we do not start with colons (sep)
2069 // except for relative paths
2070 if ( !len
&& format
!= wxPATH_MAC
)
2073 *pstrPath
= fullpath
.Left(len
);
2075 // special VMS hack: remove the initial bracket
2076 if ( format
== wxPATH_VMS
)
2078 if ( (*pstrPath
)[0u] == _T('[') )
2079 pstrPath
->erase(0, 1);
2086 // take all characters starting from the one after the last slash and
2087 // up to, but excluding, the last dot
2088 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2090 if ( posLastDot
== wxString::npos
)
2092 // take all until the end
2093 count
= wxString::npos
;
2095 else if ( posLastSlash
== wxString::npos
)
2099 else // have both dot and slash
2101 count
= posLastDot
- posLastSlash
- 1;
2104 *pstrName
= fullpath
.Mid(nStart
, count
);
2107 // finally deal with the extension here: we have an added complication that
2108 // extension may be empty (but present) as in "foo." where trailing dot
2109 // indicates the empty extension at the end -- and hence we must remember
2110 // that we have it independently of pstrExt
2111 if ( posLastDot
== wxString::npos
)
2121 // take everything after the dot
2123 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2130 void wxFileName::SplitPath(const wxString
& fullpath
,
2134 wxPathFormat format
)
2137 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2141 path
->Prepend(wxGetVolumeString(volume
, format
));
2145 // ----------------------------------------------------------------------------
2147 // ----------------------------------------------------------------------------
2151 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2152 const wxDateTime
*dtMod
,
2153 const wxDateTime
*dtCreate
)
2155 #if defined(__WIN32__)
2158 // VZ: please let me know how to do this if you can
2159 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
2163 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
2166 FILETIME ftAccess
, ftCreate
, ftWrite
;
2169 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2171 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2173 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2175 if ( ::SetFileTime(fh
,
2176 dtCreate
? &ftCreate
: NULL
,
2177 dtAccess
? &ftAccess
: NULL
,
2178 dtMod
? &ftWrite
: NULL
) )
2184 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2185 wxUnusedVar(dtCreate
);
2187 if ( !dtAccess
&& !dtMod
)
2189 // can't modify the creation time anyhow, don't try
2193 // if dtAccess or dtMod is not specified, use the other one (which must be
2194 // non NULL because of the test above) for both times
2196 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2197 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2198 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2202 #else // other platform
2203 wxUnusedVar(dtAccess
);
2205 wxUnusedVar(dtCreate
);
2208 wxLogSysError(_("Failed to modify file times for '%s'"),
2209 GetFullPath().c_str());
2214 bool wxFileName::Touch()
2216 #if defined(__UNIX_LIKE__)
2217 // under Unix touching file is simple: just pass NULL to utime()
2218 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2223 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2226 #else // other platform
2227 wxDateTime dtNow
= wxDateTime::Now();
2229 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2233 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2235 wxDateTime
*dtCreate
) const
2237 #if defined(__WIN32__)
2238 // we must use different methods for the files and directories under
2239 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2240 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2243 FILETIME ftAccess
, ftCreate
, ftWrite
;
2246 // implemented in msw/dir.cpp
2247 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2248 FILETIME
*, FILETIME
*, FILETIME
*);
2250 // we should pass the path without the trailing separator to
2251 // wxGetDirectoryTimes()
2252 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2253 &ftAccess
, &ftCreate
, &ftWrite
);
2257 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2260 ok
= ::GetFileTime(fh
,
2261 dtCreate
? &ftCreate
: NULL
,
2262 dtAccess
? &ftAccess
: NULL
,
2263 dtMod
? &ftWrite
: NULL
) != 0;
2274 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2276 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2278 ConvertFileTimeToWx(dtMod
, ftWrite
);
2282 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2283 // no need to test for IsDir() here
2285 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2288 dtAccess
->Set(stBuf
.st_atime
);
2290 dtMod
->Set(stBuf
.st_mtime
);
2292 dtCreate
->Set(stBuf
.st_ctime
);
2296 #else // other platform
2297 wxUnusedVar(dtAccess
);
2299 wxUnusedVar(dtCreate
);
2302 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2303 GetFullPath().c_str());
2308 #endif // wxUSE_DATETIME
2311 // ----------------------------------------------------------------------------
2312 // file size functions
2313 // ----------------------------------------------------------------------------
2316 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2318 if (!wxFileExists(filename
))
2319 return wxInvalidSize
;
2321 #if defined(__WXPALMOS__)
2323 return wxInvalidSize
;
2324 #elif defined(__WIN32__)
2325 wxFileHandle
f(filename
, wxFileHandle::Read
);
2327 return wxInvalidSize
;
2329 DWORD lpFileSizeHigh
;
2330 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2331 if (ret
== INVALID_FILE_SIZE
)
2332 return wxInvalidSize
;
2334 // compose the low-order and high-order byte sizes
2335 return wxULongLong(ret
| (lpFileSizeHigh
<< sizeof(WORD
)*2));
2337 #else // ! __WIN32__
2340 #ifndef wxNEED_WX_UNISTD_H
2341 if (wxStat( filename
.fn_str() , &st
) != 0)
2343 if (wxStat( filename
, &st
) != 0)
2345 return wxInvalidSize
;
2346 return wxULongLong(st
.st_size
);
2351 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2352 const wxString
&nullsize
,
2355 static const double KILOBYTESIZE
= 1024.0;
2356 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2357 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2358 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2360 if (bs
== 0 || bs
== wxInvalidSize
)
2363 double bytesize
= bs
.ToDouble();
2364 if (bytesize
< KILOBYTESIZE
)
2365 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2366 if (bytesize
< MEGABYTESIZE
)
2367 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2368 if (bytesize
< GIGABYTESIZE
)
2369 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2370 if (bytesize
< TERABYTESIZE
)
2371 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2373 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2376 wxULongLong
wxFileName::GetSize() const
2378 return GetSize(GetFullPath());
2381 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2383 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2387 // ----------------------------------------------------------------------------
2388 // Mac-specific functions
2389 // ----------------------------------------------------------------------------
2393 const short kMacExtensionMaxLength
= 16 ;
2394 class MacDefaultExtensionRecord
2397 MacDefaultExtensionRecord()
2400 m_type
= m_creator
= 0 ;
2402 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
2404 wxStrcpy( m_ext
, from
.m_ext
) ;
2405 m_type
= from
.m_type
;
2406 m_creator
= from
.m_creator
;
2408 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
2410 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
2411 m_ext
[kMacExtensionMaxLength
] = 0 ;
2413 m_creator
= creator
;
2415 wxChar m_ext
[kMacExtensionMaxLength
] ;
2420 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
2422 bool gMacDefaultExtensionsInited
= false ;
2424 #include "wx/arrimpl.cpp"
2426 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
2428 MacDefaultExtensionArray gMacDefaultExtensions
;
2430 // load the default extensions
2431 MacDefaultExtensionRecord gDefaults
[] =
2433 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2434 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2435 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2438 static void MacEnsureDefaultExtensionsLoaded()
2440 if ( !gMacDefaultExtensionsInited
)
2442 // we could load the pc exchange prefs here too
2443 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2445 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2447 gMacDefaultExtensionsInited
= true ;
2451 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2454 FSCatalogInfo catInfo
;
2457 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2459 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2461 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2462 finfo
->fileType
= type
;
2463 finfo
->fileCreator
= creator
;
2464 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2471 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2474 FSCatalogInfo catInfo
;
2477 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2479 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2481 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2482 *type
= finfo
->fileType
;
2483 *creator
= finfo
->fileCreator
;
2490 bool wxFileName::MacSetDefaultTypeAndCreator()
2492 wxUint32 type
, creator
;
2493 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2496 return MacSetTypeAndCreator( type
, creator
) ;
2501 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2503 MacEnsureDefaultExtensionsLoaded() ;
2504 wxString extl
= ext
.Lower() ;
2505 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2507 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2509 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2510 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2517 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2519 MacEnsureDefaultExtensionsLoaded() ;
2520 MacDefaultExtensionRecord rec
;
2522 rec
.m_creator
= creator
;
2523 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
2524 gMacDefaultExtensions
.Add( rec
) ;