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"
71 #include "wx/dynarray.h"
78 #include "wx/filename.h"
79 #include "wx/tokenzr.h"
80 #include "wx/config.h" // for wxExpandEnvVars
82 #include "wx/dynlib.h"
84 // For GetShort/LongPathName
86 #include "wx/msw/wrapwin.h"
87 #if defined(__MINGW32__)
88 #include "wx/msw/gccpriv.h"
93 #include "wx/msw/private.h"
96 #if defined(__WXMAC__)
97 #include "wx/mac/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
143 wxULongLong wxInvalidSize
= (unsigned)-1;
146 // ----------------------------------------------------------------------------
148 // ----------------------------------------------------------------------------
150 // small helper class which opens and closes the file - we use it just to get
151 // a file handle for the given file name to pass it to some Win32 API function
152 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
163 wxFileHandle(const wxString
& filename
, OpenMode mode
)
165 m_hFile
= ::CreateFile
168 mode
== Read
? GENERIC_READ
// access mask
170 FILE_SHARE_READ
| // sharing mode
171 FILE_SHARE_WRITE
, // (allow everything)
172 NULL
, // no secutity attr
173 OPEN_EXISTING
, // creation disposition
175 NULL
// no template file
178 if ( m_hFile
== INVALID_HANDLE_VALUE
)
180 wxLogSysError(_("Failed to open '%s' for %s"),
182 mode
== Read
? _("reading") : _("writing"));
188 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
190 if ( !::CloseHandle(m_hFile
) )
192 wxLogSysError(_("Failed to close file handle"));
197 // return true only if the file could be opened successfully
198 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
201 operator HANDLE() const { return m_hFile
; }
209 // ----------------------------------------------------------------------------
211 // ----------------------------------------------------------------------------
213 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
215 // convert between wxDateTime and FILETIME which is a 64-bit value representing
216 // the number of 100-nanosecond intervals since January 1, 1601.
218 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
220 FILETIME ftcopy
= ft
;
222 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
224 wxLogLastError(_T("FileTimeToLocalFileTime"));
228 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
230 wxLogLastError(_T("FileTimeToSystemTime"));
233 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
234 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
237 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
240 st
.wDay
= dt
.GetDay();
241 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
242 st
.wYear
= (WORD
)dt
.GetYear();
243 st
.wHour
= dt
.GetHour();
244 st
.wMinute
= dt
.GetMinute();
245 st
.wSecond
= dt
.GetSecond();
246 st
.wMilliseconds
= dt
.GetMillisecond();
249 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
251 wxLogLastError(_T("SystemTimeToFileTime"));
254 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
256 wxLogLastError(_T("LocalFileTimeToFileTime"));
260 #endif // wxUSE_DATETIME && __WIN32__
262 // return a string with the volume par
263 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
267 if ( !volume
.empty() )
269 format
= wxFileName::GetFormat(format
);
271 // Special Windows UNC paths hack, part 2: undo what we did in
272 // SplitPath() and make an UNC path if we have a drive which is not a
273 // single letter (hopefully the network shares can't be one letter only
274 // although I didn't find any authoritative docs on this)
275 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
277 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
279 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
281 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
289 // ============================================================================
291 // ============================================================================
293 // ----------------------------------------------------------------------------
294 // wxFileName construction
295 // ----------------------------------------------------------------------------
297 void wxFileName::Assign( const wxFileName
&filepath
)
299 m_volume
= filepath
.GetVolume();
300 m_dirs
= filepath
.GetDirs();
301 m_name
= filepath
.GetName();
302 m_ext
= filepath
.GetExt();
303 m_relative
= filepath
.m_relative
;
304 m_hasExt
= filepath
.m_hasExt
;
307 void wxFileName::Assign(const wxString
& volume
,
308 const wxString
& path
,
309 const wxString
& name
,
312 wxPathFormat format
)
314 SetPath( path
, format
);
323 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
327 if ( pathOrig
.empty() )
335 format
= GetFormat( format
);
337 // 0) deal with possible volume part first
340 SplitVolume(pathOrig
, &volume
, &path
, format
);
341 if ( !volume
.empty() )
348 // 1) Determine if the path is relative or absolute.
349 wxChar leadingChar
= path
[0u];
354 m_relative
= leadingChar
== wxT(':');
356 // We then remove a leading ":". The reason is in our
357 // storage form for relative paths:
358 // ":dir:file.txt" actually means "./dir/file.txt" in
359 // DOS notation and should get stored as
360 // (relative) (dir) (file.txt)
361 // "::dir:file.txt" actually means "../dir/file.txt"
362 // stored as (relative) (..) (dir) (file.txt)
363 // This is important only for the Mac as an empty dir
364 // actually means <UP>, whereas under DOS, double
365 // slashes can be ignored: "\\\\" is the same as "\\".
371 // TODO: what is the relative path format here?
376 wxFAIL_MSG( _T("Unknown path format") );
377 // !! Fall through !!
380 // the paths of the form "~" or "~username" are absolute
381 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
385 m_relative
= !IsPathSeparator(leadingChar
, format
);
390 // 2) Break up the path into its members. If the original path
391 // was just "/" or "\\", m_dirs will be empty. We know from
392 // the m_relative field, if this means "nothing" or "root dir".
394 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
396 while ( tn
.HasMoreTokens() )
398 wxString token
= tn
.GetNextToken();
400 // Remove empty token under DOS and Unix, interpret them
404 if (format
== wxPATH_MAC
)
405 m_dirs
.Add( wxT("..") );
415 void wxFileName::Assign(const wxString
& fullpath
,
418 wxString volume
, path
, name
, ext
;
420 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
422 Assign(volume
, path
, name
, ext
, hasExt
, format
);
425 void wxFileName::Assign(const wxString
& fullpathOrig
,
426 const wxString
& fullname
,
429 // always recognize fullpath as directory, even if it doesn't end with a
431 wxString fullpath
= fullpathOrig
;
432 if ( !wxEndsWithPathSeparator(fullpath
) )
434 fullpath
+= GetPathSeparator(format
);
437 wxString volume
, path
, name
, ext
;
440 // do some consistency checks in debug mode: the name should be really just
441 // the filename and the path should be really just a path
443 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
445 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
447 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
448 _T("the file name shouldn't contain the path") );
450 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
452 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
453 _T("the path shouldn't contain file name nor extension") );
455 #else // !__WXDEBUG__
456 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
457 &name
, &ext
, &hasExt
, format
);
458 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
459 #endif // __WXDEBUG__/!__WXDEBUG__
461 Assign(volume
, path
, name
, ext
, hasExt
, format
);
464 void wxFileName::Assign(const wxString
& pathOrig
,
465 const wxString
& name
,
471 SplitVolume(pathOrig
, &volume
, &path
, format
);
473 Assign(volume
, path
, name
, ext
, format
);
476 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
478 Assign(dir
, wxEmptyString
, format
);
481 void wxFileName::Clear()
487 m_ext
= wxEmptyString
;
489 // we don't have any absolute path for now
497 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
499 return wxFileName(file
, format
);
503 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
506 fn
.AssignDir(dir
, format
);
510 // ----------------------------------------------------------------------------
512 // ----------------------------------------------------------------------------
514 bool wxFileName::FileExists() const
516 return wxFileName::FileExists( GetFullPath() );
519 bool wxFileName::FileExists( const wxString
&file
)
521 return ::wxFileExists( file
);
524 bool wxFileName::DirExists() const
526 return wxFileName::DirExists( GetPath() );
529 bool wxFileName::DirExists( const wxString
&dir
)
531 return ::wxDirExists( dir
);
534 // ----------------------------------------------------------------------------
535 // CWD and HOME stuff
536 // ----------------------------------------------------------------------------
538 void wxFileName::AssignCwd(const wxString
& volume
)
540 AssignDir(wxFileName::GetCwd(volume
));
544 wxString
wxFileName::GetCwd(const wxString
& volume
)
546 // if we have the volume, we must get the current directory on this drive
547 // and to do this we have to chdir to this volume - at least under Windows,
548 // I don't know how to get the current drive on another volume elsewhere
551 if ( !volume
.empty() )
554 SetCwd(volume
+ GetVolumeSeparator());
557 wxString cwd
= ::wxGetCwd();
559 if ( !volume
.empty() )
567 bool wxFileName::SetCwd()
569 return wxFileName::SetCwd( GetPath() );
572 bool wxFileName::SetCwd( const wxString
&cwd
)
574 return ::wxSetWorkingDirectory( cwd
);
577 void wxFileName::AssignHomeDir()
579 AssignDir(wxFileName::GetHomeDir());
582 wxString
wxFileName::GetHomeDir()
584 return ::wxGetHomeDir();
589 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
591 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
592 if ( tempname
.empty() )
594 // error, failed to get temp file name
605 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
607 wxString path
, dir
, name
;
609 // use the directory specified by the prefix
610 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
614 dir
= wxGetenv(_T("TMPDIR"));
617 dir
= wxGetenv(_T("TMP"));
620 dir
= wxGetenv(_T("TEMP"));
625 #if defined(__WXWINCE__)
628 // FIXME. Create \temp dir?
629 if (DirExists(wxT("\\temp")))
632 path
= dir
+ wxT("\\") + name
;
634 while (FileExists(path
))
636 path
= dir
+ wxT("\\") + name
;
641 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
645 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
647 wxLogLastError(_T("GetTempPath"));
652 // GetTempFileName() fails if we pass it an empty string
656 else // we have a dir to create the file in
658 // ensure we use only the back slashes as GetTempFileName(), unlike all
659 // the other APIs, is picky and doesn't accept the forward ones
660 dir
.Replace(_T("/"), _T("\\"));
663 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
665 wxLogLastError(_T("GetTempFileName"));
674 #if defined(__DOS__) || defined(__OS2__)
676 #elif defined(__WXMAC__)
677 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
685 if ( !wxEndsWithPathSeparator(dir
) &&
686 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
688 path
+= wxFILE_SEP_PATH
;
693 #if defined(HAVE_MKSTEMP)
694 // scratch space for mkstemp()
695 path
+= _T("XXXXXX");
697 // we need to copy the path to the buffer in which mkstemp() can modify it
698 wxCharBuffer
buf( wxConvFile
.cWX2MB( path
) );
700 // cast is safe because the string length doesn't change
701 int fdTemp
= mkstemp( (char*)(const char*) buf
);
704 // this might be not necessary as mkstemp() on most systems should have
705 // already done it but it doesn't hurt neither...
708 else // mkstemp() succeeded
710 path
= wxConvFile
.cMB2WX( (const char*) buf
);
712 // avoid leaking the fd
715 fileTemp
->Attach(fdTemp
);
722 #else // !HAVE_MKSTEMP
726 path
+= _T("XXXXXX");
728 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
729 if ( !mktemp( (const char*) buf
) )
735 path
= wxConvFile
.cMB2WX( (const char*) buf
);
737 #else // !HAVE_MKTEMP (includes __DOS__)
738 // generate the unique file name ourselves
739 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
740 path
<< (unsigned int)getpid();
745 static const size_t numTries
= 1000;
746 for ( size_t n
= 0; n
< numTries
; n
++ )
748 // 3 hex digits is enough for numTries == 1000 < 4096
749 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
750 if ( !FileExists(pathTry
) )
759 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
761 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
763 #endif // Windows/!Windows
767 wxLogSysError(_("Failed to create a temporary file name"));
769 else if ( fileTemp
&& !fileTemp
->IsOpened() )
771 // open the file - of course, there is a race condition here, this is
772 // why we always prefer using mkstemp()...
774 // NB: GetTempFileName() under Windows creates the file, so using
775 // write_excl there would fail
776 if ( !fileTemp
->Open(path
,
777 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
782 wxS_IRUSR
| wxS_IWUSR
) )
784 // FIXME: If !ok here should we loop and try again with another
785 // file name? That is the standard recourse if open(O_EXCL)
786 // fails, though of course it should be protected against
787 // possible infinite looping too.
789 wxLogError(_("Failed to open temporary file."));
800 // ----------------------------------------------------------------------------
801 // directory operations
802 // ----------------------------------------------------------------------------
804 bool wxFileName::Mkdir( int perm
, int flags
)
806 return wxFileName::Mkdir(GetPath(), perm
, flags
);
809 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
811 if ( flags
& wxPATH_MKDIR_FULL
)
813 // split the path in components
815 filename
.AssignDir(dir
);
818 if ( filename
.HasVolume())
820 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
823 wxArrayString dirs
= filename
.GetDirs();
824 size_t count
= dirs
.GetCount();
825 for ( size_t i
= 0; i
< count
; i
++ )
828 #if defined(__WXMAC__) && !defined(__DARWIN__)
829 // relative pathnames are exactely the other way round under mac...
830 !filename
.IsAbsolute()
832 filename
.IsAbsolute()
835 currPath
+= wxFILE_SEP_PATH
;
838 if (!DirExists(currPath
))
840 if (!wxMkdir(currPath
, perm
))
842 // no need to try creating further directories
852 return ::wxMkdir( dir
, perm
);
855 bool wxFileName::Rmdir()
857 return wxFileName::Rmdir( GetPath() );
860 bool wxFileName::Rmdir( const wxString
&dir
)
862 return ::wxRmdir( dir
);
865 // ----------------------------------------------------------------------------
866 // path normalization
867 // ----------------------------------------------------------------------------
869 bool wxFileName::Normalize(int flags
,
873 // deal with env vars renaming first as this may seriously change the path
874 if ( flags
& wxPATH_NORM_ENV_VARS
)
876 wxString pathOrig
= GetFullPath(format
);
877 wxString path
= wxExpandEnvVars(pathOrig
);
878 if ( path
!= pathOrig
)
885 // the existing path components
886 wxArrayString dirs
= GetDirs();
888 // the path to prepend in front to make the path absolute
891 format
= GetFormat(format
);
893 // make the path absolute
894 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
898 curDir
.AssignCwd(GetVolume());
902 curDir
.AssignDir(cwd
);
905 // the path may be not absolute because it doesn't have the volume name
906 // but in this case we shouldn't modify the directory components of it
907 // but just set the current volume
908 if ( !HasVolume() && curDir
.HasVolume() )
910 SetVolume(curDir
.GetVolume());
914 // yes, it was the case - we don't need curDir then
920 // handle ~ stuff under Unix only
921 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
923 if ( !dirs
.IsEmpty() )
925 wxString dir
= dirs
[0u];
926 if ( !dir
.empty() && dir
[0u] == _T('~') )
928 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
935 // transform relative path into abs one
938 wxArrayString dirsNew
= curDir
.GetDirs();
939 size_t count
= dirs
.GetCount();
940 for ( size_t n
= 0; n
< count
; n
++ )
942 dirsNew
.Add(dirs
[n
]);
948 // now deal with ".", ".." and the rest
950 size_t count
= dirs
.GetCount();
951 for ( size_t n
= 0; n
< count
; n
++ )
953 wxString dir
= dirs
[n
];
955 if ( flags
& wxPATH_NORM_DOTS
)
957 if ( dir
== wxT(".") )
963 if ( dir
== wxT("..") )
965 if ( m_dirs
.IsEmpty() )
967 wxLogError(_("The path '%s' contains too many \"..\"!"),
968 GetFullPath().c_str());
972 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
977 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
985 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
986 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
989 if (GetShortcutTarget(GetFullPath(format
), filename
))
991 // Repeat this since we may now have a new path
992 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
994 filename
.MakeLower();
1002 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1004 // VZ: expand env vars here too?
1006 m_volume
.MakeLower();
1011 // we do have the path now
1013 // NB: need to do this before (maybe) calling Assign() below
1016 #if defined(__WIN32__)
1017 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1019 Assign(GetLongPath());
1026 // ----------------------------------------------------------------------------
1027 // get the shortcut target
1028 // ----------------------------------------------------------------------------
1030 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1031 // The .lnk file is a plain text file so it should be easy to
1032 // make it work. Hint from Google Groups:
1033 // "If you open up a lnk file, you'll see a
1034 // number, followed by a pound sign (#), followed by more text. The
1035 // number is the number of characters that follows the pound sign. The
1036 // characters after the pound sign are the command line (which _can_
1037 // include arguments) to be executed. Any path (e.g. \windows\program
1038 // files\myapp.exe) that includes spaces needs to be enclosed in
1039 // quotation marks."
1041 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1042 // The following lines are necessary under WinCE
1043 // #include "wx/msw/private.h"
1044 // #include <ole2.h>
1046 #if defined(__WXWINCE__)
1047 #include <shlguid.h>
1050 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1051 wxString
& targetFilename
,
1052 wxString
* arguments
)
1054 wxString path
, file
, ext
;
1055 wxSplitPath(shortcutPath
, & path
, & file
, & ext
);
1059 bool success
= false;
1061 // Assume it's not a shortcut if it doesn't end with lnk
1062 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1065 // create a ShellLink object
1066 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1067 IID_IShellLink
, (LPVOID
*) &psl
);
1069 if (SUCCEEDED(hres
))
1072 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1073 if (SUCCEEDED(hres
))
1075 WCHAR wsz
[MAX_PATH
];
1077 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1080 hres
= ppf
->Load(wsz
, 0);
1083 if (SUCCEEDED(hres
))
1086 // Wrong prototype in early versions
1087 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1088 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1090 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1092 targetFilename
= wxString(buf
);
1093 success
= (shortcutPath
!= targetFilename
);
1095 psl
->GetArguments(buf
, 2048);
1097 if (!args
.empty() && arguments
)
1109 #endif // __WIN32__ && !__WXWINCE__
1112 // ----------------------------------------------------------------------------
1113 // absolute/relative paths
1114 // ----------------------------------------------------------------------------
1116 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1118 // if our path doesn't start with a path separator, it's not an absolute
1123 if ( !GetVolumeSeparator(format
).empty() )
1125 // this format has volumes and an absolute path must have one, it's not
1126 // enough to have the full path to bean absolute file under Windows
1127 if ( GetVolume().empty() )
1134 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1136 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1138 // get cwd only once - small time saving
1139 wxString cwd
= wxGetCwd();
1140 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1141 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1143 bool withCase
= IsCaseSensitive(format
);
1145 // we can't do anything if the files live on different volumes
1146 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1152 // same drive, so we don't need our volume
1155 // remove common directories starting at the top
1156 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1157 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1160 fnBase
.m_dirs
.RemoveAt(0);
1163 // add as many ".." as needed
1164 size_t count
= fnBase
.m_dirs
.GetCount();
1165 for ( size_t i
= 0; i
< count
; i
++ )
1167 m_dirs
.Insert(wxT(".."), 0u);
1170 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1172 // a directory made relative with respect to itself is '.' under Unix
1173 // and DOS, by definition (but we don't have to insert "./" for the
1175 if ( m_dirs
.IsEmpty() && IsDir() )
1177 m_dirs
.Add(_T('.'));
1187 // ----------------------------------------------------------------------------
1188 // filename kind tests
1189 // ----------------------------------------------------------------------------
1191 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1193 wxFileName fn1
= *this,
1196 // get cwd only once - small time saving
1197 wxString cwd
= wxGetCwd();
1198 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1199 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1201 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1204 // TODO: compare inodes for Unix, this works even when filenames are
1205 // different but files are the same (symlinks) (VZ)
1211 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1213 // only Unix filenames are truely case-sensitive
1214 return GetFormat(format
) == wxPATH_UNIX
;
1218 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1220 // Inits to forbidden characters that are common to (almost) all platforms.
1221 wxString strForbiddenChars
= wxT("*?");
1223 // If asserts, wxPathFormat has been changed. In case of a new path format
1224 // addition, the following code might have to be updated.
1225 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1226 switch ( GetFormat(format
) )
1229 wxFAIL_MSG( wxT("Unknown path format") );
1230 // !! Fall through !!
1236 // On a Mac even names with * and ? are allowed (Tested with OS
1237 // 9.2.1 and OS X 10.2.5)
1238 strForbiddenChars
= wxEmptyString
;
1242 strForbiddenChars
+= wxT("\\/:\"<>|");
1249 return strForbiddenChars
;
1253 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1256 return wxEmptyString
;
1260 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1261 (GetFormat(format
) == wxPATH_VMS
) )
1263 sepVol
= wxFILE_SEP_DSK
;
1272 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1275 switch ( GetFormat(format
) )
1278 // accept both as native APIs do but put the native one first as
1279 // this is the one we use in GetFullPath()
1280 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1284 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1288 seps
= wxFILE_SEP_PATH_UNIX
;
1292 seps
= wxFILE_SEP_PATH_MAC
;
1296 seps
= wxFILE_SEP_PATH_VMS
;
1304 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1306 format
= GetFormat(format
);
1308 // under VMS the end of the path is ']', not the path separator used to
1309 // separate the components
1310 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1314 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1316 // wxString::Find() doesn't work as expected with NUL - it will always find
1317 // it, so test for it separately
1318 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1321 // ----------------------------------------------------------------------------
1322 // path components manipulation
1323 // ----------------------------------------------------------------------------
1325 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1329 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1334 const size_t len
= dir
.length();
1335 for ( size_t n
= 0; n
< len
; n
++ )
1337 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1339 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1348 void wxFileName::AppendDir( const wxString
& dir
)
1350 if ( IsValidDirComponent(dir
) )
1354 void wxFileName::PrependDir( const wxString
& dir
)
1359 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1361 if ( IsValidDirComponent(dir
) )
1362 m_dirs
.Insert(dir
, before
);
1365 void wxFileName::RemoveDir(size_t pos
)
1367 m_dirs
.RemoveAt(pos
);
1370 // ----------------------------------------------------------------------------
1372 // ----------------------------------------------------------------------------
1374 void wxFileName::SetFullName(const wxString
& fullname
)
1376 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1377 &m_name
, &m_ext
, &m_hasExt
);
1380 wxString
wxFileName::GetFullName() const
1382 wxString fullname
= m_name
;
1385 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1391 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1393 format
= GetFormat( format
);
1397 // return the volume with the path as well if requested
1398 if ( flags
& wxPATH_GET_VOLUME
)
1400 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1403 // the leading character
1408 fullpath
+= wxFILE_SEP_PATH_MAC
;
1413 fullpath
+= wxFILE_SEP_PATH_DOS
;
1417 wxFAIL_MSG( wxT("Unknown path format") );
1423 // normally the absolute file names start with a slash
1424 // with one exception: the ones like "~/foo.bar" don't
1426 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1428 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1434 // no leading character here but use this place to unset
1435 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1436 // as, if I understand correctly, there should never be a dot
1437 // before the closing bracket
1438 flags
&= ~wxPATH_GET_SEPARATOR
;
1441 if ( m_dirs
.empty() )
1443 // there is nothing more
1447 // then concatenate all the path components using the path separator
1448 if ( format
== wxPATH_VMS
)
1450 fullpath
+= wxT('[');
1453 const size_t dirCount
= m_dirs
.GetCount();
1454 for ( size_t i
= 0; i
< dirCount
; i
++ )
1459 if ( m_dirs
[i
] == wxT(".") )
1461 // skip appending ':', this shouldn't be done in this
1462 // case as "::" is interpreted as ".." under Unix
1466 // convert back from ".." to nothing
1467 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1468 fullpath
+= m_dirs
[i
];
1472 wxFAIL_MSG( wxT("Unexpected path format") );
1473 // still fall through
1477 fullpath
+= m_dirs
[i
];
1481 // TODO: What to do with ".." under VMS
1483 // convert back from ".." to nothing
1484 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1485 fullpath
+= m_dirs
[i
];
1489 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1490 fullpath
+= GetPathSeparator(format
);
1493 if ( format
== wxPATH_VMS
)
1495 fullpath
+= wxT(']');
1501 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1503 // we already have a function to get the path
1504 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1507 // now just add the file name and extension to it
1508 fullpath
+= GetFullName();
1513 // Return the short form of the path (returns identity on non-Windows platforms)
1514 wxString
wxFileName::GetShortPath() const
1516 wxString
path(GetFullPath());
1518 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1519 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1523 if ( ::GetShortPathName
1526 wxStringBuffer(pathOut
, sz
),
1538 // Return the long form of the path (returns identity on non-Windows platforms)
1539 wxString
wxFileName::GetLongPath() const
1542 path
= GetFullPath();
1544 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1546 #if wxUSE_DYNAMIC_LOADER
1547 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1549 // this is MT-safe as in the worst case we're going to resolve the function
1550 // twice -- but as the result is the same in both threads, it's ok
1551 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1552 if ( !s_pfnGetLongPathName
)
1554 static bool s_triedToLoad
= false;
1556 if ( !s_triedToLoad
)
1558 s_triedToLoad
= true;
1560 wxDynamicLibrary
dllKernel(_T("kernel32"));
1562 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1567 #endif // Unicode/ANSI
1569 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1571 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1572 dllKernel
.GetSymbol(GetLongPathName
);
1575 // note that kernel32.dll can be unloaded, it stays in memory
1576 // anyhow as all Win32 programs link to it and so it's safe to call
1577 // GetLongPathName() even after unloading it
1581 if ( s_pfnGetLongPathName
)
1583 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1586 if ( (*s_pfnGetLongPathName
)
1589 wxStringBuffer(pathOut
, dwSize
),
1597 #endif // wxUSE_DYNAMIC_LOADER
1599 // The OS didn't support GetLongPathName, or some other error.
1600 // We need to call FindFirstFile on each component in turn.
1602 WIN32_FIND_DATA findFileData
;
1606 pathOut
= GetVolume() +
1607 GetVolumeSeparator(wxPATH_DOS
) +
1608 GetPathSeparator(wxPATH_DOS
);
1610 pathOut
= wxEmptyString
;
1612 wxArrayString dirs
= GetDirs();
1613 dirs
.Add(GetFullName());
1617 size_t count
= dirs
.GetCount();
1618 for ( size_t i
= 0; i
< count
; i
++ )
1620 // We're using pathOut to collect the long-name path, but using a
1621 // temporary for appending the last path component which may be
1623 tmpPath
= pathOut
+ dirs
[i
];
1625 if ( tmpPath
.empty() )
1628 // can't see this being necessary? MF
1629 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1631 // Can't pass a drive and root dir to FindFirstFile,
1632 // so continue to next dir
1633 tmpPath
+= wxFILE_SEP_PATH
;
1638 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1639 if (hFind
== INVALID_HANDLE_VALUE
)
1641 // Error: most likely reason is that path doesn't exist, so
1642 // append any unprocessed parts and return
1643 for ( i
+= 1; i
< count
; i
++ )
1644 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1649 pathOut
+= findFileData
.cFileName
;
1650 if ( (i
< (count
-1)) )
1651 pathOut
+= wxFILE_SEP_PATH
;
1657 #endif // Win32/!Win32
1662 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1664 if (format
== wxPATH_NATIVE
)
1666 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1667 format
= wxPATH_DOS
;
1668 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1669 format
= wxPATH_MAC
;
1670 #elif defined(__VMS)
1671 format
= wxPATH_VMS
;
1673 format
= wxPATH_UNIX
;
1679 // ----------------------------------------------------------------------------
1680 // path splitting function
1681 // ----------------------------------------------------------------------------
1685 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
1686 wxString
*pstrVolume
,
1688 wxPathFormat format
)
1690 format
= GetFormat(format
);
1692 wxString fullpath
= fullpathWithVolume
;
1694 // special Windows UNC paths hack: transform \\share\path into share:path
1695 if ( format
== wxPATH_DOS
)
1697 if ( fullpath
.length() >= 4 &&
1698 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1699 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1701 fullpath
.erase(0, 2);
1703 size_t posFirstSlash
=
1704 fullpath
.find_first_of(GetPathTerminators(format
));
1705 if ( posFirstSlash
!= wxString::npos
)
1707 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1709 // UNC paths are always absolute, right? (FIXME)
1710 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1715 // We separate the volume here
1716 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1718 wxString sepVol
= GetVolumeSeparator(format
);
1720 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1721 if ( posFirstColon
!= wxString::npos
)
1725 *pstrVolume
= fullpath
.Left(posFirstColon
);
1728 // remove the volume name and the separator from the full path
1729 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1734 *pstrPath
= fullpath
;
1738 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1739 wxString
*pstrVolume
,
1744 wxPathFormat format
)
1746 format
= GetFormat(format
);
1749 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
1751 // find the positions of the last dot and last path separator in the path
1752 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1753 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
1755 // check whether this dot occurs at the very beginning of a path component
1756 if ( (posLastDot
!= wxString::npos
) &&
1758 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
1759 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
1761 // dot may be (and commonly -- at least under Unix -- is) the first
1762 // character of the filename, don't treat the entire filename as
1763 // extension in this case
1764 posLastDot
= wxString::npos
;
1767 // if we do have a dot and a slash, check that the dot is in the name part
1768 if ( (posLastDot
!= wxString::npos
) &&
1769 (posLastSlash
!= wxString::npos
) &&
1770 (posLastDot
< posLastSlash
) )
1772 // the dot is part of the path, not the start of the extension
1773 posLastDot
= wxString::npos
;
1776 // now fill in the variables provided by user
1779 if ( posLastSlash
== wxString::npos
)
1786 // take everything up to the path separator but take care to make
1787 // the path equal to something like '/', not empty, for the files
1788 // immediately under root directory
1789 size_t len
= posLastSlash
;
1791 // this rule does not apply to mac since we do not start with colons (sep)
1792 // except for relative paths
1793 if ( !len
&& format
!= wxPATH_MAC
)
1796 *pstrPath
= fullpath
.Left(len
);
1798 // special VMS hack: remove the initial bracket
1799 if ( format
== wxPATH_VMS
)
1801 if ( (*pstrPath
)[0u] == _T('[') )
1802 pstrPath
->erase(0, 1);
1809 // take all characters starting from the one after the last slash and
1810 // up to, but excluding, the last dot
1811 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1813 if ( posLastDot
== wxString::npos
)
1815 // take all until the end
1816 count
= wxString::npos
;
1818 else if ( posLastSlash
== wxString::npos
)
1822 else // have both dot and slash
1824 count
= posLastDot
- posLastSlash
- 1;
1827 *pstrName
= fullpath
.Mid(nStart
, count
);
1830 // finally deal with the extension here: we have an added complication that
1831 // extension may be empty (but present) as in "foo." where trailing dot
1832 // indicates the empty extension at the end -- and hence we must remember
1833 // that we have it independently of pstrExt
1834 if ( posLastDot
== wxString::npos
)
1844 // take everything after the dot
1846 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1853 void wxFileName::SplitPath(const wxString
& fullpath
,
1857 wxPathFormat format
)
1860 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1864 path
->Prepend(wxGetVolumeString(volume
, format
));
1868 // ----------------------------------------------------------------------------
1870 // ----------------------------------------------------------------------------
1874 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1875 const wxDateTime
*dtMod
,
1876 const wxDateTime
*dtCreate
)
1878 #if defined(__WIN32__)
1881 // VZ: please let me know how to do this if you can
1882 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1886 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1889 FILETIME ftAccess
, ftCreate
, ftWrite
;
1892 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1894 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1896 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1898 if ( ::SetFileTime(fh
,
1899 dtCreate
? &ftCreate
: NULL
,
1900 dtAccess
? &ftAccess
: NULL
,
1901 dtMod
? &ftWrite
: NULL
) )
1907 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1908 wxUnusedVar(dtCreate
);
1910 if ( !dtAccess
&& !dtMod
)
1912 // can't modify the creation time anyhow, don't try
1916 // if dtAccess or dtMod is not specified, use the other one (which must be
1917 // non NULL because of the test above) for both times
1919 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1920 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1921 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
1925 #else // other platform
1926 wxUnusedVar(dtAccess
);
1928 wxUnusedVar(dtCreate
);
1931 wxLogSysError(_("Failed to modify file times for '%s'"),
1932 GetFullPath().c_str());
1937 bool wxFileName::Touch()
1939 #if defined(__UNIX_LIKE__)
1940 // under Unix touching file is simple: just pass NULL to utime()
1941 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
1946 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1949 #else // other platform
1950 wxDateTime dtNow
= wxDateTime::Now();
1952 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1956 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1958 wxDateTime
*dtCreate
) const
1960 #if defined(__WIN32__)
1961 // we must use different methods for the files and directories under
1962 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1963 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1966 FILETIME ftAccess
, ftCreate
, ftWrite
;
1969 // implemented in msw/dir.cpp
1970 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
1971 FILETIME
*, FILETIME
*, FILETIME
*);
1973 // we should pass the path without the trailing separator to
1974 // wxGetDirectoryTimes()
1975 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
1976 &ftAccess
, &ftCreate
, &ftWrite
);
1980 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1983 ok
= ::GetFileTime(fh
,
1984 dtCreate
? &ftCreate
: NULL
,
1985 dtAccess
? &ftAccess
: NULL
,
1986 dtMod
? &ftWrite
: NULL
) != 0;
1997 ConvertFileTimeToWx(dtCreate
, ftCreate
);
1999 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2001 ConvertFileTimeToWx(dtMod
, ftWrite
);
2005 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2007 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2010 dtAccess
->Set(stBuf
.st_atime
);
2012 dtMod
->Set(stBuf
.st_mtime
);
2014 dtCreate
->Set(stBuf
.st_ctime
);
2018 #else // other platform
2019 wxUnusedVar(dtAccess
);
2021 wxUnusedVar(dtCreate
);
2024 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2025 GetFullPath().c_str());
2030 #endif // wxUSE_DATETIME
2033 // ----------------------------------------------------------------------------
2034 // file size functions
2035 // ----------------------------------------------------------------------------
2038 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2040 if (!wxFileExists(filename
))
2041 return wxInvalidSize
;
2043 #if defined(__WXPALMOS__)
2045 return wxInvalidSize
;
2046 #elif defined(__WIN32__)
2047 wxFileHandle
f(filename
, wxFileHandle::Read
);
2049 return wxInvalidSize
;
2051 DWORD lpFileSizeHigh
;
2052 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2053 if (ret
== INVALID_FILE_SIZE
)
2054 return wxInvalidSize
;
2056 // compose the low-order and high-order byte sizes
2057 return wxULongLong(ret
| (lpFileSizeHigh
<< sizeof(WORD
)*2));
2059 #else // ! __WIN32__
2062 #ifndef wxNEED_WX_UNISTD_H
2063 if (wxStat( filename
.fn_str() , &st
) != 0)
2065 if (wxStat( filename
, &st
) != 0)
2067 return wxInvalidSize
;
2068 return wxULongLong(st
.st_size
);
2073 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2074 const wxString
&nullsize
,
2077 static const double KILOBYTESIZE
= 1024.0;
2078 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2079 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2080 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2082 if (bs
== 0 || bs
== wxInvalidSize
)
2085 double bytesize
= bs
.ToDouble();
2086 if (bytesize
< KILOBYTESIZE
)
2087 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2088 if (bytesize
< MEGABYTESIZE
)
2089 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2090 if (bytesize
< GIGABYTESIZE
)
2091 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2092 if (bytesize
< TERABYTESIZE
)
2093 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2095 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2098 wxULongLong
wxFileName::GetSize() const
2100 return GetSize(GetFullPath());
2103 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2105 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2109 // ----------------------------------------------------------------------------
2110 // Mac-specific functions
2111 // ----------------------------------------------------------------------------
2115 const short kMacExtensionMaxLength
= 16 ;
2116 class MacDefaultExtensionRecord
2119 MacDefaultExtensionRecord()
2122 m_type
= m_creator
= 0 ;
2124 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
2126 wxStrcpy( m_ext
, from
.m_ext
) ;
2127 m_type
= from
.m_type
;
2128 m_creator
= from
.m_creator
;
2130 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
2132 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
2133 m_ext
[kMacExtensionMaxLength
] = 0 ;
2135 m_creator
= creator
;
2137 wxChar m_ext
[kMacExtensionMaxLength
] ;
2142 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
2144 bool gMacDefaultExtensionsInited
= false ;
2146 #include "wx/arrimpl.cpp"
2148 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
2150 MacDefaultExtensionArray gMacDefaultExtensions
;
2152 // load the default extensions
2153 MacDefaultExtensionRecord gDefaults
[] =
2155 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2156 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2157 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2160 static void MacEnsureDefaultExtensionsLoaded()
2162 if ( !gMacDefaultExtensionsInited
)
2164 // we could load the pc exchange prefs here too
2165 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2167 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2169 gMacDefaultExtensionsInited
= true ;
2173 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2176 FSCatalogInfo catInfo
;
2179 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2181 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2183 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2184 finfo
->fileType
= type
;
2185 finfo
->fileCreator
= creator
;
2186 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2193 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2196 FSCatalogInfo catInfo
;
2199 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2201 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2203 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2204 *type
= finfo
->fileType
;
2205 *creator
= finfo
->fileCreator
;
2212 bool wxFileName::MacSetDefaultTypeAndCreator()
2214 wxUint32 type
, creator
;
2215 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2218 return MacSetTypeAndCreator( type
, creator
) ;
2223 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2225 MacEnsureDefaultExtensionsLoaded() ;
2226 wxString extl
= ext
.Lower() ;
2227 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2229 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2231 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2232 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2239 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2241 MacEnsureDefaultExtensionsLoaded() ;
2242 MacDefaultExtensionRecord rec
;
2244 rec
.m_creator
= creator
;
2245 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
2246 gMacDefaultExtensions
.Add( rec
) ;