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 and
26 MSW unique volume names of the form \\?\Volume{GUID}\fullpath.
28 The latter provide a uniform way to access a volume regardless of
29 its current mount point, i.e. you can change a volume's mount
30 point from D: to E:, or even remove it, and still be able to
31 access it through its unique volume name. More on the subject can
32 be found in MSDN's article "Naming a Volume" that is currently at
33 http://msdn.microsoft.com/en-us/library/aa365248(VS.85).aspx.
36 wxPATH_MAC: Mac OS 8/9 only, not used any longer, absolute file
38 volume:dir1:...:dirN:filename
39 and the relative file names are either
40 :dir1:...:dirN:filename
43 (although :filename works as well).
44 Since the volume is just part of the file path, it is not
45 treated like a separate entity as it is done under DOS and
46 VMS, it is just treated as another dir.
48 wxPATH_VMS: VMS native format, absolute file names have the form
49 <device>:[dir1.dir2.dir3]file.txt
51 <device>:[000000.dir1.dir2.dir3]file.txt
53 the <device> is the physical device (i.e. disk). 000000 is the
54 root directory on the device which can be omitted.
56 Note that VMS uses different separators unlike Unix:
57 : always after the device. If the path does not contain : than
58 the default (the device of the current directory) is assumed.
59 [ start of directory specification
60 . separator between directory and subdirectory
61 ] between directory and file
64 // ============================================================================
66 // ============================================================================
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // For compilers that support precompilation, includes "wx.h".
73 #include "wx/wxprec.h"
81 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
83 #include "wx/dynarray.h"
90 #include "wx/filename.h"
91 #include "wx/private/filename.h"
92 #include "wx/tokenzr.h"
93 #include "wx/config.h" // for wxExpandEnvVars
94 #include "wx/dynlib.h"
96 #include "wx/longlong.h"
98 #if defined(__WIN32__) && defined(__MINGW32__)
99 #include "wx/msw/gccpriv.h"
103 #include "wx/msw/private.h"
104 #include <shlobj.h> // for CLSID_ShellLink
105 #include "wx/msw/missing.h"
108 #if defined(__WXMAC__)
109 #include "wx/osx/private.h" // includes mac headers
112 // utime() is POSIX so should normally be available on all Unices
114 #include <sys/types.h>
116 #include <sys/stat.h>
126 #include <sys/utime.h>
127 #include <sys/stat.h>
138 #define MAX_PATH _MAX_PATH
142 #define S_ISREG(mode) ((mode) & S_IFREG)
145 #define S_ISDIR(mode) ((mode) & S_IFDIR)
149 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
150 #endif // wxUSE_LONGLONG
155 // ----------------------------------------------------------------------------
157 // ----------------------------------------------------------------------------
159 // small helper class which opens and closes the file - we use it just to get
160 // a file handle for the given file name to pass it to some Win32 API function
161 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
172 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
174 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
175 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
176 // be changed when we open it because this class is used for setting
177 // access time (see #10567)
178 m_hFile
= ::CreateFile
180 filename
.t_str(), // name
181 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
182 : FILE_WRITE_ATTRIBUTES
,
183 FILE_SHARE_READ
| // sharing mode
184 FILE_SHARE_WRITE
, // (allow everything)
185 NULL
, // no secutity attr
186 OPEN_EXISTING
, // creation disposition
188 NULL
// no template file
191 if ( m_hFile
== INVALID_HANDLE_VALUE
)
193 if ( mode
== ReadAttr
)
195 wxLogSysError(_("Failed to open '%s' for reading"),
200 wxLogSysError(_("Failed to open '%s' for writing"),
208 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
210 if ( !::CloseHandle(m_hFile
) )
212 wxLogSysError(_("Failed to close file handle"));
217 // return true only if the file could be opened successfully
218 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
221 operator HANDLE() const { return m_hFile
; }
229 // ----------------------------------------------------------------------------
231 // ----------------------------------------------------------------------------
233 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
235 // Convert between wxDateTime and FILETIME which is a 64-bit value representing
236 // the number of 100-nanosecond intervals since January 1, 1601 UTC.
238 // This is the offset between FILETIME epoch and the Unix/wxDateTime Epoch.
239 static wxInt64 EPOCH_OFFSET_IN_MSEC
= wxLL(11644473600000);
241 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
243 wxLongLong
t(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
244 t
/= 10000; // Convert hundreds of nanoseconds to milliseconds.
245 t
-= EPOCH_OFFSET_IN_MSEC
;
250 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
252 // Undo the conversions above.
253 wxLongLong
t(dt
.GetValue());
254 t
+= EPOCH_OFFSET_IN_MSEC
;
257 ft
->dwHighDateTime
= t
.GetHi();
258 ft
->dwLowDateTime
= t
.GetLo();
261 #endif // wxUSE_DATETIME && __WIN32__
263 // return a string with the volume par
264 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
268 if ( !volume
.empty() )
270 format
= wxFileName::GetFormat(format
);
272 // Special Windows UNC paths hack, part 2: undo what we did in
273 // SplitPath() and make an UNC path if we have a drive which is not a
274 // single letter (hopefully the network shares can't be one letter only
275 // although I didn't find any authoritative docs on this)
276 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
278 // We also have to check for Windows unique volume names here and
279 // return it with '\\?\' prepended to it
280 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume
+ "\\",
283 path
<< "\\\\?\\" << volume
;
287 // it must be a UNC path
288 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
291 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
293 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
301 // return true if the character is a DOS path separator i.e. either a slash or
303 inline bool IsDOSPathSep(wxUniChar ch
)
305 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
308 // return true if the format used is the DOS/Windows one and the string looks
310 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
312 return format
== wxPATH_DOS
&&
313 path
.length() >= 4 && // "\\a" can't be a UNC path
314 IsDOSPathSep(path
[0u]) &&
315 IsDOSPathSep(path
[1u]) &&
316 !IsDOSPathSep(path
[2u]);
321 // Under Unix-ish systems (basically everything except Windows) we may work
322 // either with the file itself or its target if it's a symbolic link and we
323 // should dereference it, as determined by wxFileName::ShouldFollowLink() and
324 // the absence of the wxFILE_EXISTS_NO_FOLLOW flag. StatAny() can be used to
325 // stat the appropriate file with an extra twist that it also works when there
326 // is no wxFileName object at all, as is the case in static methods.
328 // Private implementation, don't call directly, use one of the overloads below.
329 bool DoStatAny(wxStructStat
& st
, wxString path
, bool dereference
)
331 // We need to remove any trailing slashes from the path because they could
332 // interfere with the symlink following decision: even if we use lstat(),
333 // it would still follow the symlink if we pass it a path with a slash at
334 // the end because the symlink resolution would happen while following the
335 // path and not for the last path element itself.
337 while ( wxEndsWithPathSeparator(path
) )
339 const size_t posLast
= path
.length() - 1;
342 // Don't turn "/" into empty string.
349 int ret
= dereference
? wxStat(path
, &st
) : wxLstat(path
, &st
);
353 // Overloads to use for a case when we don't have wxFileName object and when we
356 bool StatAny(wxStructStat
& st
, const wxString
& path
, int flags
)
358 return DoStatAny(st
, path
, !(flags
& wxFILE_EXISTS_NO_FOLLOW
));
362 bool StatAny(wxStructStat
& st
, const wxFileName
& fn
)
364 return DoStatAny(st
, fn
.GetFullPath(), fn
.ShouldFollowLink());
369 // ----------------------------------------------------------------------------
371 // ----------------------------------------------------------------------------
373 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
374 static const size_t wxMSWUniqueVolumePrefixLength
= 49;
376 } // anonymous namespace
378 // ============================================================================
380 // ============================================================================
382 // ----------------------------------------------------------------------------
383 // wxFileName construction
384 // ----------------------------------------------------------------------------
386 void wxFileName::Assign( const wxFileName
&filepath
)
388 m_volume
= filepath
.GetVolume();
389 m_dirs
= filepath
.GetDirs();
390 m_name
= filepath
.GetName();
391 m_ext
= filepath
.GetExt();
392 m_relative
= filepath
.m_relative
;
393 m_hasExt
= filepath
.m_hasExt
;
394 m_dontFollowLinks
= filepath
.m_dontFollowLinks
;
397 void wxFileName::Assign(const wxString
& volume
,
398 const wxString
& path
,
399 const wxString
& name
,
404 // we should ignore paths which look like UNC shares because we already
405 // have the volume here and the UNC notation (\\server\path) is only valid
406 // for paths which don't start with a volume, so prevent SetPath() from
407 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
409 // note also that this is a rather ugly way to do what we want (passing
410 // some kind of flag telling to ignore UNC paths to SetPath() would be
411 // better) but this is the safest thing to do to avoid breaking backwards
412 // compatibility in 2.8
413 if ( IsUNCPath(path
, format
) )
415 // remove one of the 2 leading backslashes to ensure that it's not
416 // recognized as an UNC path by SetPath()
417 wxString
pathNonUNC(path
, 1, wxString::npos
);
418 SetPath(pathNonUNC
, format
);
420 else // no UNC complications
422 SetPath(path
, format
);
432 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
436 if ( pathOrig
.empty() )
444 format
= GetFormat( format
);
446 // 0) deal with possible volume part first
449 SplitVolume(pathOrig
, &volume
, &path
, format
);
450 if ( !volume
.empty() )
457 // 1) Determine if the path is relative or absolute.
461 // we had only the volume
465 wxChar leadingChar
= path
[0u];
470 m_relative
= leadingChar
== wxT(':');
472 // We then remove a leading ":". The reason is in our
473 // storage form for relative paths:
474 // ":dir:file.txt" actually means "./dir/file.txt" in
475 // DOS notation and should get stored as
476 // (relative) (dir) (file.txt)
477 // "::dir:file.txt" actually means "../dir/file.txt"
478 // stored as (relative) (..) (dir) (file.txt)
479 // This is important only for the Mac as an empty dir
480 // actually means <UP>, whereas under DOS, double
481 // slashes can be ignored: "\\\\" is the same as "\\".
487 // TODO: what is the relative path format here?
492 wxFAIL_MSG( wxT("Unknown path format") );
493 // !! Fall through !!
496 m_relative
= leadingChar
!= wxT('/');
500 m_relative
= !IsPathSeparator(leadingChar
, format
);
505 // 2) Break up the path into its members. If the original path
506 // was just "/" or "\\", m_dirs will be empty. We know from
507 // the m_relative field, if this means "nothing" or "root dir".
509 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
511 while ( tn
.HasMoreTokens() )
513 wxString token
= tn
.GetNextToken();
515 // Remove empty token under DOS and Unix, interpret them
519 if (format
== wxPATH_MAC
)
520 m_dirs
.Add( wxT("..") );
530 void wxFileName::Assign(const wxString
& fullpath
,
533 wxString volume
, path
, name
, ext
;
535 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
537 Assign(volume
, path
, name
, ext
, hasExt
, format
);
540 void wxFileName::Assign(const wxString
& fullpathOrig
,
541 const wxString
& fullname
,
544 // always recognize fullpath as directory, even if it doesn't end with a
546 wxString fullpath
= fullpathOrig
;
547 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
549 fullpath
+= GetPathSeparator(format
);
552 wxString volume
, path
, name
, ext
;
555 // do some consistency checks: the name should be really just the filename
556 // and the path should be really just a path
557 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
559 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
561 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
562 wxT("the file name shouldn't contain the path") );
564 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
567 // This test makes no sense on an OpenVMS system.
568 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
569 wxT("the path shouldn't contain file name nor extension") );
571 Assign(volume
, path
, name
, ext
, hasExt
, format
);
574 void wxFileName::Assign(const wxString
& pathOrig
,
575 const wxString
& name
,
581 SplitVolume(pathOrig
, &volume
, &path
, format
);
583 Assign(volume
, path
, name
, ext
, format
);
586 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
588 Assign(dir
, wxEmptyString
, format
);
591 void wxFileName::Clear()
598 // we don't have any absolute path for now
604 // follow symlinks by default
605 m_dontFollowLinks
= false;
609 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
611 return wxFileName(file
, format
);
615 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
618 fn
.AssignDir(dir
, format
);
622 // ----------------------------------------------------------------------------
624 // ----------------------------------------------------------------------------
629 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
631 void RemoveTrailingSeparatorsFromPath(wxString
& strPath
)
633 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
634 // so remove all trailing backslashes from the path - but don't do this for
635 // the paths "d:\" (which are different from "d:"), for just "\" or for
636 // windows unique volume names ("\\?\Volume{GUID}\")
637 while ( wxEndsWithPathSeparator( strPath
) )
639 size_t len
= strPath
.length();
640 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) ||
641 (len
== wxMSWUniqueVolumePrefixLength
&&
642 wxFileName::IsMSWUniqueVolumeNamePath(strPath
)))
647 strPath
.Truncate(len
- 1);
651 #endif // __WINDOWS__ || __OS2__
654 wxFileSystemObjectExists(const wxString
& path
, int flags
)
657 // Should the existence of file/directory with this name be accepted, i.e.
658 // result in the true return value from this function?
659 const bool acceptFile
= (flags
& wxFILE_EXISTS_REGULAR
) != 0;
660 const bool acceptDir
= (flags
& wxFILE_EXISTS_DIR
) != 0;
662 wxString
strPath(path
);
664 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
667 // Ensure that the path doesn't have any trailing separators when
668 // checking for directories.
669 RemoveTrailingSeparatorsFromPath(strPath
);
672 // we must use GetFileAttributes() instead of the ANSI C functions because
673 // it can cope with network (UNC) paths unlike them
674 DWORD ret
= ::GetFileAttributes(strPath
.t_str());
676 if ( ret
== INVALID_FILE_ATTRIBUTES
)
679 if ( ret
& FILE_ATTRIBUTE_DIRECTORY
)
682 // Anything else must be a file (perhaps we should check for
683 // FILE_ATTRIBUTE_REPARSE_POINT?)
685 #elif defined(__OS2__)
688 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
689 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
693 FILESTATUS3 Info
= {{0}};
694 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
695 (void*) &Info
, sizeof(FILESTATUS3
));
697 if ( rc
== NO_ERROR
)
699 if ( Info
.attrFile
& FILE_DIRECTORY
)
705 // We consider that the path must exist if we get a sharing violation for
706 // it but we don't know what is it in this case.
707 if ( rc
== ERROR_SHARING_VIOLATION
)
708 return flags
& wxFILE_EXISTS_ANY
;
710 // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
713 #else // Non-MSW, non-OS/2
715 if ( !StatAny(st
, strPath
, flags
) )
718 if ( S_ISREG(st
.st_mode
) )
720 if ( S_ISDIR(st
.st_mode
) )
722 if ( S_ISLNK(st
.st_mode
) )
724 // Take care to not test for "!= 0" here as this would erroneously
725 // return true if only wxFILE_EXISTS_NO_FOLLOW, which is part of
726 // wxFILE_EXISTS_SYMLINK, is set too.
727 return (flags
& wxFILE_EXISTS_SYMLINK
) == wxFILE_EXISTS_SYMLINK
;
729 if ( S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
) )
730 return (flags
& wxFILE_EXISTS_DEVICE
) != 0;
731 if ( S_ISFIFO(st
.st_mode
) )
732 return (flags
& wxFILE_EXISTS_FIFO
) != 0;
733 if ( S_ISSOCK(st
.st_mode
) )
734 return (flags
& wxFILE_EXISTS_SOCKET
) != 0;
736 return flags
& wxFILE_EXISTS_ANY
;
740 } // anonymous namespace
742 bool wxFileName::FileExists() const
744 int flags
= wxFILE_EXISTS_REGULAR
;
745 if ( !ShouldFollowLink() )
746 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
748 return wxFileSystemObjectExists(GetFullPath(), flags
);
752 bool wxFileName::FileExists( const wxString
&filePath
)
754 return wxFileSystemObjectExists(filePath
, wxFILE_EXISTS_REGULAR
);
757 bool wxFileName::DirExists() const
759 int flags
= wxFILE_EXISTS_DIR
;
760 if ( !ShouldFollowLink() )
761 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
763 return Exists(GetPath(), flags
);
767 bool wxFileName::DirExists( const wxString
&dirPath
)
769 return wxFileSystemObjectExists(dirPath
, wxFILE_EXISTS_DIR
);
772 bool wxFileName::Exists(int flags
) const
774 // Notice that wxFILE_EXISTS_NO_FOLLOW may be specified in the flags even
775 // if our DontFollowLink() hadn't been called and we do honour it then. But
776 // if the user took the care of calling DontFollowLink(), it is always
777 // taken into account.
778 if ( !ShouldFollowLink() )
779 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
781 return wxFileSystemObjectExists(GetFullPath(), flags
);
785 bool wxFileName::Exists(const wxString
& path
, int flags
)
787 return wxFileSystemObjectExists(path
, flags
);
790 // ----------------------------------------------------------------------------
791 // CWD and HOME stuff
792 // ----------------------------------------------------------------------------
794 void wxFileName::AssignCwd(const wxString
& volume
)
796 AssignDir(wxFileName::GetCwd(volume
));
800 wxString
wxFileName::GetCwd(const wxString
& volume
)
802 // if we have the volume, we must get the current directory on this drive
803 // and to do this we have to chdir to this volume - at least under Windows,
804 // I don't know how to get the current drive on another volume elsewhere
807 if ( !volume
.empty() )
810 SetCwd(volume
+ GetVolumeSeparator());
813 wxString cwd
= ::wxGetCwd();
815 if ( !volume
.empty() )
823 bool wxFileName::SetCwd() const
825 return wxFileName::SetCwd( GetPath() );
828 bool wxFileName::SetCwd( const wxString
&cwd
)
830 return ::wxSetWorkingDirectory( cwd
);
833 void wxFileName::AssignHomeDir()
835 AssignDir(wxFileName::GetHomeDir());
838 wxString
wxFileName::GetHomeDir()
840 return ::wxGetHomeDir();
844 // ----------------------------------------------------------------------------
845 // CreateTempFileName
846 // ----------------------------------------------------------------------------
848 #if wxUSE_FILE || wxUSE_FFILE
851 #if !defined wx_fdopen && defined HAVE_FDOPEN
852 #define wx_fdopen fdopen
855 // NB: GetTempFileName() under Windows creates the file, so using
856 // O_EXCL there would fail
858 #define wxOPEN_EXCL 0
860 #define wxOPEN_EXCL O_EXCL
864 #ifdef wxOpenOSFHandle
865 #define WX_HAVE_DELETE_ON_CLOSE
866 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
868 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
870 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
872 DWORD disposition
= OPEN_ALWAYS
;
874 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
875 FILE_FLAG_DELETE_ON_CLOSE
;
877 HANDLE h
= ::CreateFile(filename
.t_str(), access
, 0, NULL
,
878 disposition
, attributes
, NULL
);
880 return wxOpenOSFHandle(h
, wxO_BINARY
);
882 #endif // wxOpenOSFHandle
885 // Helper to open the file
887 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
889 #ifdef WX_HAVE_DELETE_ON_CLOSE
891 return wxOpenWithDeleteOnClose(path
);
894 *deleteOnClose
= false;
896 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
901 // Helper to open the file and attach it to the wxFFile
903 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
906 *deleteOnClose
= false;
907 return file
->Open(path
, wxT("w+b"));
909 int fd
= wxTempOpen(path
, deleteOnClose
);
912 file
->Attach(wx_fdopen(fd
, "w+b"), path
);
913 return file
->IsOpened();
916 #endif // wxUSE_FFILE
920 #define WXFILEARGS(x, y) y
922 #define WXFILEARGS(x, y) x
924 #define WXFILEARGS(x, y) x, y
928 // Implementation of wxFileName::CreateTempFileName().
930 static wxString
wxCreateTempImpl(
931 const wxString
& prefix
,
932 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
933 bool *deleteOnClose
= NULL
)
935 #if wxUSE_FILE && wxUSE_FFILE
936 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
938 wxString path
, dir
, name
;
939 bool wantDeleteOnClose
= false;
943 // set the result to false initially
944 wantDeleteOnClose
= *deleteOnClose
;
945 *deleteOnClose
= false;
949 // easier if it alwasys points to something
950 deleteOnClose
= &wantDeleteOnClose
;
953 // use the directory specified by the prefix
954 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
958 dir
= wxFileName::GetTempDir();
961 #if defined(__WXWINCE__)
962 path
= dir
+ wxT("\\") + name
;
964 while (wxFileName::FileExists(path
))
966 path
= dir
+ wxT("\\") + name
;
971 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
972 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
973 wxStringBuffer(path
, MAX_PATH
+ 1)))
975 wxLogLastError(wxT("GetTempFileName"));
983 if ( !wxEndsWithPathSeparator(dir
) &&
984 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
986 path
+= wxFILE_SEP_PATH
;
991 #if defined(HAVE_MKSTEMP)
992 // scratch space for mkstemp()
993 path
+= wxT("XXXXXX");
995 // we need to copy the path to the buffer in which mkstemp() can modify it
996 wxCharBuffer
buf(path
.fn_str());
998 // cast is safe because the string length doesn't change
999 int fdTemp
= mkstemp( (char*)(const char*) buf
);
1002 // this might be not necessary as mkstemp() on most systems should have
1003 // already done it but it doesn't hurt neither...
1006 else // mkstemp() succeeded
1008 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1011 // avoid leaking the fd
1014 fileTemp
->Attach(fdTemp
);
1023 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"), path
);
1025 ffileTemp
->Open(path
, wxT("r+b"));
1036 #else // !HAVE_MKSTEMP
1040 path
+= wxT("XXXXXX");
1042 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
1043 if ( !mktemp( (char*)(const char*) buf
) )
1049 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1051 #else // !HAVE_MKTEMP (includes __DOS__)
1052 // generate the unique file name ourselves
1053 #if !defined(__DOS__)
1054 path
<< (unsigned int)getpid();
1059 static const size_t numTries
= 1000;
1060 for ( size_t n
= 0; n
< numTries
; n
++ )
1062 // 3 hex digits is enough for numTries == 1000 < 4096
1063 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
1064 if ( !wxFileName::FileExists(pathTry
) )
1073 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1075 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1077 #endif // Windows/!Windows
1081 wxLogSysError(_("Failed to create a temporary file name"));
1087 // open the file - of course, there is a race condition here, this is
1088 // why we always prefer using mkstemp()...
1090 if ( fileTemp
&& !fileTemp
->IsOpened() )
1092 *deleteOnClose
= wantDeleteOnClose
;
1093 int fd
= wxTempOpen(path
, deleteOnClose
);
1095 fileTemp
->Attach(fd
);
1102 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1104 *deleteOnClose
= wantDeleteOnClose
;
1105 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1111 // FIXME: If !ok here should we loop and try again with another
1112 // file name? That is the standard recourse if open(O_EXCL)
1113 // fails, though of course it should be protected against
1114 // possible infinite looping too.
1116 wxLogError(_("Failed to open temporary file."));
1126 static bool wxCreateTempImpl(
1127 const wxString
& prefix
,
1128 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1131 bool deleteOnClose
= true;
1133 *name
= wxCreateTempImpl(prefix
,
1134 WXFILEARGS(fileTemp
, ffileTemp
),
1137 bool ok
= !name
->empty();
1142 else if (ok
&& wxRemoveFile(*name
))
1150 static void wxAssignTempImpl(
1152 const wxString
& prefix
,
1153 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1156 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1158 if ( tempname
.empty() )
1160 // error, failed to get temp file name
1165 fn
->Assign(tempname
);
1170 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1172 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1176 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1178 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1181 #endif // wxUSE_FILE || wxUSE_FFILE
1186 wxString
wxCreateTempFileName(const wxString
& prefix
,
1188 bool *deleteOnClose
)
1190 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1193 bool wxCreateTempFile(const wxString
& prefix
,
1197 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1200 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1202 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1207 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1209 return wxCreateTempFileName(prefix
, fileTemp
);
1212 #endif // wxUSE_FILE
1217 wxString
wxCreateTempFileName(const wxString
& prefix
,
1219 bool *deleteOnClose
)
1221 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1224 bool wxCreateTempFile(const wxString
& prefix
,
1228 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1232 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1234 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1239 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1241 return wxCreateTempFileName(prefix
, fileTemp
);
1244 #endif // wxUSE_FFILE
1247 // ----------------------------------------------------------------------------
1248 // directory operations
1249 // ----------------------------------------------------------------------------
1251 // helper of GetTempDir(): check if the given directory exists and return it if
1252 // it does or an empty string otherwise
1256 wxString
CheckIfDirExists(const wxString
& dir
)
1258 return wxFileName::DirExists(dir
) ? dir
: wxString();
1261 } // anonymous namespace
1263 wxString
wxFileName::GetTempDir()
1265 // first try getting it from environment: this allows overriding the values
1266 // used by default if the user wants to create temporary files in another
1268 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1271 dir
= CheckIfDirExists(wxGetenv("TMP"));
1273 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1276 // if no environment variables are set, use the system default
1279 #if defined(__WXWINCE__)
1280 dir
= CheckIfDirExists(wxT("\\temp"));
1281 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1282 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1284 wxLogLastError(wxT("GetTempPath"));
1286 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1287 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1288 #endif // systems with native way
1290 else // we got directory from an environment variable
1292 // remove any trailing path separators, we don't want to ever return
1293 // them from this function for consistency
1294 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1295 if ( lastNonSep
== wxString::npos
)
1297 // the string consists entirely of separators, leave only one
1298 dir
= GetPathSeparator();
1302 dir
.erase(lastNonSep
+ 1);
1306 // fall back to hard coded value
1309 #ifdef __UNIX_LIKE__
1310 dir
= CheckIfDirExists("/tmp");
1312 #endif // __UNIX_LIKE__
1319 bool wxFileName::Mkdir( int perm
, int flags
) const
1321 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1324 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1326 if ( flags
& wxPATH_MKDIR_FULL
)
1328 // split the path in components
1329 wxFileName filename
;
1330 filename
.AssignDir(dir
);
1333 if ( filename
.HasVolume())
1335 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1338 wxArrayString dirs
= filename
.GetDirs();
1339 size_t count
= dirs
.GetCount();
1340 for ( size_t i
= 0; i
< count
; i
++ )
1342 if ( i
> 0 || filename
.IsAbsolute() )
1343 currPath
+= wxFILE_SEP_PATH
;
1344 currPath
+= dirs
[i
];
1346 if (!DirExists(currPath
))
1348 if (!wxMkdir(currPath
, perm
))
1350 // no need to try creating further directories
1360 return ::wxMkdir( dir
, perm
);
1363 bool wxFileName::Rmdir(int flags
) const
1365 return wxFileName::Rmdir( GetPath(), flags
);
1368 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1371 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1373 // SHFileOperation needs double null termination string
1374 // but without separator at the end of the path
1376 if ( path
.Last() == wxFILE_SEP_PATH
)
1380 SHFILEOPSTRUCT fileop
;
1381 wxZeroMemory(fileop
);
1382 fileop
.wFunc
= FO_DELETE
;
1383 fileop
.pFrom
= path
.t_str();
1384 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1386 // FOF_NOERRORUI is not defined in WinCE
1387 fileop
.fFlags
|= FOF_NOERRORUI
;
1390 int ret
= SHFileOperation(&fileop
);
1393 // SHFileOperation may return non-Win32 error codes, so the error
1394 // message can be incorrect
1395 wxLogApiError(wxT("SHFileOperation"), ret
);
1401 else if ( flags
& wxPATH_RMDIR_FULL
)
1402 #else // !__WINDOWS__
1403 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1404 #endif // !__WINDOWS__
1407 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1409 // When deleting the tree recursively, we are supposed to delete
1410 // this directory itself even when it is a symlink -- but without
1411 // following it. Do it here as wxRmdir() would simply follow if
1412 // called for a symlink.
1413 if ( wxFileName::Exists(dir
, wxFILE_EXISTS_SYMLINK
) )
1415 return wxRemoveFile(dir
);
1418 #endif // !__WINDOWS__
1421 if ( path
.Last() != wxFILE_SEP_PATH
)
1422 path
+= wxFILE_SEP_PATH
;
1426 if ( !d
.IsOpened() )
1431 // First delete all subdirectories: notice that we don't follow
1432 // symbolic links, potentially leading outside this directory, to avoid
1433 // unpleasant surprises.
1434 bool cont
= d
.GetFirst(&filename
, wxString(),
1435 wxDIR_DIRS
| wxDIR_HIDDEN
| wxDIR_NO_FOLLOW
);
1438 wxFileName::Rmdir(path
+ filename
, flags
);
1439 cont
= d
.GetNext(&filename
);
1443 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1445 // Delete all files too and, for the same reasons as above, don't
1446 // follow symlinks which could refer to the files outside of this
1447 // directory and just delete the symlinks themselves.
1448 cont
= d
.GetFirst(&filename
, wxString(),
1449 wxDIR_FILES
| wxDIR_HIDDEN
| wxDIR_NO_FOLLOW
);
1452 ::wxRemoveFile(path
+ filename
);
1453 cont
= d
.GetNext(&filename
);
1456 #endif // !__WINDOWS__
1459 return ::wxRmdir(dir
);
1462 // ----------------------------------------------------------------------------
1463 // path normalization
1464 // ----------------------------------------------------------------------------
1466 bool wxFileName::Normalize(int flags
,
1467 const wxString
& cwd
,
1468 wxPathFormat format
)
1470 // deal with env vars renaming first as this may seriously change the path
1471 if ( flags
& wxPATH_NORM_ENV_VARS
)
1473 wxString pathOrig
= GetFullPath(format
);
1474 wxString path
= wxExpandEnvVars(pathOrig
);
1475 if ( path
!= pathOrig
)
1481 // the existing path components
1482 wxArrayString dirs
= GetDirs();
1484 // the path to prepend in front to make the path absolute
1487 format
= GetFormat(format
);
1489 // set up the directory to use for making the path absolute later
1490 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1494 curDir
.AssignCwd(GetVolume());
1496 else // cwd provided
1498 curDir
.AssignDir(cwd
);
1502 // handle ~ stuff under Unix only
1503 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1505 if ( !dirs
.IsEmpty() )
1507 wxString dir
= dirs
[0u];
1508 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1510 // to make the path absolute use the home directory
1511 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1517 // transform relative path into abs one
1518 if ( curDir
.IsOk() )
1520 // this path may be relative because it doesn't have the volume name
1521 // and still have m_relative=true; in this case we shouldn't modify
1522 // our directory components but just set the current volume
1523 if ( !HasVolume() && curDir
.HasVolume() )
1525 SetVolume(curDir
.GetVolume());
1529 // yes, it was the case - we don't need curDir then
1534 // finally, prepend curDir to the dirs array
1535 wxArrayString dirsNew
= curDir
.GetDirs();
1536 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1538 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1539 // return for some reason an absolute path, then curDir maybe not be absolute!
1540 if ( !curDir
.m_relative
)
1542 // we have prepended an absolute path and thus we are now an absolute
1546 // else if (flags & wxPATH_NORM_ABSOLUTE):
1547 // should we warn the user that we didn't manage to make the path absolute?
1550 // now deal with ".", ".." and the rest
1552 size_t count
= dirs
.GetCount();
1553 for ( size_t n
= 0; n
< count
; n
++ )
1555 wxString dir
= dirs
[n
];
1557 if ( flags
& wxPATH_NORM_DOTS
)
1559 if ( dir
== wxT(".") )
1565 if ( dir
== wxT("..") )
1567 if ( m_dirs
.empty() )
1569 // We have more ".." than directory components so far.
1570 // Don't treat this as an error as the path could have been
1571 // entered by user so try to handle it reasonably: if the
1572 // path is absolute, just ignore the extra ".." because
1573 // "/.." is the same as "/". Otherwise, i.e. for relative
1574 // paths, keep ".." unchanged because removing it would
1575 // modify the file a relative path refers to.
1580 else // Normal case, go one step up.
1591 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1592 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1595 if (GetShortcutTarget(GetFullPath(format
), filename
))
1603 #if defined(__WIN32__)
1604 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1606 Assign(GetLongPath());
1610 // Change case (this should be kept at the end of the function, to ensure
1611 // that the path doesn't change any more after we normalize its case)
1612 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1614 m_volume
.MakeLower();
1618 // directory entries must be made lower case as well
1619 count
= m_dirs
.GetCount();
1620 for ( size_t i
= 0; i
< count
; i
++ )
1622 m_dirs
[i
].MakeLower();
1630 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1631 const wxString
& replacementFmtString
,
1632 wxPathFormat format
)
1634 // look into stringForm for the contents of the given environment variable
1636 if (envname
.empty() ||
1637 !wxGetEnv(envname
, &val
))
1642 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1643 // do not touch the file name and the extension
1645 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1646 stringForm
.Replace(val
, replacement
);
1648 // Now assign ourselves the modified path:
1649 Assign(stringForm
, GetFullName(), format
);
1655 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1657 wxString homedir
= wxGetHomeDir();
1658 if (homedir
.empty())
1661 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1662 // do not touch the file name and the extension
1664 stringForm
.Replace(homedir
, "~");
1666 // Now assign ourselves the modified path:
1667 Assign(stringForm
, GetFullName(), format
);
1672 // ----------------------------------------------------------------------------
1673 // get the shortcut target
1674 // ----------------------------------------------------------------------------
1676 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1677 // The .lnk file is a plain text file so it should be easy to
1678 // make it work. Hint from Google Groups:
1679 // "If you open up a lnk file, you'll see a
1680 // number, followed by a pound sign (#), followed by more text. The
1681 // number is the number of characters that follows the pound sign. The
1682 // characters after the pound sign are the command line (which _can_
1683 // include arguments) to be executed. Any path (e.g. \windows\program
1684 // files\myapp.exe) that includes spaces needs to be enclosed in
1685 // quotation marks."
1687 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1689 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1690 wxString
& targetFilename
,
1691 wxString
* arguments
) const
1693 wxString path
, file
, ext
;
1694 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1698 bool success
= false;
1700 // Assume it's not a shortcut if it doesn't end with lnk
1701 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1704 // create a ShellLink object
1705 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1706 IID_IShellLink
, (LPVOID
*) &psl
);
1708 if (SUCCEEDED(hres
))
1711 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1712 if (SUCCEEDED(hres
))
1714 WCHAR wsz
[MAX_PATH
];
1716 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1719 hres
= ppf
->Load(wsz
, 0);
1722 if (SUCCEEDED(hres
))
1725 // Wrong prototype in early versions
1726 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1727 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1729 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1731 targetFilename
= wxString(buf
);
1732 success
= (shortcutPath
!= targetFilename
);
1734 psl
->GetArguments(buf
, 2048);
1736 if (!args
.empty() && arguments
)
1748 #endif // __WIN32__ && !__WXWINCE__
1751 // ----------------------------------------------------------------------------
1752 // absolute/relative paths
1753 // ----------------------------------------------------------------------------
1755 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1757 // unix paths beginning with ~ are reported as being absolute
1758 if ( format
== wxPATH_UNIX
)
1760 if ( !m_dirs
.IsEmpty() )
1762 wxString dir
= m_dirs
[0u];
1764 if (!dir
.empty() && dir
[0u] == wxT('~'))
1769 // if our path doesn't start with a path separator, it's not an absolute
1774 if ( !GetVolumeSeparator(format
).empty() )
1776 // this format has volumes and an absolute path must have one, it's not
1777 // enough to have the full path to be an absolute file under Windows
1778 if ( GetVolume().empty() )
1785 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1787 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1789 // get cwd only once - small time saving
1790 wxString cwd
= wxGetCwd();
1791 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1792 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1794 bool withCase
= IsCaseSensitive(format
);
1796 // we can't do anything if the files live on different volumes
1797 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1803 // same drive, so we don't need our volume
1806 // remove common directories starting at the top
1807 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1808 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1811 fnBase
.m_dirs
.RemoveAt(0);
1814 // add as many ".." as needed
1815 size_t count
= fnBase
.m_dirs
.GetCount();
1816 for ( size_t i
= 0; i
< count
; i
++ )
1818 m_dirs
.Insert(wxT(".."), 0u);
1821 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1823 // a directory made relative with respect to itself is '.' under Unix
1824 // and DOS, by definition (but we don't have to insert "./" for the
1826 if ( m_dirs
.IsEmpty() && IsDir() )
1828 m_dirs
.Add(wxT('.'));
1838 // ----------------------------------------------------------------------------
1839 // filename kind tests
1840 // ----------------------------------------------------------------------------
1842 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1844 wxFileName fn1
= *this,
1847 // get cwd only once - small time saving
1848 wxString cwd
= wxGetCwd();
1849 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1850 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1852 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1855 #if defined(__UNIX__)
1856 wxStructStat st1
, st2
;
1857 if ( StatAny(st1
, fn1
) && StatAny(st2
, fn2
) )
1859 if ( st1
.st_ino
== st2
.st_ino
&& st1
.st_dev
== st2
.st_dev
)
1862 //else: It's not an error if one or both files don't exist.
1863 #endif // defined __UNIX__
1869 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1871 // only Unix filenames are truly case-sensitive
1872 return GetFormat(format
) == wxPATH_UNIX
;
1876 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1878 // Inits to forbidden characters that are common to (almost) all platforms.
1879 wxString strForbiddenChars
= wxT("*?");
1881 // If asserts, wxPathFormat has been changed. In case of a new path format
1882 // addition, the following code might have to be updated.
1883 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1884 switch ( GetFormat(format
) )
1887 wxFAIL_MSG( wxT("Unknown path format") );
1888 // !! Fall through !!
1894 // On a Mac even names with * and ? are allowed (Tested with OS
1895 // 9.2.1 and OS X 10.2.5)
1896 strForbiddenChars
.clear();
1900 strForbiddenChars
+= wxT("\\/:\"<>|");
1907 return strForbiddenChars
;
1911 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1914 return wxEmptyString
;
1918 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1919 (GetFormat(format
) == wxPATH_VMS
) )
1921 sepVol
= wxFILE_SEP_DSK
;
1930 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1933 switch ( GetFormat(format
) )
1936 // accept both as native APIs do but put the native one first as
1937 // this is the one we use in GetFullPath()
1938 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1942 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1946 seps
= wxFILE_SEP_PATH_UNIX
;
1950 seps
= wxFILE_SEP_PATH_MAC
;
1954 seps
= wxFILE_SEP_PATH_VMS
;
1962 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1964 format
= GetFormat(format
);
1966 // under VMS the end of the path is ']', not the path separator used to
1967 // separate the components
1968 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1972 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1974 // wxString::Find() doesn't work as expected with NUL - it will always find
1975 // it, so test for it separately
1976 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1981 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
1983 // return true if the format used is the DOS/Windows one and the string begins
1984 // with a Windows unique volume name ("\\?\Volume{guid}\")
1985 return format
== wxPATH_DOS
&&
1986 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
1987 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
1988 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
1991 // ----------------------------------------------------------------------------
1992 // path components manipulation
1993 // ----------------------------------------------------------------------------
1995 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1999 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
2004 const size_t len
= dir
.length();
2005 for ( size_t n
= 0; n
< len
; n
++ )
2007 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
2009 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
2018 bool wxFileName::AppendDir( const wxString
& dir
)
2020 if (!IsValidDirComponent(dir
))
2026 void wxFileName::PrependDir( const wxString
& dir
)
2031 bool wxFileName::InsertDir(size_t before
, const wxString
& dir
)
2033 if (!IsValidDirComponent(dir
))
2035 m_dirs
.Insert(dir
, before
);
2039 void wxFileName::RemoveDir(size_t pos
)
2041 m_dirs
.RemoveAt(pos
);
2044 // ----------------------------------------------------------------------------
2046 // ----------------------------------------------------------------------------
2048 void wxFileName::SetFullName(const wxString
& fullname
)
2050 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
2051 &m_name
, &m_ext
, &m_hasExt
);
2054 wxString
wxFileName::GetFullName() const
2056 wxString fullname
= m_name
;
2059 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
2065 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
2067 format
= GetFormat( format
);
2071 // return the volume with the path as well if requested
2072 if ( flags
& wxPATH_GET_VOLUME
)
2074 fullpath
+= wxGetVolumeString(GetVolume(), format
);
2077 // the leading character
2082 fullpath
+= wxFILE_SEP_PATH_MAC
;
2087 fullpath
+= wxFILE_SEP_PATH_DOS
;
2091 wxFAIL_MSG( wxT("Unknown path format") );
2097 fullpath
+= wxFILE_SEP_PATH_UNIX
;
2102 // no leading character here but use this place to unset
2103 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2104 // as, if I understand correctly, there should never be a dot
2105 // before the closing bracket
2106 flags
&= ~wxPATH_GET_SEPARATOR
;
2109 if ( m_dirs
.empty() )
2111 // there is nothing more
2115 // then concatenate all the path components using the path separator
2116 if ( format
== wxPATH_VMS
)
2118 fullpath
+= wxT('[');
2121 const size_t dirCount
= m_dirs
.GetCount();
2122 for ( size_t i
= 0; i
< dirCount
; i
++ )
2127 if ( m_dirs
[i
] == wxT(".") )
2129 // skip appending ':', this shouldn't be done in this
2130 // case as "::" is interpreted as ".." under Unix
2134 // convert back from ".." to nothing
2135 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2136 fullpath
+= m_dirs
[i
];
2140 wxFAIL_MSG( wxT("Unexpected path format") );
2141 // still fall through
2145 fullpath
+= m_dirs
[i
];
2149 // TODO: What to do with ".." under VMS
2151 // convert back from ".." to nothing
2152 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2153 fullpath
+= m_dirs
[i
];
2157 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2158 fullpath
+= GetPathSeparator(format
);
2161 if ( format
== wxPATH_VMS
)
2163 fullpath
+= wxT(']');
2169 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2171 // we already have a function to get the path
2172 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2175 // now just add the file name and extension to it
2176 fullpath
+= GetFullName();
2181 // Return the short form of the path (returns identity on non-Windows platforms)
2182 wxString
wxFileName::GetShortPath() const
2184 wxString
path(GetFullPath());
2186 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2187 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2191 if ( ::GetShortPathName
2194 wxStringBuffer(pathOut
, sz
),
2206 // Return the long form of the path (returns identity on non-Windows platforms)
2207 wxString
wxFileName::GetLongPath() const
2210 path
= GetFullPath();
2212 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2214 #if wxUSE_DYNLIB_CLASS
2215 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2217 // this is MT-safe as in the worst case we're going to resolve the function
2218 // twice -- but as the result is the same in both threads, it's ok
2219 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2220 if ( !s_pfnGetLongPathName
)
2222 static bool s_triedToLoad
= false;
2224 if ( !s_triedToLoad
)
2226 s_triedToLoad
= true;
2228 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2230 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2235 #endif // Unicode/ANSI
2237 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2239 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2240 dllKernel
.GetSymbol(GetLongPathName
);
2243 // note that kernel32.dll can be unloaded, it stays in memory
2244 // anyhow as all Win32 programs link to it and so it's safe to call
2245 // GetLongPathName() even after unloading it
2249 if ( s_pfnGetLongPathName
)
2251 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2254 if ( (*s_pfnGetLongPathName
)
2257 wxStringBuffer(pathOut
, dwSize
),
2265 #endif // wxUSE_DYNLIB_CLASS
2267 // The OS didn't support GetLongPathName, or some other error.
2268 // We need to call FindFirstFile on each component in turn.
2270 WIN32_FIND_DATA findFileData
;
2274 pathOut
= GetVolume() +
2275 GetVolumeSeparator(wxPATH_DOS
) +
2276 GetPathSeparator(wxPATH_DOS
);
2280 wxArrayString dirs
= GetDirs();
2281 dirs
.Add(GetFullName());
2285 size_t count
= dirs
.GetCount();
2286 for ( size_t i
= 0; i
< count
; i
++ )
2288 const wxString
& dir
= dirs
[i
];
2290 // We're using pathOut to collect the long-name path, but using a
2291 // temporary for appending the last path component which may be
2293 tmpPath
= pathOut
+ dir
;
2295 // We must not process "." or ".." here as they would be (unexpectedly)
2296 // replaced by the corresponding directory names so just leave them
2299 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2300 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2301 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2303 tmpPath
+= wxFILE_SEP_PATH
;
2308 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2309 if (hFind
== INVALID_HANDLE_VALUE
)
2311 // Error: most likely reason is that path doesn't exist, so
2312 // append any unprocessed parts and return
2313 for ( i
+= 1; i
< count
; i
++ )
2314 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2319 pathOut
+= findFileData
.cFileName
;
2320 if ( (i
< (count
-1)) )
2321 pathOut
+= wxFILE_SEP_PATH
;
2327 #endif // Win32/!Win32
2332 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2334 if (format
== wxPATH_NATIVE
)
2336 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2337 format
= wxPATH_DOS
;
2338 #elif defined(__VMS)
2339 format
= wxPATH_VMS
;
2341 format
= wxPATH_UNIX
;
2347 #ifdef wxHAS_FILESYSTEM_VOLUMES
2350 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2352 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2354 wxString
vol(drive
);
2355 vol
+= wxFILE_SEP_DSK
;
2356 if ( flags
& wxPATH_GET_SEPARATOR
)
2357 vol
+= wxFILE_SEP_PATH
;
2362 #endif // wxHAS_FILESYSTEM_VOLUMES
2364 // ----------------------------------------------------------------------------
2365 // path splitting function
2366 // ----------------------------------------------------------------------------
2370 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2371 wxString
*pstrVolume
,
2373 wxPathFormat format
)
2375 format
= GetFormat(format
);
2377 wxString fullpath
= fullpathWithVolume
;
2379 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2381 // special Windows unique volume names hack: transform
2382 // \\?\Volume{guid}\path into Volume{guid}:path
2383 // note: this check must be done before the check for UNC path
2385 // we know the last backslash from the unique volume name is located
2386 // there from IsMSWUniqueVolumeNamePath
2387 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2389 // paths starting with a unique volume name should always be absolute
2390 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2392 // remove the leading "\\?\" part
2393 fullpath
.erase(0, 4);
2395 else if ( IsUNCPath(fullpath
, format
) )
2397 // special Windows UNC paths hack: transform \\share\path into share:path
2399 fullpath
.erase(0, 2);
2401 size_t posFirstSlash
=
2402 fullpath
.find_first_of(GetPathTerminators(format
));
2403 if ( posFirstSlash
!= wxString::npos
)
2405 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2407 // UNC paths are always absolute, right? (FIXME)
2408 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2412 // We separate the volume here
2413 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2415 wxString sepVol
= GetVolumeSeparator(format
);
2417 // we have to exclude the case of a colon in the very beginning of the
2418 // string as it can't be a volume separator (nor can this be a valid
2419 // DOS file name at all but we'll leave dealing with this to our caller)
2420 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2421 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2425 *pstrVolume
= fullpath
.Left(posFirstColon
);
2428 // remove the volume name and the separator from the full path
2429 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2434 *pstrPath
= fullpath
;
2438 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2439 wxString
*pstrVolume
,
2444 wxPathFormat format
)
2446 format
= GetFormat(format
);
2449 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2451 // find the positions of the last dot and last path separator in the path
2452 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2453 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2455 // check whether this dot occurs at the very beginning of a path component
2456 if ( (posLastDot
!= wxString::npos
) &&
2458 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2459 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2461 // dot may be (and commonly -- at least under Unix -- is) the first
2462 // character of the filename, don't treat the entire filename as
2463 // extension in this case
2464 posLastDot
= wxString::npos
;
2467 // if we do have a dot and a slash, check that the dot is in the name part
2468 if ( (posLastDot
!= wxString::npos
) &&
2469 (posLastSlash
!= wxString::npos
) &&
2470 (posLastDot
< posLastSlash
) )
2472 // the dot is part of the path, not the start of the extension
2473 posLastDot
= wxString::npos
;
2476 // now fill in the variables provided by user
2479 if ( posLastSlash
== wxString::npos
)
2486 // take everything up to the path separator but take care to make
2487 // the path equal to something like '/', not empty, for the files
2488 // immediately under root directory
2489 size_t len
= posLastSlash
;
2491 // this rule does not apply to mac since we do not start with colons (sep)
2492 // except for relative paths
2493 if ( !len
&& format
!= wxPATH_MAC
)
2496 *pstrPath
= fullpath
.Left(len
);
2498 // special VMS hack: remove the initial bracket
2499 if ( format
== wxPATH_VMS
)
2501 if ( (*pstrPath
)[0u] == wxT('[') )
2502 pstrPath
->erase(0, 1);
2509 // take all characters starting from the one after the last slash and
2510 // up to, but excluding, the last dot
2511 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2513 if ( posLastDot
== wxString::npos
)
2515 // take all until the end
2516 count
= wxString::npos
;
2518 else if ( posLastSlash
== wxString::npos
)
2522 else // have both dot and slash
2524 count
= posLastDot
- posLastSlash
- 1;
2527 *pstrName
= fullpath
.Mid(nStart
, count
);
2530 // finally deal with the extension here: we have an added complication that
2531 // extension may be empty (but present) as in "foo." where trailing dot
2532 // indicates the empty extension at the end -- and hence we must remember
2533 // that we have it independently of pstrExt
2534 if ( posLastDot
== wxString::npos
)
2544 // take everything after the dot
2546 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2553 void wxFileName::SplitPath(const wxString
& fullpath
,
2557 wxPathFormat format
)
2560 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2564 path
->Prepend(wxGetVolumeString(volume
, format
));
2569 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2571 wxFileName
fn(fullpath
);
2573 return fn
.GetFullPath();
2576 // ----------------------------------------------------------------------------
2578 // ----------------------------------------------------------------------------
2582 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2583 const wxDateTime
*dtMod
,
2584 const wxDateTime
*dtCreate
) const
2586 #if defined(__WIN32__)
2587 FILETIME ftAccess
, ftCreate
, ftWrite
;
2590 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2592 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2594 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2600 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2602 wxLogError(_("Setting directory access times is not supported "
2603 "under this OS version"));
2608 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2612 path
= GetFullPath();
2616 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2619 if ( ::SetFileTime(fh
,
2620 dtCreate
? &ftCreate
: NULL
,
2621 dtAccess
? &ftAccess
: NULL
,
2622 dtMod
? &ftWrite
: NULL
) )
2627 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2628 wxUnusedVar(dtCreate
);
2630 if ( !dtAccess
&& !dtMod
)
2632 // can't modify the creation time anyhow, don't try
2636 // if dtAccess or dtMod is not specified, use the other one (which must be
2637 // non NULL because of the test above) for both times
2639 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2640 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2641 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2645 #else // other platform
2646 wxUnusedVar(dtAccess
);
2648 wxUnusedVar(dtCreate
);
2651 wxLogSysError(_("Failed to modify file times for '%s'"),
2652 GetFullPath().c_str());
2657 bool wxFileName::Touch() const
2659 #if defined(__UNIX_LIKE__)
2660 // under Unix touching file is simple: just pass NULL to utime()
2661 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2666 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2669 #else // other platform
2670 wxDateTime dtNow
= wxDateTime::Now();
2672 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2676 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2678 wxDateTime
*dtCreate
) const
2680 #if defined(__WIN32__)
2681 // we must use different methods for the files and directories under
2682 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2683 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2686 FILETIME ftAccess
, ftCreate
, ftWrite
;
2689 // implemented in msw/dir.cpp
2690 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2691 FILETIME
*, FILETIME
*, FILETIME
*);
2693 // we should pass the path without the trailing separator to
2694 // wxGetDirectoryTimes()
2695 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2696 &ftAccess
, &ftCreate
, &ftWrite
);
2700 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2703 ok
= ::GetFileTime(fh
,
2704 dtCreate
? &ftCreate
: NULL
,
2705 dtAccess
? &ftAccess
: NULL
,
2706 dtMod
? &ftWrite
: NULL
) != 0;
2717 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2719 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2721 ConvertFileTimeToWx(dtMod
, ftWrite
);
2725 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2726 // no need to test for IsDir() here
2728 if ( StatAny(stBuf
, *this) )
2730 // Android defines st_*time fields as unsigned long, but time_t as long,
2731 // hence the static_casts.
2733 dtAccess
->Set(static_cast<time_t>(stBuf
.st_atime
));
2735 dtMod
->Set(static_cast<time_t>(stBuf
.st_mtime
));
2737 dtCreate
->Set(static_cast<time_t>(stBuf
.st_ctime
));
2741 #else // other platform
2742 wxUnusedVar(dtAccess
);
2744 wxUnusedVar(dtCreate
);
2747 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2748 GetFullPath().c_str());
2753 #endif // wxUSE_DATETIME
2756 // ----------------------------------------------------------------------------
2757 // file size functions
2758 // ----------------------------------------------------------------------------
2763 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2765 if (!wxFileExists(filename
))
2766 return wxInvalidSize
;
2768 #if defined(__WIN32__)
2769 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2771 return wxInvalidSize
;
2773 DWORD lpFileSizeHigh
;
2774 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2775 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2776 return wxInvalidSize
;
2778 return wxULongLong(lpFileSizeHigh
, ret
);
2779 #else // ! __WIN32__
2781 if (wxStat( filename
, &st
) != 0)
2782 return wxInvalidSize
;
2783 return wxULongLong(st
.st_size
);
2788 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2789 const wxString
&nullsize
,
2791 wxSizeConvention conv
)
2793 // deal with trivial case first
2794 if ( bs
== 0 || bs
== wxInvalidSize
)
2797 // depending on the convention used the multiplier may be either 1000 or
2798 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2799 double multiplier
= 1024.;
2804 case wxSIZE_CONV_TRADITIONAL
:
2805 // nothing to do, this corresponds to the default values of both
2806 // the multiplier and infix string
2809 case wxSIZE_CONV_IEC
:
2813 case wxSIZE_CONV_SI
:
2818 const double kiloByteSize
= multiplier
;
2819 const double megaByteSize
= multiplier
* kiloByteSize
;
2820 const double gigaByteSize
= multiplier
* megaByteSize
;
2821 const double teraByteSize
= multiplier
* gigaByteSize
;
2823 const double bytesize
= bs
.ToDouble();
2826 if ( bytesize
< kiloByteSize
)
2827 result
.Printf("%s B", bs
.ToString());
2828 else if ( bytesize
< megaByteSize
)
2829 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2830 else if (bytesize
< gigaByteSize
)
2831 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2832 else if (bytesize
< teraByteSize
)
2833 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2835 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2840 wxULongLong
wxFileName::GetSize() const
2842 return GetSize(GetFullPath());
2845 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2847 wxSizeConvention conv
) const
2849 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2852 #endif // wxUSE_LONGLONG
2854 // ----------------------------------------------------------------------------
2855 // Mac-specific functions
2856 // ----------------------------------------------------------------------------
2858 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2863 class MacDefaultExtensionRecord
2866 MacDefaultExtensionRecord()
2872 // default copy ctor, assignment operator and dtor are ok
2874 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2878 m_creator
= creator
;
2886 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2888 bool gMacDefaultExtensionsInited
= false;
2890 #include "wx/arrimpl.cpp"
2892 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2894 MacDefaultExtensionArray gMacDefaultExtensions
;
2896 // load the default extensions
2897 const MacDefaultExtensionRecord gDefaults
[] =
2899 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2900 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2901 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2904 void MacEnsureDefaultExtensionsLoaded()
2906 if ( !gMacDefaultExtensionsInited
)
2908 // we could load the pc exchange prefs here too
2909 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2911 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2913 gMacDefaultExtensionsInited
= true;
2917 } // anonymous namespace
2919 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2922 FSCatalogInfo catInfo
;
2925 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2927 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2929 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2930 finfo
->fileType
= type
;
2931 finfo
->fileCreator
= creator
;
2932 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2939 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2942 FSCatalogInfo catInfo
;
2945 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2947 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2949 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2950 *type
= finfo
->fileType
;
2951 *creator
= finfo
->fileCreator
;
2958 bool wxFileName::MacSetDefaultTypeAndCreator()
2960 wxUint32 type
, creator
;
2961 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2964 return MacSetTypeAndCreator( type
, creator
) ;
2969 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2971 MacEnsureDefaultExtensionsLoaded() ;
2972 wxString extl
= ext
.Lower() ;
2973 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2975 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2977 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2978 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2985 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2987 MacEnsureDefaultExtensionsLoaded();
2988 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2989 gMacDefaultExtensions
.Add( rec
);
2992 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON