1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filename.cpp
3 // Purpose: wxFileName - encapsulates a file path
4 // Author: Robert Roebling, Vadim Zeitlin
8 // Copyright: (c) 2000 Robert Roebling
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 Here are brief descriptions of the filename formats supported by this class:
15 wxPATH_UNIX: standard Unix format, used under Darwin as well, absolute file
17 /dir1/dir2/.../dirN/filename, "." and ".." stand for the
18 current and parent directory respectively, "~" is parsed as the
19 user HOME and "~username" as the HOME of that user
21 wxPATH_DOS: DOS/Windows format, absolute file names have the form:
22 drive:\dir1\dir2\...\dirN\filename.ext where drive is a single
23 letter. "." and ".." as for Unix but no "~".
25 There are also UNC names of the form \\share\fullpath
27 wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
29 volume:dir1:...:dirN:filename
30 and the relative file names are either
31 :dir1:...:dirN:filename
34 (although :filename works as well).
35 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
39 wxPATH_VMS: VMS native format, absolute file names have the form
40 <device>:[dir1.dir2.dir3]file.txt
42 <device>:[000000.dir1.dir2.dir3]file.txt
44 the <device> is the physical device (i.e. disk). 000000 is the
45 root directory on the device which can be omitted.
47 Note that VMS uses different separators unlike Unix:
48 : always after the device. If the path does not contain : than
49 the default (the device of the current directory) is assumed.
50 [ start of directory specification
51 . separator between directory and subdirectory
52 ] between directory and file
55 // ============================================================================
57 // ============================================================================
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
63 // For compilers that support precompilation, includes "wx.h".
64 #include "wx/wxprec.h"
72 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
74 #include "wx/dynarray.h"
81 #include "wx/filename.h"
82 #include "wx/tokenzr.h"
83 #include "wx/config.h" // for wxExpandEnvVars
85 #include "wx/dynlib.h"
87 #if defined(__WIN32__) && defined(__MINGW32__)
88 #include "wx/msw/gccpriv.h"
92 #include "wx/msw/private.h"
95 #if defined(__WXMAC__)
96 #include "wx/mac/private.h" // includes mac headers
99 // utime() is POSIX so should normally be available on all Unices
101 #include <sys/types.h>
103 #include <sys/stat.h>
113 #include <sys/types.h>
115 #include <sys/stat.h>
126 #include <sys/utime.h>
127 #include <sys/stat.h>
138 #define MAX_PATH _MAX_PATH
142 wxULongLong wxInvalidSize
= (unsigned)-1;
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
149 // small helper class which opens and closes the file - we use it just to get
150 // a file handle for the given file name to pass it to some Win32 API function
151 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
162 wxFileHandle(const wxString
& filename
, OpenMode mode
)
164 m_hFile
= ::CreateFile
167 mode
== Read
? GENERIC_READ
// access mask
169 FILE_SHARE_READ
| // sharing mode
170 FILE_SHARE_WRITE
, // (allow everything)
171 NULL
, // no secutity attr
172 OPEN_EXISTING
, // creation disposition
174 NULL
// no template file
177 if ( m_hFile
== INVALID_HANDLE_VALUE
)
179 wxLogSysError(_("Failed to open '%s' for %s"),
181 mode
== Read
? _("reading") : _("writing"));
187 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
189 if ( !::CloseHandle(m_hFile
) )
191 wxLogSysError(_("Failed to close file handle"));
196 // return true only if the file could be opened successfully
197 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
200 operator HANDLE() const { return m_hFile
; }
208 // ----------------------------------------------------------------------------
210 // ----------------------------------------------------------------------------
212 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
214 // convert between wxDateTime and FILETIME which is a 64-bit value representing
215 // the number of 100-nanosecond intervals since January 1, 1601.
217 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
219 FILETIME ftcopy
= ft
;
221 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
223 wxLogLastError(_T("FileTimeToLocalFileTime"));
227 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
229 wxLogLastError(_T("FileTimeToSystemTime"));
232 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
233 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
236 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
239 st
.wDay
= dt
.GetDay();
240 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
241 st
.wYear
= (WORD
)dt
.GetYear();
242 st
.wHour
= dt
.GetHour();
243 st
.wMinute
= dt
.GetMinute();
244 st
.wSecond
= dt
.GetSecond();
245 st
.wMilliseconds
= dt
.GetMillisecond();
248 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
250 wxLogLastError(_T("SystemTimeToFileTime"));
253 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
255 wxLogLastError(_T("LocalFileTimeToFileTime"));
259 #endif // wxUSE_DATETIME && __WIN32__
261 // return a string with the volume par
262 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
266 if ( !volume
.empty() )
268 format
= wxFileName::GetFormat(format
);
270 // Special Windows UNC paths hack, part 2: undo what we did in
271 // SplitPath() and make an UNC path if we have a drive which is not a
272 // single letter (hopefully the network shares can't be one letter only
273 // although I didn't find any authoritative docs on this)
274 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
276 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
278 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
280 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
288 // ============================================================================
290 // ============================================================================
292 // ----------------------------------------------------------------------------
293 // wxFileName construction
294 // ----------------------------------------------------------------------------
296 void wxFileName::Assign( const wxFileName
&filepath
)
298 m_volume
= filepath
.GetVolume();
299 m_dirs
= filepath
.GetDirs();
300 m_name
= filepath
.GetName();
301 m_ext
= filepath
.GetExt();
302 m_relative
= filepath
.m_relative
;
303 m_hasExt
= filepath
.m_hasExt
;
306 void wxFileName::Assign(const wxString
& volume
,
307 const wxString
& path
,
308 const wxString
& name
,
311 wxPathFormat format
)
313 SetPath( path
, format
);
322 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
326 if ( pathOrig
.empty() )
334 format
= GetFormat( format
);
336 // 0) deal with possible volume part first
339 SplitVolume(pathOrig
, &volume
, &path
, format
);
340 if ( !volume
.empty() )
347 // 1) Determine if the path is relative or absolute.
348 wxChar leadingChar
= path
[0u];
353 m_relative
= leadingChar
== wxT(':');
355 // We then remove a leading ":". The reason is in our
356 // storage form for relative paths:
357 // ":dir:file.txt" actually means "./dir/file.txt" in
358 // DOS notation and should get stored as
359 // (relative) (dir) (file.txt)
360 // "::dir:file.txt" actually means "../dir/file.txt"
361 // stored as (relative) (..) (dir) (file.txt)
362 // This is important only for the Mac as an empty dir
363 // actually means <UP>, whereas under DOS, double
364 // slashes can be ignored: "\\\\" is the same as "\\".
370 // TODO: what is the relative path format here?
375 wxFAIL_MSG( _T("Unknown path format") );
376 // !! Fall through !!
379 // the paths of the form "~" or "~username" are absolute
380 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
384 m_relative
= !IsPathSeparator(leadingChar
, format
);
389 // 2) Break up the path into its members. If the original path
390 // was just "/" or "\\", m_dirs will be empty. We know from
391 // the m_relative field, if this means "nothing" or "root dir".
393 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
395 while ( tn
.HasMoreTokens() )
397 wxString token
= tn
.GetNextToken();
399 // Remove empty token under DOS and Unix, interpret them
403 if (format
== wxPATH_MAC
)
404 m_dirs
.Add( wxT("..") );
414 void wxFileName::Assign(const wxString
& fullpath
,
417 wxString volume
, path
, name
, ext
;
419 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
421 Assign(volume
, path
, name
, ext
, hasExt
, format
);
424 void wxFileName::Assign(const wxString
& fullpathOrig
,
425 const wxString
& fullname
,
428 // always recognize fullpath as directory, even if it doesn't end with a
430 wxString fullpath
= fullpathOrig
;
431 if ( !wxEndsWithPathSeparator(fullpath
) )
433 fullpath
+= GetPathSeparator(format
);
436 wxString volume
, path
, name
, ext
;
439 // do some consistency checks in debug mode: the name should be really just
440 // the filename and the path should be really just a path
442 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
444 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
446 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
447 _T("the file name shouldn't contain the path") );
449 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
451 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
452 _T("the path shouldn't contain file name nor extension") );
454 #else // !__WXDEBUG__
455 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
456 &name
, &ext
, &hasExt
, format
);
457 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
458 #endif // __WXDEBUG__/!__WXDEBUG__
460 Assign(volume
, path
, name
, ext
, hasExt
, format
);
463 void wxFileName::Assign(const wxString
& pathOrig
,
464 const wxString
& name
,
470 SplitVolume(pathOrig
, &volume
, &path
, format
);
472 Assign(volume
, path
, name
, ext
, format
);
475 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
477 Assign(dir
, wxEmptyString
, format
);
480 void wxFileName::Clear()
486 m_ext
= wxEmptyString
;
488 // we don't have any absolute path for now
496 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
498 return wxFileName(file
, format
);
502 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
505 fn
.AssignDir(dir
, format
);
509 // ----------------------------------------------------------------------------
511 // ----------------------------------------------------------------------------
513 bool wxFileName::FileExists() const
515 return wxFileName::FileExists( GetFullPath() );
518 bool wxFileName::FileExists( const wxString
&file
)
520 return ::wxFileExists( file
);
523 bool wxFileName::DirExists() const
525 return wxFileName::DirExists( GetPath() );
528 bool wxFileName::DirExists( const wxString
&dir
)
530 return ::wxDirExists( dir
);
533 // ----------------------------------------------------------------------------
534 // CWD and HOME stuff
535 // ----------------------------------------------------------------------------
537 void wxFileName::AssignCwd(const wxString
& volume
)
539 AssignDir(wxFileName::GetCwd(volume
));
543 wxString
wxFileName::GetCwd(const wxString
& volume
)
545 // if we have the volume, we must get the current directory on this drive
546 // and to do this we have to chdir to this volume - at least under Windows,
547 // I don't know how to get the current drive on another volume elsewhere
550 if ( !volume
.empty() )
553 SetCwd(volume
+ GetVolumeSeparator());
556 wxString cwd
= ::wxGetCwd();
558 if ( !volume
.empty() )
566 bool wxFileName::SetCwd()
568 return wxFileName::SetCwd( GetPath() );
571 bool wxFileName::SetCwd( const wxString
&cwd
)
573 return ::wxSetWorkingDirectory( cwd
);
576 void wxFileName::AssignHomeDir()
578 AssignDir(wxFileName::GetHomeDir());
581 wxString
wxFileName::GetHomeDir()
583 return ::wxGetHomeDir();
588 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
590 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
591 if ( tempname
.empty() )
593 // error, failed to get temp file name
604 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
606 wxString path
, dir
, name
;
608 // use the directory specified by the prefix
609 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
613 dir
= wxGetenv(_T("TMPDIR"));
616 dir
= wxGetenv(_T("TMP"));
619 dir
= wxGetenv(_T("TEMP"));
624 #if defined(__WXWINCE__)
627 // FIXME. Create \temp dir?
628 if (DirExists(wxT("\\temp")))
631 path
= dir
+ wxT("\\") + name
;
633 while (FileExists(path
))
635 path
= dir
+ wxT("\\") + name
;
640 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
644 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
646 wxLogLastError(_T("GetTempPath"));
651 // GetTempFileName() fails if we pass it an empty string
655 else // we have a dir to create the file in
657 // ensure we use only the back slashes as GetTempFileName(), unlike all
658 // the other APIs, is picky and doesn't accept the forward ones
659 dir
.Replace(_T("/"), _T("\\"));
662 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
664 wxLogLastError(_T("GetTempFileName"));
673 #if defined(__DOS__) || defined(__OS2__)
675 #elif defined(__WXMAC__)
676 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
684 if ( !wxEndsWithPathSeparator(dir
) &&
685 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
687 path
+= wxFILE_SEP_PATH
;
692 #if defined(HAVE_MKSTEMP)
693 // scratch space for mkstemp()
694 path
+= _T("XXXXXX");
696 // we need to copy the path to the buffer in which mkstemp() can modify it
697 wxCharBuffer
buf( wxConvFile
.cWX2MB( path
) );
699 // cast is safe because the string length doesn't change
700 int fdTemp
= mkstemp( (char*)(const char*) buf
);
703 // this might be not necessary as mkstemp() on most systems should have
704 // already done it but it doesn't hurt neither...
707 else // mkstemp() succeeded
709 path
= wxConvFile
.cMB2WX( (const char*) buf
);
711 // avoid leaking the fd
714 fileTemp
->Attach(fdTemp
);
721 #else // !HAVE_MKSTEMP
725 path
+= _T("XXXXXX");
727 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
728 if ( !mktemp( (const char*) buf
) )
734 path
= wxConvFile
.cMB2WX( (const char*) buf
);
736 #else // !HAVE_MKTEMP (includes __DOS__)
737 // generate the unique file name ourselves
738 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
739 path
<< (unsigned int)getpid();
744 static const size_t numTries
= 1000;
745 for ( size_t n
= 0; n
< numTries
; n
++ )
747 // 3 hex digits is enough for numTries == 1000 < 4096
748 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
749 if ( !FileExists(pathTry
) )
758 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
760 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
762 #endif // Windows/!Windows
766 wxLogSysError(_("Failed to create a temporary file name"));
768 else if ( fileTemp
&& !fileTemp
->IsOpened() )
770 // open the file - of course, there is a race condition here, this is
771 // why we always prefer using mkstemp()...
773 // NB: GetTempFileName() under Windows creates the file, so using
774 // write_excl there would fail
775 if ( !fileTemp
->Open(path
,
776 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
781 wxS_IRUSR
| wxS_IWUSR
) )
783 // FIXME: If !ok here should we loop and try again with another
784 // file name? That is the standard recourse if open(O_EXCL)
785 // fails, though of course it should be protected against
786 // possible infinite looping too.
788 wxLogError(_("Failed to open temporary file."));
799 // ----------------------------------------------------------------------------
800 // directory operations
801 // ----------------------------------------------------------------------------
803 bool wxFileName::Mkdir( int perm
, int flags
)
805 return wxFileName::Mkdir(GetPath(), perm
, flags
);
808 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
810 if ( flags
& wxPATH_MKDIR_FULL
)
812 // split the path in components
814 filename
.AssignDir(dir
);
817 if ( filename
.HasVolume())
819 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
822 wxArrayString dirs
= filename
.GetDirs();
823 size_t count
= dirs
.GetCount();
824 for ( size_t i
= 0; i
< count
; i
++ )
827 #if defined(__WXMAC__) && !defined(__DARWIN__)
828 // relative pathnames are exactely the other way round under mac...
829 !filename
.IsAbsolute()
831 filename
.IsAbsolute()
834 currPath
+= wxFILE_SEP_PATH
;
837 if (!DirExists(currPath
))
839 if (!wxMkdir(currPath
, perm
))
841 // no need to try creating further directories
851 return ::wxMkdir( dir
, perm
);
854 bool wxFileName::Rmdir()
856 return wxFileName::Rmdir( GetPath() );
859 bool wxFileName::Rmdir( const wxString
&dir
)
861 return ::wxRmdir( dir
);
864 // ----------------------------------------------------------------------------
865 // path normalization
866 // ----------------------------------------------------------------------------
868 bool wxFileName::Normalize(int flags
,
872 // deal with env vars renaming first as this may seriously change the path
873 if ( flags
& wxPATH_NORM_ENV_VARS
)
875 wxString pathOrig
= GetFullPath(format
);
876 wxString path
= wxExpandEnvVars(pathOrig
);
877 if ( path
!= pathOrig
)
884 // the existing path components
885 wxArrayString dirs
= GetDirs();
887 // the path to prepend in front to make the path absolute
890 format
= GetFormat(format
);
892 // make the path absolute
893 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
897 curDir
.AssignCwd(GetVolume());
901 curDir
.AssignDir(cwd
);
904 // the path may be not absolute because it doesn't have the volume name
905 // but in this case we shouldn't modify the directory components of it
906 // but just set the current volume
907 if ( !HasVolume() && curDir
.HasVolume() )
909 SetVolume(curDir
.GetVolume());
913 // yes, it was the case - we don't need curDir then
919 // handle ~ stuff under Unix only
920 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
922 if ( !dirs
.IsEmpty() )
924 wxString dir
= dirs
[0u];
925 if ( !dir
.empty() && dir
[0u] == _T('~') )
927 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
934 // transform relative path into abs one
937 wxArrayString dirsNew
= curDir
.GetDirs();
938 size_t count
= dirs
.GetCount();
939 for ( size_t n
= 0; n
< count
; n
++ )
941 dirsNew
.Add(dirs
[n
]);
947 // now deal with ".", ".." and the rest
949 size_t count
= dirs
.GetCount();
950 for ( size_t n
= 0; n
< count
; n
++ )
952 wxString dir
= dirs
[n
];
954 if ( flags
& wxPATH_NORM_DOTS
)
956 if ( dir
== wxT(".") )
962 if ( dir
== wxT("..") )
964 if ( m_dirs
.IsEmpty() )
966 wxLogError(_("The path '%s' contains too many \"..\"!"),
967 GetFullPath().c_str());
971 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
976 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
984 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
985 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
988 if (GetShortcutTarget(GetFullPath(format
), filename
))
990 // Repeat this since we may now have a new path
991 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
993 filename
.MakeLower();
1001 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1003 // VZ: expand env vars here too?
1005 m_volume
.MakeLower();
1010 // we do have the path now
1012 // NB: need to do this before (maybe) calling Assign() below
1015 #if defined(__WIN32__)
1016 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1018 Assign(GetLongPath());
1025 // ----------------------------------------------------------------------------
1026 // get the shortcut target
1027 // ----------------------------------------------------------------------------
1029 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1030 // The .lnk file is a plain text file so it should be easy to
1031 // make it work. Hint from Google Groups:
1032 // "If you open up a lnk file, you'll see a
1033 // number, followed by a pound sign (#), followed by more text. The
1034 // number is the number of characters that follows the pound sign. The
1035 // characters after the pound sign are the command line (which _can_
1036 // include arguments) to be executed. Any path (e.g. \windows\program
1037 // files\myapp.exe) that includes spaces needs to be enclosed in
1038 // quotation marks."
1040 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1041 // The following lines are necessary under WinCE
1042 // #include "wx/msw/private.h"
1043 // #include <ole2.h>
1045 #if defined(__WXWINCE__)
1046 #include <shlguid.h>
1049 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1050 wxString
& targetFilename
,
1051 wxString
* arguments
)
1053 wxString path
, file
, ext
;
1054 wxSplitPath(shortcutPath
, & path
, & file
, & ext
);
1058 bool success
= false;
1060 // Assume it's not a shortcut if it doesn't end with lnk
1061 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1064 // create a ShellLink object
1065 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1066 IID_IShellLink
, (LPVOID
*) &psl
);
1068 if (SUCCEEDED(hres
))
1071 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1072 if (SUCCEEDED(hres
))
1074 WCHAR wsz
[MAX_PATH
];
1076 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1079 hres
= ppf
->Load(wsz
, 0);
1082 if (SUCCEEDED(hres
))
1085 // Wrong prototype in early versions
1086 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1087 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1089 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1091 targetFilename
= wxString(buf
);
1092 success
= (shortcutPath
!= targetFilename
);
1094 psl
->GetArguments(buf
, 2048);
1096 if (!args
.empty() && arguments
)
1108 #endif // __WIN32__ && !__WXWINCE__
1111 // ----------------------------------------------------------------------------
1112 // absolute/relative paths
1113 // ----------------------------------------------------------------------------
1115 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1117 // if our path doesn't start with a path separator, it's not an absolute
1122 if ( !GetVolumeSeparator(format
).empty() )
1124 // this format has volumes and an absolute path must have one, it's not
1125 // enough to have the full path to bean absolute file under Windows
1126 if ( GetVolume().empty() )
1133 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1135 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1137 // get cwd only once - small time saving
1138 wxString cwd
= wxGetCwd();
1139 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1140 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1142 bool withCase
= IsCaseSensitive(format
);
1144 // we can't do anything if the files live on different volumes
1145 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1151 // same drive, so we don't need our volume
1154 // remove common directories starting at the top
1155 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1156 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1159 fnBase
.m_dirs
.RemoveAt(0);
1162 // add as many ".." as needed
1163 size_t count
= fnBase
.m_dirs
.GetCount();
1164 for ( size_t i
= 0; i
< count
; i
++ )
1166 m_dirs
.Insert(wxT(".."), 0u);
1169 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1171 // a directory made relative with respect to itself is '.' under Unix
1172 // and DOS, by definition (but we don't have to insert "./" for the
1174 if ( m_dirs
.IsEmpty() && IsDir() )
1176 m_dirs
.Add(_T('.'));
1186 // ----------------------------------------------------------------------------
1187 // filename kind tests
1188 // ----------------------------------------------------------------------------
1190 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1192 wxFileName fn1
= *this,
1195 // get cwd only once - small time saving
1196 wxString cwd
= wxGetCwd();
1197 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1198 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1200 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1203 // TODO: compare inodes for Unix, this works even when filenames are
1204 // different but files are the same (symlinks) (VZ)
1210 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1212 // only Unix filenames are truely case-sensitive
1213 return GetFormat(format
) == wxPATH_UNIX
;
1217 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1219 // Inits to forbidden characters that are common to (almost) all platforms.
1220 wxString strForbiddenChars
= wxT("*?");
1222 // If asserts, wxPathFormat has been changed. In case of a new path format
1223 // addition, the following code might have to be updated.
1224 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1225 switch ( GetFormat(format
) )
1228 wxFAIL_MSG( wxT("Unknown path format") );
1229 // !! Fall through !!
1235 // On a Mac even names with * and ? are allowed (Tested with OS
1236 // 9.2.1 and OS X 10.2.5)
1237 strForbiddenChars
= wxEmptyString
;
1241 strForbiddenChars
+= wxT("\\/:\"<>|");
1248 return strForbiddenChars
;
1252 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1255 return wxEmptyString
;
1259 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1260 (GetFormat(format
) == wxPATH_VMS
) )
1262 sepVol
= wxFILE_SEP_DSK
;
1271 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1274 switch ( GetFormat(format
) )
1277 // accept both as native APIs do but put the native one first as
1278 // this is the one we use in GetFullPath()
1279 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1283 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1287 seps
= wxFILE_SEP_PATH_UNIX
;
1291 seps
= wxFILE_SEP_PATH_MAC
;
1295 seps
= wxFILE_SEP_PATH_VMS
;
1303 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1305 format
= GetFormat(format
);
1307 // under VMS the end of the path is ']', not the path separator used to
1308 // separate the components
1309 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1313 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1315 // wxString::Find() doesn't work as expected with NUL - it will always find
1316 // it, so test for it separately
1317 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1320 // ----------------------------------------------------------------------------
1321 // path components manipulation
1322 // ----------------------------------------------------------------------------
1324 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1328 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1333 const size_t len
= dir
.length();
1334 for ( size_t n
= 0; n
< len
; n
++ )
1336 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1338 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1347 void wxFileName::AppendDir( const wxString
& dir
)
1349 if ( IsValidDirComponent(dir
) )
1353 void wxFileName::PrependDir( const wxString
& dir
)
1358 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1360 if ( IsValidDirComponent(dir
) )
1361 m_dirs
.Insert(dir
, before
);
1364 void wxFileName::RemoveDir(size_t pos
)
1366 m_dirs
.RemoveAt(pos
);
1369 // ----------------------------------------------------------------------------
1371 // ----------------------------------------------------------------------------
1373 void wxFileName::SetFullName(const wxString
& fullname
)
1375 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1376 &m_name
, &m_ext
, &m_hasExt
);
1379 wxString
wxFileName::GetFullName() const
1381 wxString fullname
= m_name
;
1384 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1390 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1392 format
= GetFormat( format
);
1396 // return the volume with the path as well if requested
1397 if ( flags
& wxPATH_GET_VOLUME
)
1399 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1402 // the leading character
1407 fullpath
+= wxFILE_SEP_PATH_MAC
;
1412 fullpath
+= wxFILE_SEP_PATH_DOS
;
1416 wxFAIL_MSG( wxT("Unknown path format") );
1422 // normally the absolute file names start with a slash
1423 // with one exception: the ones like "~/foo.bar" don't
1425 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1427 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1433 // no leading character here but use this place to unset
1434 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1435 // as, if I understand correctly, there should never be a dot
1436 // before the closing bracket
1437 flags
&= ~wxPATH_GET_SEPARATOR
;
1440 if ( m_dirs
.empty() )
1442 // there is nothing more
1446 // then concatenate all the path components using the path separator
1447 if ( format
== wxPATH_VMS
)
1449 fullpath
+= wxT('[');
1452 const size_t dirCount
= m_dirs
.GetCount();
1453 for ( size_t i
= 0; i
< dirCount
; i
++ )
1458 if ( m_dirs
[i
] == wxT(".") )
1460 // skip appending ':', this shouldn't be done in this
1461 // case as "::" is interpreted as ".." under Unix
1465 // convert back from ".." to nothing
1466 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1467 fullpath
+= m_dirs
[i
];
1471 wxFAIL_MSG( wxT("Unexpected path format") );
1472 // still fall through
1476 fullpath
+= m_dirs
[i
];
1480 // TODO: What to do with ".." under VMS
1482 // convert back from ".." to nothing
1483 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1484 fullpath
+= m_dirs
[i
];
1488 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1489 fullpath
+= GetPathSeparator(format
);
1492 if ( format
== wxPATH_VMS
)
1494 fullpath
+= wxT(']');
1500 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1502 // we already have a function to get the path
1503 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1506 // now just add the file name and extension to it
1507 fullpath
+= GetFullName();
1512 // Return the short form of the path (returns identity on non-Windows platforms)
1513 wxString
wxFileName::GetShortPath() const
1515 wxString
path(GetFullPath());
1517 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1518 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1522 if ( ::GetShortPathName
1525 wxStringBuffer(pathOut
, sz
),
1537 // Return the long form of the path (returns identity on non-Windows platforms)
1538 wxString
wxFileName::GetLongPath() const
1541 path
= GetFullPath();
1543 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1545 #if wxUSE_DYNAMIC_LOADER
1546 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1548 // this is MT-safe as in the worst case we're going to resolve the function
1549 // twice -- but as the result is the same in both threads, it's ok
1550 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1551 if ( !s_pfnGetLongPathName
)
1553 static bool s_triedToLoad
= false;
1555 if ( !s_triedToLoad
)
1557 s_triedToLoad
= true;
1559 wxDynamicLibrary
dllKernel(_T("kernel32"));
1561 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1566 #endif // Unicode/ANSI
1568 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1570 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1571 dllKernel
.GetSymbol(GetLongPathName
);
1574 // note that kernel32.dll can be unloaded, it stays in memory
1575 // anyhow as all Win32 programs link to it and so it's safe to call
1576 // GetLongPathName() even after unloading it
1580 if ( s_pfnGetLongPathName
)
1582 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1585 if ( (*s_pfnGetLongPathName
)
1588 wxStringBuffer(pathOut
, dwSize
),
1596 #endif // wxUSE_DYNAMIC_LOADER
1598 // The OS didn't support GetLongPathName, or some other error.
1599 // We need to call FindFirstFile on each component in turn.
1601 WIN32_FIND_DATA findFileData
;
1605 pathOut
= GetVolume() +
1606 GetVolumeSeparator(wxPATH_DOS
) +
1607 GetPathSeparator(wxPATH_DOS
);
1609 pathOut
= wxEmptyString
;
1611 wxArrayString dirs
= GetDirs();
1612 dirs
.Add(GetFullName());
1616 size_t count
= dirs
.GetCount();
1617 for ( size_t i
= 0; i
< count
; i
++ )
1619 // We're using pathOut to collect the long-name path, but using a
1620 // temporary for appending the last path component which may be
1622 tmpPath
= pathOut
+ dirs
[i
];
1624 if ( tmpPath
.empty() )
1627 // can't see this being necessary? MF
1628 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1630 // Can't pass a drive and root dir to FindFirstFile,
1631 // so continue to next dir
1632 tmpPath
+= wxFILE_SEP_PATH
;
1637 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1638 if (hFind
== INVALID_HANDLE_VALUE
)
1640 // Error: most likely reason is that path doesn't exist, so
1641 // append any unprocessed parts and return
1642 for ( i
+= 1; i
< count
; i
++ )
1643 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1648 pathOut
+= findFileData
.cFileName
;
1649 if ( (i
< (count
-1)) )
1650 pathOut
+= wxFILE_SEP_PATH
;
1656 #endif // Win32/!Win32
1661 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1663 if (format
== wxPATH_NATIVE
)
1665 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1666 format
= wxPATH_DOS
;
1667 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1668 format
= wxPATH_MAC
;
1669 #elif defined(__VMS)
1670 format
= wxPATH_VMS
;
1672 format
= wxPATH_UNIX
;
1678 // ----------------------------------------------------------------------------
1679 // path splitting function
1680 // ----------------------------------------------------------------------------
1684 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
1685 wxString
*pstrVolume
,
1687 wxPathFormat format
)
1689 format
= GetFormat(format
);
1691 wxString fullpath
= fullpathWithVolume
;
1693 // special Windows UNC paths hack: transform \\share\path into share:path
1694 if ( format
== wxPATH_DOS
)
1696 if ( fullpath
.length() >= 4 &&
1697 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1698 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1700 fullpath
.erase(0, 2);
1702 size_t posFirstSlash
=
1703 fullpath
.find_first_of(GetPathTerminators(format
));
1704 if ( posFirstSlash
!= wxString::npos
)
1706 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1708 // UNC paths are always absolute, right? (FIXME)
1709 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1714 // We separate the volume here
1715 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1717 wxString sepVol
= GetVolumeSeparator(format
);
1719 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1720 if ( posFirstColon
!= wxString::npos
)
1724 *pstrVolume
= fullpath
.Left(posFirstColon
);
1727 // remove the volume name and the separator from the full path
1728 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1733 *pstrPath
= fullpath
;
1737 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1738 wxString
*pstrVolume
,
1743 wxPathFormat format
)
1745 format
= GetFormat(format
);
1748 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
1750 // find the positions of the last dot and last path separator in the path
1751 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1752 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
1754 // check whether this dot occurs at the very beginning of a path component
1755 if ( (posLastDot
!= wxString::npos
) &&
1757 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
1758 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
1760 // dot may be (and commonly -- at least under Unix -- is) the first
1761 // character of the filename, don't treat the entire filename as
1762 // extension in this case
1763 posLastDot
= wxString::npos
;
1766 // if we do have a dot and a slash, check that the dot is in the name part
1767 if ( (posLastDot
!= wxString::npos
) &&
1768 (posLastSlash
!= wxString::npos
) &&
1769 (posLastDot
< posLastSlash
) )
1771 // the dot is part of the path, not the start of the extension
1772 posLastDot
= wxString::npos
;
1775 // now fill in the variables provided by user
1778 if ( posLastSlash
== wxString::npos
)
1785 // take everything up to the path separator but take care to make
1786 // the path equal to something like '/', not empty, for the files
1787 // immediately under root directory
1788 size_t len
= posLastSlash
;
1790 // this rule does not apply to mac since we do not start with colons (sep)
1791 // except for relative paths
1792 if ( !len
&& format
!= wxPATH_MAC
)
1795 *pstrPath
= fullpath
.Left(len
);
1797 // special VMS hack: remove the initial bracket
1798 if ( format
== wxPATH_VMS
)
1800 if ( (*pstrPath
)[0u] == _T('[') )
1801 pstrPath
->erase(0, 1);
1808 // take all characters starting from the one after the last slash and
1809 // up to, but excluding, the last dot
1810 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1812 if ( posLastDot
== wxString::npos
)
1814 // take all until the end
1815 count
= wxString::npos
;
1817 else if ( posLastSlash
== wxString::npos
)
1821 else // have both dot and slash
1823 count
= posLastDot
- posLastSlash
- 1;
1826 *pstrName
= fullpath
.Mid(nStart
, count
);
1829 // finally deal with the extension here: we have an added complication that
1830 // extension may be empty (but present) as in "foo." where trailing dot
1831 // indicates the empty extension at the end -- and hence we must remember
1832 // that we have it independently of pstrExt
1833 if ( posLastDot
== wxString::npos
)
1843 // take everything after the dot
1845 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1852 void wxFileName::SplitPath(const wxString
& fullpath
,
1856 wxPathFormat format
)
1859 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1863 path
->Prepend(wxGetVolumeString(volume
, format
));
1867 // ----------------------------------------------------------------------------
1869 // ----------------------------------------------------------------------------
1873 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1874 const wxDateTime
*dtMod
,
1875 const wxDateTime
*dtCreate
)
1877 #if defined(__WIN32__)
1880 // VZ: please let me know how to do this if you can
1881 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1885 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1888 FILETIME ftAccess
, ftCreate
, ftWrite
;
1891 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1893 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1895 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1897 if ( ::SetFileTime(fh
,
1898 dtCreate
? &ftCreate
: NULL
,
1899 dtAccess
? &ftAccess
: NULL
,
1900 dtMod
? &ftWrite
: NULL
) )
1906 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1907 wxUnusedVar(dtCreate
);
1909 if ( !dtAccess
&& !dtMod
)
1911 // can't modify the creation time anyhow, don't try
1915 // if dtAccess or dtMod is not specified, use the other one (which must be
1916 // non NULL because of the test above) for both times
1918 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1919 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1920 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
1924 #else // other platform
1925 wxUnusedVar(dtAccess
);
1927 wxUnusedVar(dtCreate
);
1930 wxLogSysError(_("Failed to modify file times for '%s'"),
1931 GetFullPath().c_str());
1936 bool wxFileName::Touch()
1938 #if defined(__UNIX_LIKE__)
1939 // under Unix touching file is simple: just pass NULL to utime()
1940 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
1945 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1948 #else // other platform
1949 wxDateTime dtNow
= wxDateTime::Now();
1951 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1955 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1957 wxDateTime
*dtCreate
) const
1959 #if defined(__WIN32__)
1960 // we must use different methods for the files and directories under
1961 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1962 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1965 FILETIME ftAccess
, ftCreate
, ftWrite
;
1968 // implemented in msw/dir.cpp
1969 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
1970 FILETIME
*, FILETIME
*, FILETIME
*);
1972 // we should pass the path without the trailing separator to
1973 // wxGetDirectoryTimes()
1974 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
1975 &ftAccess
, &ftCreate
, &ftWrite
);
1979 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1982 ok
= ::GetFileTime(fh
,
1983 dtCreate
? &ftCreate
: NULL
,
1984 dtAccess
? &ftAccess
: NULL
,
1985 dtMod
? &ftWrite
: NULL
) != 0;
1996 ConvertFileTimeToWx(dtCreate
, ftCreate
);
1998 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2000 ConvertFileTimeToWx(dtMod
, ftWrite
);
2004 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2006 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2009 dtAccess
->Set(stBuf
.st_atime
);
2011 dtMod
->Set(stBuf
.st_mtime
);
2013 dtCreate
->Set(stBuf
.st_ctime
);
2017 #else // other platform
2018 wxUnusedVar(dtAccess
);
2020 wxUnusedVar(dtCreate
);
2023 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2024 GetFullPath().c_str());
2029 #endif // wxUSE_DATETIME
2032 // ----------------------------------------------------------------------------
2033 // file size functions
2034 // ----------------------------------------------------------------------------
2037 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2039 if (!wxFileExists(filename
))
2040 return wxInvalidSize
;
2042 #if defined(__WXPALMOS__)
2044 return wxInvalidSize
;
2045 #elif defined(__WIN32__)
2046 wxFileHandle
f(filename
, wxFileHandle::Read
);
2048 return wxInvalidSize
;
2050 DWORD lpFileSizeHigh
;
2051 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2052 if (ret
== INVALID_FILE_SIZE
)
2053 return wxInvalidSize
;
2055 // compose the low-order and high-order byte sizes
2056 return wxULongLong(ret
| (lpFileSizeHigh
<< sizeof(WORD
)*2));
2058 #else // ! __WIN32__
2061 #ifndef wxNEED_WX_UNISTD_H
2062 if (wxStat( filename
.fn_str() , &st
) != 0)
2064 if (wxStat( filename
, &st
) != 0)
2066 return wxInvalidSize
;
2067 return wxULongLong(st
.st_size
);
2072 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2073 const wxString
&nullsize
,
2076 static const double KILOBYTESIZE
= 1024.0;
2077 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2078 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2079 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2081 if (bs
== 0 || bs
== wxInvalidSize
)
2084 double bytesize
= bs
.ToDouble();
2085 if (bytesize
< KILOBYTESIZE
)
2086 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2087 if (bytesize
< MEGABYTESIZE
)
2088 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2089 if (bytesize
< GIGABYTESIZE
)
2090 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2091 if (bytesize
< TERABYTESIZE
)
2092 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2094 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2097 wxULongLong
wxFileName::GetSize() const
2099 return GetSize(GetFullPath());
2102 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2104 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2108 // ----------------------------------------------------------------------------
2109 // Mac-specific functions
2110 // ----------------------------------------------------------------------------
2114 const short kMacExtensionMaxLength
= 16 ;
2115 class MacDefaultExtensionRecord
2118 MacDefaultExtensionRecord()
2121 m_type
= m_creator
= 0 ;
2123 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
2125 wxStrcpy( m_ext
, from
.m_ext
) ;
2126 m_type
= from
.m_type
;
2127 m_creator
= from
.m_creator
;
2129 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
2131 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
2132 m_ext
[kMacExtensionMaxLength
] = 0 ;
2134 m_creator
= creator
;
2136 wxChar m_ext
[kMacExtensionMaxLength
] ;
2141 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
2143 bool gMacDefaultExtensionsInited
= false ;
2145 #include "wx/arrimpl.cpp"
2147 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
2149 MacDefaultExtensionArray gMacDefaultExtensions
;
2151 // load the default extensions
2152 MacDefaultExtensionRecord gDefaults
[] =
2154 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2155 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2156 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2159 static void MacEnsureDefaultExtensionsLoaded()
2161 if ( !gMacDefaultExtensionsInited
)
2163 // we could load the pc exchange prefs here too
2164 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2166 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2168 gMacDefaultExtensionsInited
= true ;
2172 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2175 FSCatalogInfo catInfo
;
2178 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2180 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2182 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2183 finfo
->fileType
= type
;
2184 finfo
->fileCreator
= creator
;
2185 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2192 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2195 FSCatalogInfo catInfo
;
2198 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2200 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2202 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2203 *type
= finfo
->fileType
;
2204 *creator
= finfo
->fileCreator
;
2211 bool wxFileName::MacSetDefaultTypeAndCreator()
2213 wxUint32 type
, creator
;
2214 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2217 return MacSetTypeAndCreator( type
, creator
) ;
2222 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2224 MacEnsureDefaultExtensionsLoaded() ;
2225 wxString extl
= ext
.Lower() ;
2226 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2228 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2230 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2231 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2238 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2240 MacEnsureDefaultExtensionsLoaded() ;
2241 MacDefaultExtensionRecord rec
;
2243 rec
.m_creator
= creator
;
2244 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
2245 gMacDefaultExtensions
.Add( rec
) ;