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
, wxString
& targetFilename
, wxString
* arguments
)
1052 wxString path
, file
, ext
;
1053 wxSplitPath(shortcutPath
, & path
, & file
, & ext
);
1057 bool success
= false;
1059 // Assume it's not a shortcut if it doesn't end with lnk
1060 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1063 // create a ShellLink object
1064 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1065 IID_IShellLink
, (LPVOID
*) &psl
);
1067 if (SUCCEEDED(hres
))
1070 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1071 if (SUCCEEDED(hres
))
1073 WCHAR wsz
[MAX_PATH
];
1075 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1078 hres
= ppf
->Load(wsz
, 0);
1079 if (SUCCEEDED(hres
))
1082 // Wrong prototype in early versions
1083 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1084 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1086 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1088 targetFilename
= wxString(buf
);
1089 success
= (shortcutPath
!= targetFilename
);
1091 psl
->GetArguments(buf
, 2048);
1093 if (!args
.empty() && arguments
)
1106 // ----------------------------------------------------------------------------
1107 // absolute/relative paths
1108 // ----------------------------------------------------------------------------
1110 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1112 // if our path doesn't start with a path separator, it's not an absolute
1117 if ( !GetVolumeSeparator(format
).empty() )
1119 // this format has volumes and an absolute path must have one, it's not
1120 // enough to have the full path to bean absolute file under Windows
1121 if ( GetVolume().empty() )
1128 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1130 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1132 // get cwd only once - small time saving
1133 wxString cwd
= wxGetCwd();
1134 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1135 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1137 bool withCase
= IsCaseSensitive(format
);
1139 // we can't do anything if the files live on different volumes
1140 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1146 // same drive, so we don't need our volume
1149 // remove common directories starting at the top
1150 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1151 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1154 fnBase
.m_dirs
.RemoveAt(0);
1157 // add as many ".." as needed
1158 size_t count
= fnBase
.m_dirs
.GetCount();
1159 for ( size_t i
= 0; i
< count
; i
++ )
1161 m_dirs
.Insert(wxT(".."), 0u);
1164 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1166 // a directory made relative with respect to itself is '.' under Unix
1167 // and DOS, by definition (but we don't have to insert "./" for the
1169 if ( m_dirs
.IsEmpty() && IsDir() )
1171 m_dirs
.Add(_T('.'));
1181 // ----------------------------------------------------------------------------
1182 // filename kind tests
1183 // ----------------------------------------------------------------------------
1185 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1187 wxFileName fn1
= *this,
1190 // get cwd only once - small time saving
1191 wxString cwd
= wxGetCwd();
1192 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1193 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1195 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1198 // TODO: compare inodes for Unix, this works even when filenames are
1199 // different but files are the same (symlinks) (VZ)
1205 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1207 // only Unix filenames are truely case-sensitive
1208 return GetFormat(format
) == wxPATH_UNIX
;
1212 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1214 // Inits to forbidden characters that are common to (almost) all platforms.
1215 wxString strForbiddenChars
= wxT("*?");
1217 // If asserts, wxPathFormat has been changed. In case of a new path format
1218 // addition, the following code might have to be updated.
1219 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1220 switch ( GetFormat(format
) )
1223 wxFAIL_MSG( wxT("Unknown path format") );
1224 // !! Fall through !!
1230 // On a Mac even names with * and ? are allowed (Tested with OS
1231 // 9.2.1 and OS X 10.2.5)
1232 strForbiddenChars
= wxEmptyString
;
1236 strForbiddenChars
+= wxT("\\/:\"<>|");
1243 return strForbiddenChars
;
1247 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1250 return wxEmptyString
;
1254 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1255 (GetFormat(format
) == wxPATH_VMS
) )
1257 sepVol
= wxFILE_SEP_DSK
;
1266 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1269 switch ( GetFormat(format
) )
1272 // accept both as native APIs do but put the native one first as
1273 // this is the one we use in GetFullPath()
1274 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1278 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1282 seps
= wxFILE_SEP_PATH_UNIX
;
1286 seps
= wxFILE_SEP_PATH_MAC
;
1290 seps
= wxFILE_SEP_PATH_VMS
;
1298 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1300 format
= GetFormat(format
);
1302 // under VMS the end of the path is ']', not the path separator used to
1303 // separate the components
1304 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1308 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1310 // wxString::Find() doesn't work as expected with NUL - it will always find
1311 // it, so test for it separately
1312 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1315 // ----------------------------------------------------------------------------
1316 // path components manipulation
1317 // ----------------------------------------------------------------------------
1319 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1323 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1328 const size_t len
= dir
.length();
1329 for ( size_t n
= 0; n
< len
; n
++ )
1331 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1333 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1342 void wxFileName::AppendDir( const wxString
& dir
)
1344 if ( IsValidDirComponent(dir
) )
1348 void wxFileName::PrependDir( const wxString
& dir
)
1353 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1355 if ( IsValidDirComponent(dir
) )
1356 m_dirs
.Insert(dir
, before
);
1359 void wxFileName::RemoveDir(size_t pos
)
1361 m_dirs
.RemoveAt(pos
);
1364 // ----------------------------------------------------------------------------
1366 // ----------------------------------------------------------------------------
1368 void wxFileName::SetFullName(const wxString
& fullname
)
1370 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1371 &m_name
, &m_ext
, &m_hasExt
);
1374 wxString
wxFileName::GetFullName() const
1376 wxString fullname
= m_name
;
1379 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1385 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1387 format
= GetFormat( format
);
1391 // return the volume with the path as well if requested
1392 if ( flags
& wxPATH_GET_VOLUME
)
1394 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1397 // the leading character
1402 fullpath
+= wxFILE_SEP_PATH_MAC
;
1407 fullpath
+= wxFILE_SEP_PATH_DOS
;
1411 wxFAIL_MSG( wxT("Unknown path format") );
1417 // normally the absolute file names start with a slash
1418 // with one exception: the ones like "~/foo.bar" don't
1420 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1422 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1428 // no leading character here but use this place to unset
1429 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1430 // as, if I understand correctly, there should never be a dot
1431 // before the closing bracket
1432 flags
&= ~wxPATH_GET_SEPARATOR
;
1435 if ( m_dirs
.empty() )
1437 // there is nothing more
1441 // then concatenate all the path components using the path separator
1442 if ( format
== wxPATH_VMS
)
1444 fullpath
+= wxT('[');
1447 const size_t dirCount
= m_dirs
.GetCount();
1448 for ( size_t i
= 0; i
< dirCount
; i
++ )
1453 if ( m_dirs
[i
] == wxT(".") )
1455 // skip appending ':', this shouldn't be done in this
1456 // case as "::" is interpreted as ".." under Unix
1460 // convert back from ".." to nothing
1461 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1462 fullpath
+= m_dirs
[i
];
1466 wxFAIL_MSG( wxT("Unexpected path format") );
1467 // still fall through
1471 fullpath
+= m_dirs
[i
];
1475 // TODO: What to do with ".." under VMS
1477 // convert back from ".." to nothing
1478 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1479 fullpath
+= m_dirs
[i
];
1483 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1484 fullpath
+= GetPathSeparator(format
);
1487 if ( format
== wxPATH_VMS
)
1489 fullpath
+= wxT(']');
1495 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1497 // we already have a function to get the path
1498 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1501 // now just add the file name and extension to it
1502 fullpath
+= GetFullName();
1507 // Return the short form of the path (returns identity on non-Windows platforms)
1508 wxString
wxFileName::GetShortPath() const
1510 wxString
path(GetFullPath());
1512 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1513 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1517 if ( ::GetShortPathName
1520 wxStringBuffer(pathOut
, sz
),
1532 // Return the long form of the path (returns identity on non-Windows platforms)
1533 wxString
wxFileName::GetLongPath() const
1536 path
= GetFullPath();
1538 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1540 #if wxUSE_DYNAMIC_LOADER
1541 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1543 // this is MT-safe as in the worst case we're going to resolve the function
1544 // twice -- but as the result is the same in both threads, it's ok
1545 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1546 if ( !s_pfnGetLongPathName
)
1548 static bool s_triedToLoad
= false;
1550 if ( !s_triedToLoad
)
1552 s_triedToLoad
= true;
1554 wxDynamicLibrary
dllKernel(_T("kernel32"));
1556 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1561 #endif // Unicode/ANSI
1563 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1565 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1566 dllKernel
.GetSymbol(GetLongPathName
);
1569 // note that kernel32.dll can be unloaded, it stays in memory
1570 // anyhow as all Win32 programs link to it and so it's safe to call
1571 // GetLongPathName() even after unloading it
1575 if ( s_pfnGetLongPathName
)
1577 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1580 if ( (*s_pfnGetLongPathName
)
1583 wxStringBuffer(pathOut
, dwSize
),
1591 #endif // wxUSE_DYNAMIC_LOADER
1593 // The OS didn't support GetLongPathName, or some other error.
1594 // We need to call FindFirstFile on each component in turn.
1596 WIN32_FIND_DATA findFileData
;
1600 pathOut
= GetVolume() +
1601 GetVolumeSeparator(wxPATH_DOS
) +
1602 GetPathSeparator(wxPATH_DOS
);
1604 pathOut
= wxEmptyString
;
1606 wxArrayString dirs
= GetDirs();
1607 dirs
.Add(GetFullName());
1611 size_t count
= dirs
.GetCount();
1612 for ( size_t i
= 0; i
< count
; i
++ )
1614 // We're using pathOut to collect the long-name path, but using a
1615 // temporary for appending the last path component which may be
1617 tmpPath
= pathOut
+ dirs
[i
];
1619 if ( tmpPath
.empty() )
1622 // can't see this being necessary? MF
1623 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1625 // Can't pass a drive and root dir to FindFirstFile,
1626 // so continue to next dir
1627 tmpPath
+= wxFILE_SEP_PATH
;
1632 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1633 if (hFind
== INVALID_HANDLE_VALUE
)
1635 // Error: most likely reason is that path doesn't exist, so
1636 // append any unprocessed parts and return
1637 for ( i
+= 1; i
< count
; i
++ )
1638 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1643 pathOut
+= findFileData
.cFileName
;
1644 if ( (i
< (count
-1)) )
1645 pathOut
+= wxFILE_SEP_PATH
;
1651 #endif // Win32/!Win32
1656 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1658 if (format
== wxPATH_NATIVE
)
1660 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1661 format
= wxPATH_DOS
;
1662 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1663 format
= wxPATH_MAC
;
1664 #elif defined(__VMS)
1665 format
= wxPATH_VMS
;
1667 format
= wxPATH_UNIX
;
1673 // ----------------------------------------------------------------------------
1674 // path splitting function
1675 // ----------------------------------------------------------------------------
1679 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
1680 wxString
*pstrVolume
,
1682 wxPathFormat format
)
1684 format
= GetFormat(format
);
1686 wxString fullpath
= fullpathWithVolume
;
1688 // special Windows UNC paths hack: transform \\share\path into share:path
1689 if ( format
== wxPATH_DOS
)
1691 if ( fullpath
.length() >= 4 &&
1692 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1693 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1695 fullpath
.erase(0, 2);
1697 size_t posFirstSlash
=
1698 fullpath
.find_first_of(GetPathTerminators(format
));
1699 if ( posFirstSlash
!= wxString::npos
)
1701 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1703 // UNC paths are always absolute, right? (FIXME)
1704 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1709 // We separate the volume here
1710 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1712 wxString sepVol
= GetVolumeSeparator(format
);
1714 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1715 if ( posFirstColon
!= wxString::npos
)
1719 *pstrVolume
= fullpath
.Left(posFirstColon
);
1722 // remove the volume name and the separator from the full path
1723 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1728 *pstrPath
= fullpath
;
1732 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1733 wxString
*pstrVolume
,
1738 wxPathFormat format
)
1740 format
= GetFormat(format
);
1743 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
1745 // find the positions of the last dot and last path separator in the path
1746 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1747 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
1749 // check whether this dot occurs at the very beginning of a path component
1750 if ( (posLastDot
!= wxString::npos
) &&
1752 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
1753 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
1755 // dot may be (and commonly -- at least under Unix -- is) the first
1756 // character of the filename, don't treat the entire filename as
1757 // extension in this case
1758 posLastDot
= wxString::npos
;
1761 // if we do have a dot and a slash, check that the dot is in the name part
1762 if ( (posLastDot
!= wxString::npos
) &&
1763 (posLastSlash
!= wxString::npos
) &&
1764 (posLastDot
< posLastSlash
) )
1766 // the dot is part of the path, not the start of the extension
1767 posLastDot
= wxString::npos
;
1770 // now fill in the variables provided by user
1773 if ( posLastSlash
== wxString::npos
)
1780 // take everything up to the path separator but take care to make
1781 // the path equal to something like '/', not empty, for the files
1782 // immediately under root directory
1783 size_t len
= posLastSlash
;
1785 // this rule does not apply to mac since we do not start with colons (sep)
1786 // except for relative paths
1787 if ( !len
&& format
!= wxPATH_MAC
)
1790 *pstrPath
= fullpath
.Left(len
);
1792 // special VMS hack: remove the initial bracket
1793 if ( format
== wxPATH_VMS
)
1795 if ( (*pstrPath
)[0u] == _T('[') )
1796 pstrPath
->erase(0, 1);
1803 // take all characters starting from the one after the last slash and
1804 // up to, but excluding, the last dot
1805 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1807 if ( posLastDot
== wxString::npos
)
1809 // take all until the end
1810 count
= wxString::npos
;
1812 else if ( posLastSlash
== wxString::npos
)
1816 else // have both dot and slash
1818 count
= posLastDot
- posLastSlash
- 1;
1821 *pstrName
= fullpath
.Mid(nStart
, count
);
1824 // finally deal with the extension here: we have an added complication that
1825 // extension may be empty (but present) as in "foo." where trailing dot
1826 // indicates the empty extension at the end -- and hence we must remember
1827 // that we have it independently of pstrExt
1828 if ( posLastDot
== wxString::npos
)
1838 // take everything after the dot
1840 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1847 void wxFileName::SplitPath(const wxString
& fullpath
,
1851 wxPathFormat format
)
1854 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1858 path
->Prepend(wxGetVolumeString(volume
, format
));
1862 // ----------------------------------------------------------------------------
1864 // ----------------------------------------------------------------------------
1868 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1869 const wxDateTime
*dtMod
,
1870 const wxDateTime
*dtCreate
)
1872 #if defined(__WIN32__)
1875 // VZ: please let me know how to do this if you can
1876 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1880 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1883 FILETIME ftAccess
, ftCreate
, ftWrite
;
1886 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1888 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1890 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1892 if ( ::SetFileTime(fh
,
1893 dtCreate
? &ftCreate
: NULL
,
1894 dtAccess
? &ftAccess
: NULL
,
1895 dtMod
? &ftWrite
: NULL
) )
1901 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1902 wxUnusedVar(dtCreate
);
1904 if ( !dtAccess
&& !dtMod
)
1906 // can't modify the creation time anyhow, don't try
1910 // if dtAccess or dtMod is not specified, use the other one (which must be
1911 // non NULL because of the test above) for both times
1913 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1914 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1915 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
1919 #else // other platform
1920 wxUnusedVar(dtAccess
);
1922 wxUnusedVar(dtCreate
);
1925 wxLogSysError(_("Failed to modify file times for '%s'"),
1926 GetFullPath().c_str());
1931 bool wxFileName::Touch()
1933 #if defined(__UNIX_LIKE__)
1934 // under Unix touching file is simple: just pass NULL to utime()
1935 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
1940 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1943 #else // other platform
1944 wxDateTime dtNow
= wxDateTime::Now();
1946 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1950 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1952 wxDateTime
*dtCreate
) const
1954 #if defined(__WIN32__)
1955 // we must use different methods for the files and directories under
1956 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1957 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1960 FILETIME ftAccess
, ftCreate
, ftWrite
;
1963 // implemented in msw/dir.cpp
1964 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
1965 FILETIME
*, FILETIME
*, FILETIME
*);
1967 // we should pass the path without the trailing separator to
1968 // wxGetDirectoryTimes()
1969 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
1970 &ftAccess
, &ftCreate
, &ftWrite
);
1974 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1977 ok
= ::GetFileTime(fh
,
1978 dtCreate
? &ftCreate
: NULL
,
1979 dtAccess
? &ftAccess
: NULL
,
1980 dtMod
? &ftWrite
: NULL
) != 0;
1991 ConvertFileTimeToWx(dtCreate
, ftCreate
);
1993 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1995 ConvertFileTimeToWx(dtMod
, ftWrite
);
1999 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2001 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2004 dtAccess
->Set(stBuf
.st_atime
);
2006 dtMod
->Set(stBuf
.st_mtime
);
2008 dtCreate
->Set(stBuf
.st_ctime
);
2012 #else // other platform
2013 wxUnusedVar(dtAccess
);
2015 wxUnusedVar(dtCreate
);
2018 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2019 GetFullPath().c_str());
2024 #endif // wxUSE_DATETIME
2027 // ----------------------------------------------------------------------------
2028 // file size functions
2029 // ----------------------------------------------------------------------------
2032 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2034 if (!wxFileExists(filename
))
2035 return wxInvalidSize
;
2038 wxFileHandle
f(filename
, wxFileHandle::Read
);
2040 return wxInvalidSize
;
2042 DWORD lpFileSizeHigh
;
2043 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2044 if (ret
== INVALID_FILE_SIZE
)
2045 return wxInvalidSize
;
2047 // compose the low-order and high-order byte sizes
2048 return wxULongLong(ret
| (lpFileSizeHigh
<< sizeof(WORD
)*2));
2050 #else // ! __WIN32__
2053 #ifndef wxNEED_WX_UNISTD_H
2054 if (wxStat( filename
.fn_str() , &st
) != 0)
2056 if (wxStat( filename
, &st
) != 0)
2058 return wxInvalidSize
;
2059 return wxULongLong(st
.st_size
);
2064 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2065 const wxString
&nullsize
,
2068 static const double KILOBYTESIZE
= 1024.0;
2069 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2070 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2071 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2073 if (bs
== 0 || bs
== wxInvalidSize
)
2076 double bytesize
= bs
.ToDouble();
2077 if (bytesize
< KILOBYTESIZE
)
2078 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2079 if (bytesize
< MEGABYTESIZE
)
2080 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2081 if (bytesize
< GIGABYTESIZE
)
2082 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2083 if (bytesize
< TERABYTESIZE
)
2084 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2086 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2089 wxULongLong
wxFileName::GetSize() const
2091 return GetSize(GetFullPath());
2094 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2096 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2100 // ----------------------------------------------------------------------------
2101 // Mac-specific functions
2102 // ----------------------------------------------------------------------------
2106 const short kMacExtensionMaxLength
= 16 ;
2107 class MacDefaultExtensionRecord
2110 MacDefaultExtensionRecord()
2113 m_type
= m_creator
= 0 ;
2115 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
2117 wxStrcpy( m_ext
, from
.m_ext
) ;
2118 m_type
= from
.m_type
;
2119 m_creator
= from
.m_creator
;
2121 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
2123 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
2124 m_ext
[kMacExtensionMaxLength
] = 0 ;
2126 m_creator
= creator
;
2128 wxChar m_ext
[kMacExtensionMaxLength
] ;
2133 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
2135 bool gMacDefaultExtensionsInited
= false ;
2137 #include "wx/arrimpl.cpp"
2139 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
2141 MacDefaultExtensionArray gMacDefaultExtensions
;
2143 // load the default extensions
2144 MacDefaultExtensionRecord gDefaults
[] =
2146 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2147 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2148 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2151 static void MacEnsureDefaultExtensionsLoaded()
2153 if ( !gMacDefaultExtensionsInited
)
2155 // we could load the pc exchange prefs here too
2156 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2158 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2160 gMacDefaultExtensionsInited
= true ;
2164 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2167 FSCatalogInfo catInfo
;
2170 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2172 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2174 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2175 finfo
->fileType
= type
;
2176 finfo
->fileCreator
= creator
;
2177 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2184 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2187 FSCatalogInfo catInfo
;
2190 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2192 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2194 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2195 *type
= finfo
->fileType
;
2196 *creator
= finfo
->fileCreator
;
2203 bool wxFileName::MacSetDefaultTypeAndCreator()
2205 wxUint32 type
, creator
;
2206 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2209 return MacSetTypeAndCreator( type
, creator
) ;
2214 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2216 MacEnsureDefaultExtensionsLoaded() ;
2217 wxString extl
= ext
.Lower() ;
2218 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2220 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2222 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2223 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2230 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2232 MacEnsureDefaultExtensionsLoaded() ;
2233 MacDefaultExtensionRecord rec
;
2235 rec
.m_creator
= creator
;
2236 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
2237 gMacDefaultExtensions
.Add( rec
) ;