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"
97 #if defined(__WIN32__) && defined(__MINGW32__)
98 #include "wx/msw/gccpriv.h"
102 #include "wx/msw/private.h"
105 #if defined(__WXMAC__)
106 #include "wx/osx/private.h" // includes mac headers
109 // utime() is POSIX so should normally be available on all Unices
111 #include <sys/types.h>
113 #include <sys/stat.h>
123 #include <sys/utime.h>
124 #include <sys/stat.h>
135 #define MAX_PATH _MAX_PATH
139 #define S_ISREG(mode) ((mode) & S_IFREG)
142 #define S_ISDIR(mode) ((mode) & S_IFDIR)
146 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
147 #endif // wxUSE_LONGLONG
152 // ----------------------------------------------------------------------------
154 // ----------------------------------------------------------------------------
156 // small helper class which opens and closes the file - we use it just to get
157 // a file handle for the given file name to pass it to some Win32 API function
158 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
169 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
171 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
172 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
173 // be changed when we open it because this class is used for setting
174 // access time (see #10567)
175 m_hFile
= ::CreateFile
177 filename
.t_str(), // name
178 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
179 : FILE_WRITE_ATTRIBUTES
,
180 FILE_SHARE_READ
| // sharing mode
181 FILE_SHARE_WRITE
, // (allow everything)
182 NULL
, // no secutity attr
183 OPEN_EXISTING
, // creation disposition
185 NULL
// no template file
188 if ( m_hFile
== INVALID_HANDLE_VALUE
)
190 if ( mode
== ReadAttr
)
192 wxLogSysError(_("Failed to open '%s' for reading"),
197 wxLogSysError(_("Failed to open '%s' for writing"),
205 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
207 if ( !::CloseHandle(m_hFile
) )
209 wxLogSysError(_("Failed to close file handle"));
214 // return true only if the file could be opened successfully
215 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
218 operator HANDLE() const { return m_hFile
; }
226 // ----------------------------------------------------------------------------
228 // ----------------------------------------------------------------------------
230 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
232 // convert between wxDateTime and FILETIME which is a 64-bit value representing
233 // the number of 100-nanosecond intervals since January 1, 1601.
235 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
237 FILETIME ftcopy
= ft
;
239 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
241 wxLogLastError(wxT("FileTimeToLocalFileTime"));
245 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
247 wxLogLastError(wxT("FileTimeToSystemTime"));
250 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
251 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
254 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
257 st
.wDay
= dt
.GetDay();
258 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
259 st
.wYear
= (WORD
)dt
.GetYear();
260 st
.wHour
= dt
.GetHour();
261 st
.wMinute
= dt
.GetMinute();
262 st
.wSecond
= dt
.GetSecond();
263 st
.wMilliseconds
= dt
.GetMillisecond();
266 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
268 wxLogLastError(wxT("SystemTimeToFileTime"));
271 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
273 wxLogLastError(wxT("LocalFileTimeToFileTime"));
277 #endif // wxUSE_DATETIME && __WIN32__
279 // return a string with the volume par
280 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
284 if ( !volume
.empty() )
286 format
= wxFileName::GetFormat(format
);
288 // Special Windows UNC paths hack, part 2: undo what we did in
289 // SplitPath() and make an UNC path if we have a drive which is not a
290 // single letter (hopefully the network shares can't be one letter only
291 // although I didn't find any authoritative docs on this)
292 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
294 // We also have to check for Windows unique volume names here and
295 // return it with '\\?\' prepended to it
296 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume
+ "\\",
299 path
<< "\\\\?\\" << volume
;
303 // it must be a UNC path
304 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
307 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
309 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
317 // return true if the character is a DOS path separator i.e. either a slash or
319 inline bool IsDOSPathSep(wxUniChar ch
)
321 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
324 // return true if the format used is the DOS/Windows one and the string looks
326 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
328 return format
== wxPATH_DOS
&&
329 path
.length() >= 4 && // "\\a" can't be a UNC path
330 IsDOSPathSep(path
[0u]) &&
331 IsDOSPathSep(path
[1u]) &&
332 !IsDOSPathSep(path
[2u]);
337 // Under Unix-ish systems (basically everything except Windows) we may work
338 // either with the file itself or its target if it's a symbolic link and we
339 // should dereference it, as determined by wxFileName::ShouldFollowLink() and
340 // the absence of the wxFILE_EXISTS_NO_FOLLOW flag. StatAny() can be used to
341 // stat the appropriate file with an extra twist that it also works when there
342 // is no wxFileName object at all, as is the case in static methods.
344 // Private implementation, don't call directly, use one of the overloads below.
345 bool DoStatAny(wxStructStat
& st
, wxString path
, bool dereference
)
347 // We need to remove any trailing slashes from the path because they could
348 // interfere with the symlink following decision: even if we use lstat(),
349 // it would still follow the symlink if we pass it a path with a slash at
350 // the end because the symlink resolution would happen while following the
351 // path and not for the last path element itself.
353 while ( wxEndsWithPathSeparator(path
) )
355 const size_t posLast
= path
.length() - 1;
358 // Don't turn "/" into empty string.
365 int ret
= dereference
? wxStat(path
, &st
) : wxLstat(path
, &st
);
369 // Overloads to use for a case when we don't have wxFileName object and when we
372 bool StatAny(wxStructStat
& st
, const wxString
& path
, int flags
)
374 return DoStatAny(st
, path
, !(flags
& wxFILE_EXISTS_NO_FOLLOW
));
378 bool StatAny(wxStructStat
& st
, const wxFileName
& fn
)
380 return DoStatAny(st
, fn
.GetFullPath(), fn
.ShouldFollowLink());
385 // ----------------------------------------------------------------------------
387 // ----------------------------------------------------------------------------
389 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
390 static const size_t wxMSWUniqueVolumePrefixLength
= 49;
392 } // anonymous namespace
394 // ============================================================================
396 // ============================================================================
398 // ----------------------------------------------------------------------------
399 // wxFileName construction
400 // ----------------------------------------------------------------------------
402 void wxFileName::Assign( const wxFileName
&filepath
)
404 m_volume
= filepath
.GetVolume();
405 m_dirs
= filepath
.GetDirs();
406 m_name
= filepath
.GetName();
407 m_ext
= filepath
.GetExt();
408 m_relative
= filepath
.m_relative
;
409 m_hasExt
= filepath
.m_hasExt
;
410 m_dontFollowLinks
= filepath
.m_dontFollowLinks
;
413 void wxFileName::Assign(const wxString
& volume
,
414 const wxString
& path
,
415 const wxString
& name
,
420 // we should ignore paths which look like UNC shares because we already
421 // have the volume here and the UNC notation (\\server\path) is only valid
422 // for paths which don't start with a volume, so prevent SetPath() from
423 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
425 // note also that this is a rather ugly way to do what we want (passing
426 // some kind of flag telling to ignore UNC paths to SetPath() would be
427 // better) but this is the safest thing to do to avoid breaking backwards
428 // compatibility in 2.8
429 if ( IsUNCPath(path
, format
) )
431 // remove one of the 2 leading backslashes to ensure that it's not
432 // recognized as an UNC path by SetPath()
433 wxString
pathNonUNC(path
, 1, wxString::npos
);
434 SetPath(pathNonUNC
, format
);
436 else // no UNC complications
438 SetPath(path
, format
);
448 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
452 if ( pathOrig
.empty() )
460 format
= GetFormat( format
);
462 // 0) deal with possible volume part first
465 SplitVolume(pathOrig
, &volume
, &path
, format
);
466 if ( !volume
.empty() )
473 // 1) Determine if the path is relative or absolute.
477 // we had only the volume
481 wxChar leadingChar
= path
[0u];
486 m_relative
= leadingChar
== wxT(':');
488 // We then remove a leading ":". The reason is in our
489 // storage form for relative paths:
490 // ":dir:file.txt" actually means "./dir/file.txt" in
491 // DOS notation and should get stored as
492 // (relative) (dir) (file.txt)
493 // "::dir:file.txt" actually means "../dir/file.txt"
494 // stored as (relative) (..) (dir) (file.txt)
495 // This is important only for the Mac as an empty dir
496 // actually means <UP>, whereas under DOS, double
497 // slashes can be ignored: "\\\\" is the same as "\\".
503 // TODO: what is the relative path format here?
508 wxFAIL_MSG( wxT("Unknown path format") );
509 // !! Fall through !!
512 m_relative
= leadingChar
!= wxT('/');
516 m_relative
= !IsPathSeparator(leadingChar
, format
);
521 // 2) Break up the path into its members. If the original path
522 // was just "/" or "\\", m_dirs will be empty. We know from
523 // the m_relative field, if this means "nothing" or "root dir".
525 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
527 while ( tn
.HasMoreTokens() )
529 wxString token
= tn
.GetNextToken();
531 // Remove empty token under DOS and Unix, interpret them
535 if (format
== wxPATH_MAC
)
536 m_dirs
.Add( wxT("..") );
546 void wxFileName::Assign(const wxString
& fullpath
,
549 wxString volume
, path
, name
, ext
;
551 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
553 Assign(volume
, path
, name
, ext
, hasExt
, format
);
556 void wxFileName::Assign(const wxString
& fullpathOrig
,
557 const wxString
& fullname
,
560 // always recognize fullpath as directory, even if it doesn't end with a
562 wxString fullpath
= fullpathOrig
;
563 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
565 fullpath
+= GetPathSeparator(format
);
568 wxString volume
, path
, name
, ext
;
571 // do some consistency checks: the name should be really just the filename
572 // and the path should be really just a path
573 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
575 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
577 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
578 wxT("the file name shouldn't contain the path") );
580 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
583 // This test makes no sense on an OpenVMS system.
584 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
585 wxT("the path shouldn't contain file name nor extension") );
587 Assign(volume
, path
, name
, ext
, hasExt
, format
);
590 void wxFileName::Assign(const wxString
& pathOrig
,
591 const wxString
& name
,
597 SplitVolume(pathOrig
, &volume
, &path
, format
);
599 Assign(volume
, path
, name
, ext
, format
);
602 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
604 Assign(dir
, wxEmptyString
, format
);
607 void wxFileName::Clear()
613 m_ext
= wxEmptyString
;
615 // we don't have any absolute path for now
621 // follow symlinks by default
622 m_dontFollowLinks
= false;
626 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
628 return wxFileName(file
, format
);
632 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
635 fn
.AssignDir(dir
, format
);
639 // ----------------------------------------------------------------------------
641 // ----------------------------------------------------------------------------
646 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
648 void RemoveTrailingSeparatorsFromPath(wxString
& strPath
)
650 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
651 // so remove all trailing backslashes from the path - but don't do this for
652 // the paths "d:\" (which are different from "d:"), for just "\" or for
653 // windows unique volume names ("\\?\Volume{GUID}\")
654 while ( wxEndsWithPathSeparator( strPath
) )
656 size_t len
= strPath
.length();
657 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) ||
658 (len
== wxMSWUniqueVolumePrefixLength
&&
659 wxFileName::IsMSWUniqueVolumeNamePath(strPath
)))
664 strPath
.Truncate(len
- 1);
668 #endif // __WINDOWS__ || __OS2__
671 wxFileSystemObjectExists(const wxString
& path
, int flags
)
674 // Should the existence of file/directory with this name be accepted, i.e.
675 // result in the true return value from this function?
676 const bool acceptFile
= (flags
& wxFILE_EXISTS_REGULAR
) != 0;
677 const bool acceptDir
= (flags
& wxFILE_EXISTS_DIR
) != 0;
679 wxString
strPath(path
);
681 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
684 // Ensure that the path doesn't have any trailing separators when
685 // checking for directories.
686 RemoveTrailingSeparatorsFromPath(strPath
);
689 // we must use GetFileAttributes() instead of the ANSI C functions because
690 // it can cope with network (UNC) paths unlike them
691 DWORD ret
= ::GetFileAttributes(strPath
.t_str());
693 if ( ret
== INVALID_FILE_ATTRIBUTES
)
696 if ( ret
& FILE_ATTRIBUTE_DIRECTORY
)
699 // Anything else must be a file (perhaps we should check for
700 // FILE_ATTRIBUTE_REPARSE_POINT?)
702 #elif defined(__OS2__)
705 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
706 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
710 FILESTATUS3 Info
= {{0}};
711 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
712 (void*) &Info
, sizeof(FILESTATUS3
));
714 if ( rc
== NO_ERROR
)
716 if ( Info
.attrFile
& FILE_DIRECTORY
)
722 // We consider that the path must exist if we get a sharing violation for
723 // it but we don't know what is it in this case.
724 if ( rc
== ERROR_SHARING_VIOLATION
)
725 return flags
& wxFILE_EXISTS_ANY
;
727 // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
730 #else // Non-MSW, non-OS/2
732 if ( !StatAny(st
, strPath
, flags
) )
735 if ( S_ISREG(st
.st_mode
) )
737 if ( S_ISDIR(st
.st_mode
) )
739 if ( S_ISLNK(st
.st_mode
) )
740 return (flags
& wxFILE_EXISTS_SYMLINK
) != 0;
741 if ( S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
) )
742 return (flags
& wxFILE_EXISTS_DEVICE
) != 0;
743 if ( S_ISFIFO(st
.st_mode
) )
744 return (flags
& wxFILE_EXISTS_FIFO
) != 0;
745 if ( S_ISSOCK(st
.st_mode
) )
746 return (flags
& wxFILE_EXISTS_SOCKET
) != 0;
748 return flags
& wxFILE_EXISTS_ANY
;
752 } // anonymous namespace
754 bool wxFileName::FileExists() const
756 int flags
= wxFILE_EXISTS_REGULAR
;
757 if ( !ShouldFollowLink() )
758 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
760 return wxFileSystemObjectExists(GetFullPath(), flags
);
764 bool wxFileName::FileExists( const wxString
&filePath
)
766 return wxFileSystemObjectExists(filePath
, wxFILE_EXISTS_REGULAR
);
769 bool wxFileName::DirExists() const
771 int flags
= wxFILE_EXISTS_DIR
;
772 if ( !ShouldFollowLink() )
773 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
775 return Exists(GetPath(), flags
);
779 bool wxFileName::DirExists( const wxString
&dirPath
)
781 return wxFileSystemObjectExists(dirPath
, wxFILE_EXISTS_DIR
);
784 bool wxFileName::Exists(int flags
) const
786 // Notice that wxFILE_EXISTS_NO_FOLLOW may be specified in the flags even
787 // if our DontFollowLink() hadn't been called and we do honour it then. But
788 // if the user took the care of calling DontFollowLink(), it is always
789 // taken into account.
790 if ( !ShouldFollowLink() )
791 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
793 return wxFileSystemObjectExists(GetFullPath(), flags
);
797 bool wxFileName::Exists(const wxString
& path
, int flags
)
799 return wxFileSystemObjectExists(path
, flags
);
802 // ----------------------------------------------------------------------------
803 // CWD and HOME stuff
804 // ----------------------------------------------------------------------------
806 void wxFileName::AssignCwd(const wxString
& volume
)
808 AssignDir(wxFileName::GetCwd(volume
));
812 wxString
wxFileName::GetCwd(const wxString
& volume
)
814 // if we have the volume, we must get the current directory on this drive
815 // and to do this we have to chdir to this volume - at least under Windows,
816 // I don't know how to get the current drive on another volume elsewhere
819 if ( !volume
.empty() )
822 SetCwd(volume
+ GetVolumeSeparator());
825 wxString cwd
= ::wxGetCwd();
827 if ( !volume
.empty() )
835 bool wxFileName::SetCwd() const
837 return wxFileName::SetCwd( GetPath() );
840 bool wxFileName::SetCwd( const wxString
&cwd
)
842 return ::wxSetWorkingDirectory( cwd
);
845 void wxFileName::AssignHomeDir()
847 AssignDir(wxFileName::GetHomeDir());
850 wxString
wxFileName::GetHomeDir()
852 return ::wxGetHomeDir();
856 // ----------------------------------------------------------------------------
857 // CreateTempFileName
858 // ----------------------------------------------------------------------------
860 #if wxUSE_FILE || wxUSE_FFILE
863 #if !defined wx_fdopen && defined HAVE_FDOPEN
864 #define wx_fdopen fdopen
867 // NB: GetTempFileName() under Windows creates the file, so using
868 // O_EXCL there would fail
870 #define wxOPEN_EXCL 0
872 #define wxOPEN_EXCL O_EXCL
876 #ifdef wxOpenOSFHandle
877 #define WX_HAVE_DELETE_ON_CLOSE
878 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
880 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
882 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
884 DWORD disposition
= OPEN_ALWAYS
;
886 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
887 FILE_FLAG_DELETE_ON_CLOSE
;
889 HANDLE h
= ::CreateFile(filename
.t_str(), access
, 0, NULL
,
890 disposition
, attributes
, NULL
);
892 return wxOpenOSFHandle(h
, wxO_BINARY
);
894 #endif // wxOpenOSFHandle
897 // Helper to open the file
899 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
901 #ifdef WX_HAVE_DELETE_ON_CLOSE
903 return wxOpenWithDeleteOnClose(path
);
906 *deleteOnClose
= false;
908 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
913 // Helper to open the file and attach it to the wxFFile
915 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
918 *deleteOnClose
= false;
919 return file
->Open(path
, wxT("w+b"));
921 int fd
= wxTempOpen(path
, deleteOnClose
);
924 file
->Attach(wx_fdopen(fd
, "w+b"), path
);
925 return file
->IsOpened();
928 #endif // wxUSE_FFILE
932 #define WXFILEARGS(x, y) y
934 #define WXFILEARGS(x, y) x
936 #define WXFILEARGS(x, y) x, y
940 // Implementation of wxFileName::CreateTempFileName().
942 static wxString
wxCreateTempImpl(
943 const wxString
& prefix
,
944 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
945 bool *deleteOnClose
= NULL
)
947 #if wxUSE_FILE && wxUSE_FFILE
948 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
950 wxString path
, dir
, name
;
951 bool wantDeleteOnClose
= false;
955 // set the result to false initially
956 wantDeleteOnClose
= *deleteOnClose
;
957 *deleteOnClose
= false;
961 // easier if it alwasys points to something
962 deleteOnClose
= &wantDeleteOnClose
;
965 // use the directory specified by the prefix
966 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
970 dir
= wxFileName::GetTempDir();
973 #if defined(__WXWINCE__)
974 path
= dir
+ wxT("\\") + name
;
976 while (wxFileName::FileExists(path
))
978 path
= dir
+ wxT("\\") + name
;
983 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
984 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
985 wxStringBuffer(path
, MAX_PATH
+ 1)))
987 wxLogLastError(wxT("GetTempFileName"));
995 if ( !wxEndsWithPathSeparator(dir
) &&
996 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
998 path
+= wxFILE_SEP_PATH
;
1003 #if defined(HAVE_MKSTEMP)
1004 // scratch space for mkstemp()
1005 path
+= wxT("XXXXXX");
1007 // we need to copy the path to the buffer in which mkstemp() can modify it
1008 wxCharBuffer
buf(path
.fn_str());
1010 // cast is safe because the string length doesn't change
1011 int fdTemp
= mkstemp( (char*)(const char*) buf
);
1014 // this might be not necessary as mkstemp() on most systems should have
1015 // already done it but it doesn't hurt neither...
1018 else // mkstemp() succeeded
1020 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1023 // avoid leaking the fd
1026 fileTemp
->Attach(fdTemp
);
1035 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"), path
);
1037 ffileTemp
->Open(path
, wxT("r+b"));
1048 #else // !HAVE_MKSTEMP
1052 path
+= wxT("XXXXXX");
1054 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
1055 if ( !mktemp( (char*)(const char*) buf
) )
1061 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1063 #else // !HAVE_MKTEMP (includes __DOS__)
1064 // generate the unique file name ourselves
1065 #if !defined(__DOS__)
1066 path
<< (unsigned int)getpid();
1071 static const size_t numTries
= 1000;
1072 for ( size_t n
= 0; n
< numTries
; n
++ )
1074 // 3 hex digits is enough for numTries == 1000 < 4096
1075 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
1076 if ( !wxFileName::FileExists(pathTry
) )
1085 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1087 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1089 #endif // Windows/!Windows
1093 wxLogSysError(_("Failed to create a temporary file name"));
1099 // open the file - of course, there is a race condition here, this is
1100 // why we always prefer using mkstemp()...
1102 if ( fileTemp
&& !fileTemp
->IsOpened() )
1104 *deleteOnClose
= wantDeleteOnClose
;
1105 int fd
= wxTempOpen(path
, deleteOnClose
);
1107 fileTemp
->Attach(fd
);
1114 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1116 *deleteOnClose
= wantDeleteOnClose
;
1117 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1123 // FIXME: If !ok here should we loop and try again with another
1124 // file name? That is the standard recourse if open(O_EXCL)
1125 // fails, though of course it should be protected against
1126 // possible infinite looping too.
1128 wxLogError(_("Failed to open temporary file."));
1138 static bool wxCreateTempImpl(
1139 const wxString
& prefix
,
1140 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1143 bool deleteOnClose
= true;
1145 *name
= wxCreateTempImpl(prefix
,
1146 WXFILEARGS(fileTemp
, ffileTemp
),
1149 bool ok
= !name
->empty();
1154 else if (ok
&& wxRemoveFile(*name
))
1162 static void wxAssignTempImpl(
1164 const wxString
& prefix
,
1165 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1168 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1170 if ( tempname
.empty() )
1172 // error, failed to get temp file name
1177 fn
->Assign(tempname
);
1182 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1184 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1188 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1190 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1193 #endif // wxUSE_FILE || wxUSE_FFILE
1198 wxString
wxCreateTempFileName(const wxString
& prefix
,
1200 bool *deleteOnClose
)
1202 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1205 bool wxCreateTempFile(const wxString
& prefix
,
1209 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1212 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1214 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1219 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1221 return wxCreateTempFileName(prefix
, fileTemp
);
1224 #endif // wxUSE_FILE
1229 wxString
wxCreateTempFileName(const wxString
& prefix
,
1231 bool *deleteOnClose
)
1233 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1236 bool wxCreateTempFile(const wxString
& prefix
,
1240 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1244 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1246 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1251 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1253 return wxCreateTempFileName(prefix
, fileTemp
);
1256 #endif // wxUSE_FFILE
1259 // ----------------------------------------------------------------------------
1260 // directory operations
1261 // ----------------------------------------------------------------------------
1263 // helper of GetTempDir(): check if the given directory exists and return it if
1264 // it does or an empty string otherwise
1268 wxString
CheckIfDirExists(const wxString
& dir
)
1270 return wxFileName::DirExists(dir
) ? dir
: wxString();
1273 } // anonymous namespace
1275 wxString
wxFileName::GetTempDir()
1277 // first try getting it from environment: this allows overriding the values
1278 // used by default if the user wants to create temporary files in another
1280 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1283 dir
= CheckIfDirExists(wxGetenv("TMP"));
1285 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1288 // if no environment variables are set, use the system default
1291 #if defined(__WXWINCE__)
1292 dir
= CheckIfDirExists(wxT("\\temp"));
1293 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1294 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1296 wxLogLastError(wxT("GetTempPath"));
1298 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1299 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1300 #endif // systems with native way
1302 else // we got directory from an environment variable
1304 // remove any trailing path separators, we don't want to ever return
1305 // them from this function for consistency
1306 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1307 if ( lastNonSep
== wxString::npos
)
1309 // the string consists entirely of separators, leave only one
1310 dir
= GetPathSeparator();
1314 dir
.erase(lastNonSep
+ 1);
1318 // fall back to hard coded value
1321 #ifdef __UNIX_LIKE__
1322 dir
= CheckIfDirExists("/tmp");
1324 #endif // __UNIX_LIKE__
1331 bool wxFileName::Mkdir( int perm
, int flags
) const
1333 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1336 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1338 if ( flags
& wxPATH_MKDIR_FULL
)
1340 // split the path in components
1341 wxFileName filename
;
1342 filename
.AssignDir(dir
);
1345 if ( filename
.HasVolume())
1347 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1350 wxArrayString dirs
= filename
.GetDirs();
1351 size_t count
= dirs
.GetCount();
1352 for ( size_t i
= 0; i
< count
; i
++ )
1354 if ( i
> 0 || filename
.IsAbsolute() )
1355 currPath
+= wxFILE_SEP_PATH
;
1356 currPath
+= dirs
[i
];
1358 if (!DirExists(currPath
))
1360 if (!wxMkdir(currPath
, perm
))
1362 // no need to try creating further directories
1372 return ::wxMkdir( dir
, perm
);
1375 bool wxFileName::Rmdir(int flags
) const
1377 return wxFileName::Rmdir( GetPath(), flags
);
1380 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1383 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1385 // SHFileOperation needs double null termination string
1386 // but without separator at the end of the path
1388 if ( path
.Last() == wxFILE_SEP_PATH
)
1392 SHFILEOPSTRUCT fileop
;
1393 wxZeroMemory(fileop
);
1394 fileop
.wFunc
= FO_DELETE
;
1395 fileop
.pFrom
= path
.t_str();
1396 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1398 // FOF_NOERRORUI is not defined in WinCE
1399 fileop
.fFlags
|= FOF_NOERRORUI
;
1402 int ret
= SHFileOperation(&fileop
);
1405 // SHFileOperation may return non-Win32 error codes, so the error
1406 // message can be incorrect
1407 wxLogApiError(wxT("SHFileOperation"), ret
);
1413 else if ( flags
& wxPATH_RMDIR_FULL
)
1414 #else // !__WINDOWS__
1415 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1416 #endif // !__WINDOWS__
1419 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1421 // When deleting the tree recursively, we are supposed to delete
1422 // this directory itself even when it is a symlink -- but without
1423 // following it. Do it here as wxRmdir() would simply follow if
1424 // called for a symlink.
1425 if ( wxFileName::Exists(dir
, wxFILE_EXISTS_SYMLINK
|
1426 wxFILE_EXISTS_NO_FOLLOW
) )
1428 return wxRemoveFile(dir
);
1431 #endif // !__WINDOWS__
1434 if ( path
.Last() != wxFILE_SEP_PATH
)
1435 path
+= wxFILE_SEP_PATH
;
1439 if ( !d
.IsOpened() )
1444 // First delete all subdirectories: notice that we don't follow
1445 // symbolic links, potentially leading outside this directory, to avoid
1446 // unpleasant surprises.
1447 bool cont
= d
.GetFirst(&filename
, wxString(),
1448 wxDIR_DIRS
| wxDIR_HIDDEN
| wxDIR_NO_FOLLOW
);
1451 wxFileName::Rmdir(path
+ filename
, flags
);
1452 cont
= d
.GetNext(&filename
);
1456 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1458 // Delete all files too and, for the same reasons as above, don't
1459 // follow symlinks which could refer to the files outside of this
1460 // directory and just delete the symlinks themselves.
1461 cont
= d
.GetFirst(&filename
, wxString(),
1462 wxDIR_FILES
| wxDIR_HIDDEN
| wxDIR_NO_FOLLOW
);
1465 ::wxRemoveFile(path
+ filename
);
1466 cont
= d
.GetNext(&filename
);
1469 #endif // !__WINDOWS__
1472 return ::wxRmdir(dir
);
1475 // ----------------------------------------------------------------------------
1476 // path normalization
1477 // ----------------------------------------------------------------------------
1479 bool wxFileName::Normalize(int flags
,
1480 const wxString
& cwd
,
1481 wxPathFormat format
)
1483 // deal with env vars renaming first as this may seriously change the path
1484 if ( flags
& wxPATH_NORM_ENV_VARS
)
1486 wxString pathOrig
= GetFullPath(format
);
1487 wxString path
= wxExpandEnvVars(pathOrig
);
1488 if ( path
!= pathOrig
)
1494 // the existing path components
1495 wxArrayString dirs
= GetDirs();
1497 // the path to prepend in front to make the path absolute
1500 format
= GetFormat(format
);
1502 // set up the directory to use for making the path absolute later
1503 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1507 curDir
.AssignCwd(GetVolume());
1509 else // cwd provided
1511 curDir
.AssignDir(cwd
);
1515 // handle ~ stuff under Unix only
1516 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1518 if ( !dirs
.IsEmpty() )
1520 wxString dir
= dirs
[0u];
1521 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1523 // to make the path absolute use the home directory
1524 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1530 // transform relative path into abs one
1531 if ( curDir
.IsOk() )
1533 // this path may be relative because it doesn't have the volume name
1534 // and still have m_relative=true; in this case we shouldn't modify
1535 // our directory components but just set the current volume
1536 if ( !HasVolume() && curDir
.HasVolume() )
1538 SetVolume(curDir
.GetVolume());
1542 // yes, it was the case - we don't need curDir then
1547 // finally, prepend curDir to the dirs array
1548 wxArrayString dirsNew
= curDir
.GetDirs();
1549 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1551 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1552 // return for some reason an absolute path, then curDir maybe not be absolute!
1553 if ( !curDir
.m_relative
)
1555 // we have prepended an absolute path and thus we are now an absolute
1559 // else if (flags & wxPATH_NORM_ABSOLUTE):
1560 // should we warn the user that we didn't manage to make the path absolute?
1563 // now deal with ".", ".." and the rest
1565 size_t count
= dirs
.GetCount();
1566 for ( size_t n
= 0; n
< count
; n
++ )
1568 wxString dir
= dirs
[n
];
1570 if ( flags
& wxPATH_NORM_DOTS
)
1572 if ( dir
== wxT(".") )
1578 if ( dir
== wxT("..") )
1580 if ( m_dirs
.empty() )
1582 // We have more ".." than directory components so far.
1583 // Don't treat this as an error as the path could have been
1584 // entered by user so try to handle it reasonably: if the
1585 // path is absolute, just ignore the extra ".." because
1586 // "/.." is the same as "/". Otherwise, i.e. for relative
1587 // paths, keep ".." unchanged because removing it would
1588 // modify the file a relative path refers to.
1593 else // Normal case, go one step up.
1604 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1605 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1608 if (GetShortcutTarget(GetFullPath(format
), filename
))
1616 #if defined(__WIN32__)
1617 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1619 Assign(GetLongPath());
1623 // Change case (this should be kept at the end of the function, to ensure
1624 // that the path doesn't change any more after we normalize its case)
1625 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1627 m_volume
.MakeLower();
1631 // directory entries must be made lower case as well
1632 count
= m_dirs
.GetCount();
1633 for ( size_t i
= 0; i
< count
; i
++ )
1635 m_dirs
[i
].MakeLower();
1643 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1644 const wxString
& replacementFmtString
,
1645 wxPathFormat format
)
1647 // look into stringForm for the contents of the given environment variable
1649 if (envname
.empty() ||
1650 !wxGetEnv(envname
, &val
))
1655 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1656 // do not touch the file name and the extension
1658 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1659 stringForm
.Replace(val
, replacement
);
1661 // Now assign ourselves the modified path:
1662 Assign(stringForm
, GetFullName(), format
);
1668 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1670 wxString homedir
= wxGetHomeDir();
1671 if (homedir
.empty())
1674 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1675 // do not touch the file name and the extension
1677 stringForm
.Replace(homedir
, "~");
1679 // Now assign ourselves the modified path:
1680 Assign(stringForm
, GetFullName(), format
);
1685 // ----------------------------------------------------------------------------
1686 // get the shortcut target
1687 // ----------------------------------------------------------------------------
1689 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1690 // The .lnk file is a plain text file so it should be easy to
1691 // make it work. Hint from Google Groups:
1692 // "If you open up a lnk file, you'll see a
1693 // number, followed by a pound sign (#), followed by more text. The
1694 // number is the number of characters that follows the pound sign. The
1695 // characters after the pound sign are the command line (which _can_
1696 // include arguments) to be executed. Any path (e.g. \windows\program
1697 // files\myapp.exe) that includes spaces needs to be enclosed in
1698 // quotation marks."
1700 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1701 // The following lines are necessary under WinCE
1702 // #include "wx/msw/private.h"
1703 // #include <ole2.h>
1705 #if defined(__WXWINCE__)
1706 #include <shlguid.h>
1709 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1710 wxString
& targetFilename
,
1711 wxString
* arguments
) const
1713 wxString path
, file
, ext
;
1714 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1718 bool success
= false;
1720 // Assume it's not a shortcut if it doesn't end with lnk
1721 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1724 // create a ShellLink object
1725 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1726 IID_IShellLink
, (LPVOID
*) &psl
);
1728 if (SUCCEEDED(hres
))
1731 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1732 if (SUCCEEDED(hres
))
1734 WCHAR wsz
[MAX_PATH
];
1736 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1739 hres
= ppf
->Load(wsz
, 0);
1742 if (SUCCEEDED(hres
))
1745 // Wrong prototype in early versions
1746 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1747 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1749 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1751 targetFilename
= wxString(buf
);
1752 success
= (shortcutPath
!= targetFilename
);
1754 psl
->GetArguments(buf
, 2048);
1756 if (!args
.empty() && arguments
)
1768 #endif // __WIN32__ && !__WXWINCE__
1771 // ----------------------------------------------------------------------------
1772 // absolute/relative paths
1773 // ----------------------------------------------------------------------------
1775 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1777 // unix paths beginning with ~ are reported as being absolute
1778 if ( format
== wxPATH_UNIX
)
1780 if ( !m_dirs
.IsEmpty() )
1782 wxString dir
= m_dirs
[0u];
1784 if (!dir
.empty() && dir
[0u] == wxT('~'))
1789 // if our path doesn't start with a path separator, it's not an absolute
1794 if ( !GetVolumeSeparator(format
).empty() )
1796 // this format has volumes and an absolute path must have one, it's not
1797 // enough to have the full path to be an absolute file under Windows
1798 if ( GetVolume().empty() )
1805 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1807 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1809 // get cwd only once - small time saving
1810 wxString cwd
= wxGetCwd();
1811 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1812 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1814 bool withCase
= IsCaseSensitive(format
);
1816 // we can't do anything if the files live on different volumes
1817 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1823 // same drive, so we don't need our volume
1826 // remove common directories starting at the top
1827 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1828 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1831 fnBase
.m_dirs
.RemoveAt(0);
1834 // add as many ".." as needed
1835 size_t count
= fnBase
.m_dirs
.GetCount();
1836 for ( size_t i
= 0; i
< count
; i
++ )
1838 m_dirs
.Insert(wxT(".."), 0u);
1841 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1843 // a directory made relative with respect to itself is '.' under Unix
1844 // and DOS, by definition (but we don't have to insert "./" for the
1846 if ( m_dirs
.IsEmpty() && IsDir() )
1848 m_dirs
.Add(wxT('.'));
1858 // ----------------------------------------------------------------------------
1859 // filename kind tests
1860 // ----------------------------------------------------------------------------
1862 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1864 wxFileName fn1
= *this,
1867 // get cwd only once - small time saving
1868 wxString cwd
= wxGetCwd();
1869 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1870 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1872 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1875 #if defined(__UNIX__)
1876 wxStructStat st1
, st2
;
1877 if ( StatAny(st1
, fn1
) && StatAny(st2
, fn2
) )
1879 if ( st1
.st_ino
== st2
.st_ino
&& st1
.st_dev
== st2
.st_dev
)
1882 //else: It's not an error if one or both files don't exist.
1883 #endif // defined __UNIX__
1889 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1891 // only Unix filenames are truly case-sensitive
1892 return GetFormat(format
) == wxPATH_UNIX
;
1896 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1898 // Inits to forbidden characters that are common to (almost) all platforms.
1899 wxString strForbiddenChars
= wxT("*?");
1901 // If asserts, wxPathFormat has been changed. In case of a new path format
1902 // addition, the following code might have to be updated.
1903 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1904 switch ( GetFormat(format
) )
1907 wxFAIL_MSG( wxT("Unknown path format") );
1908 // !! Fall through !!
1914 // On a Mac even names with * and ? are allowed (Tested with OS
1915 // 9.2.1 and OS X 10.2.5)
1916 strForbiddenChars
= wxEmptyString
;
1920 strForbiddenChars
+= wxT("\\/:\"<>|");
1927 return strForbiddenChars
;
1931 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1934 return wxEmptyString
;
1938 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1939 (GetFormat(format
) == wxPATH_VMS
) )
1941 sepVol
= wxFILE_SEP_DSK
;
1950 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1953 switch ( GetFormat(format
) )
1956 // accept both as native APIs do but put the native one first as
1957 // this is the one we use in GetFullPath()
1958 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1962 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1966 seps
= wxFILE_SEP_PATH_UNIX
;
1970 seps
= wxFILE_SEP_PATH_MAC
;
1974 seps
= wxFILE_SEP_PATH_VMS
;
1982 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1984 format
= GetFormat(format
);
1986 // under VMS the end of the path is ']', not the path separator used to
1987 // separate the components
1988 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1992 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1994 // wxString::Find() doesn't work as expected with NUL - it will always find
1995 // it, so test for it separately
1996 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
2001 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
2003 // return true if the format used is the DOS/Windows one and the string begins
2004 // with a Windows unique volume name ("\\?\Volume{guid}\")
2005 return format
== wxPATH_DOS
&&
2006 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
2007 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
2008 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
2011 // ----------------------------------------------------------------------------
2012 // path components manipulation
2013 // ----------------------------------------------------------------------------
2015 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
2019 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
2024 const size_t len
= dir
.length();
2025 for ( size_t n
= 0; n
< len
; n
++ )
2027 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
2029 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
2038 void wxFileName::AppendDir( const wxString
& dir
)
2040 if ( IsValidDirComponent(dir
) )
2044 void wxFileName::PrependDir( const wxString
& dir
)
2049 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
2051 if ( IsValidDirComponent(dir
) )
2052 m_dirs
.Insert(dir
, before
);
2055 void wxFileName::RemoveDir(size_t pos
)
2057 m_dirs
.RemoveAt(pos
);
2060 // ----------------------------------------------------------------------------
2062 // ----------------------------------------------------------------------------
2064 void wxFileName::SetFullName(const wxString
& fullname
)
2066 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
2067 &m_name
, &m_ext
, &m_hasExt
);
2070 wxString
wxFileName::GetFullName() const
2072 wxString fullname
= m_name
;
2075 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
2081 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
2083 format
= GetFormat( format
);
2087 // return the volume with the path as well if requested
2088 if ( flags
& wxPATH_GET_VOLUME
)
2090 fullpath
+= wxGetVolumeString(GetVolume(), format
);
2093 // the leading character
2098 fullpath
+= wxFILE_SEP_PATH_MAC
;
2103 fullpath
+= wxFILE_SEP_PATH_DOS
;
2107 wxFAIL_MSG( wxT("Unknown path format") );
2113 fullpath
+= wxFILE_SEP_PATH_UNIX
;
2118 // no leading character here but use this place to unset
2119 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2120 // as, if I understand correctly, there should never be a dot
2121 // before the closing bracket
2122 flags
&= ~wxPATH_GET_SEPARATOR
;
2125 if ( m_dirs
.empty() )
2127 // there is nothing more
2131 // then concatenate all the path components using the path separator
2132 if ( format
== wxPATH_VMS
)
2134 fullpath
+= wxT('[');
2137 const size_t dirCount
= m_dirs
.GetCount();
2138 for ( size_t i
= 0; i
< dirCount
; i
++ )
2143 if ( m_dirs
[i
] == wxT(".") )
2145 // skip appending ':', this shouldn't be done in this
2146 // case as "::" is interpreted as ".." under Unix
2150 // convert back from ".." to nothing
2151 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2152 fullpath
+= m_dirs
[i
];
2156 wxFAIL_MSG( wxT("Unexpected path format") );
2157 // still fall through
2161 fullpath
+= m_dirs
[i
];
2165 // TODO: What to do with ".." under VMS
2167 // convert back from ".." to nothing
2168 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2169 fullpath
+= m_dirs
[i
];
2173 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2174 fullpath
+= GetPathSeparator(format
);
2177 if ( format
== wxPATH_VMS
)
2179 fullpath
+= wxT(']');
2185 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2187 // we already have a function to get the path
2188 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2191 // now just add the file name and extension to it
2192 fullpath
+= GetFullName();
2197 // Return the short form of the path (returns identity on non-Windows platforms)
2198 wxString
wxFileName::GetShortPath() const
2200 wxString
path(GetFullPath());
2202 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2203 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2207 if ( ::GetShortPathName
2210 wxStringBuffer(pathOut
, sz
),
2222 // Return the long form of the path (returns identity on non-Windows platforms)
2223 wxString
wxFileName::GetLongPath() const
2226 path
= GetFullPath();
2228 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2230 #if wxUSE_DYNLIB_CLASS
2231 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2233 // this is MT-safe as in the worst case we're going to resolve the function
2234 // twice -- but as the result is the same in both threads, it's ok
2235 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2236 if ( !s_pfnGetLongPathName
)
2238 static bool s_triedToLoad
= false;
2240 if ( !s_triedToLoad
)
2242 s_triedToLoad
= true;
2244 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2246 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2251 #endif // Unicode/ANSI
2253 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2255 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2256 dllKernel
.GetSymbol(GetLongPathName
);
2259 // note that kernel32.dll can be unloaded, it stays in memory
2260 // anyhow as all Win32 programs link to it and so it's safe to call
2261 // GetLongPathName() even after unloading it
2265 if ( s_pfnGetLongPathName
)
2267 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2270 if ( (*s_pfnGetLongPathName
)
2273 wxStringBuffer(pathOut
, dwSize
),
2281 #endif // wxUSE_DYNLIB_CLASS
2283 // The OS didn't support GetLongPathName, or some other error.
2284 // We need to call FindFirstFile on each component in turn.
2286 WIN32_FIND_DATA findFileData
;
2290 pathOut
= GetVolume() +
2291 GetVolumeSeparator(wxPATH_DOS
) +
2292 GetPathSeparator(wxPATH_DOS
);
2294 pathOut
= wxEmptyString
;
2296 wxArrayString dirs
= GetDirs();
2297 dirs
.Add(GetFullName());
2301 size_t count
= dirs
.GetCount();
2302 for ( size_t i
= 0; i
< count
; i
++ )
2304 const wxString
& dir
= dirs
[i
];
2306 // We're using pathOut to collect the long-name path, but using a
2307 // temporary for appending the last path component which may be
2309 tmpPath
= pathOut
+ dir
;
2311 // We must not process "." or ".." here as they would be (unexpectedly)
2312 // replaced by the corresponding directory names so just leave them
2315 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2316 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2317 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2319 tmpPath
+= wxFILE_SEP_PATH
;
2324 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2325 if (hFind
== INVALID_HANDLE_VALUE
)
2327 // Error: most likely reason is that path doesn't exist, so
2328 // append any unprocessed parts and return
2329 for ( i
+= 1; i
< count
; i
++ )
2330 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2335 pathOut
+= findFileData
.cFileName
;
2336 if ( (i
< (count
-1)) )
2337 pathOut
+= wxFILE_SEP_PATH
;
2343 #endif // Win32/!Win32
2348 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2350 if (format
== wxPATH_NATIVE
)
2352 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2353 format
= wxPATH_DOS
;
2354 #elif defined(__VMS)
2355 format
= wxPATH_VMS
;
2357 format
= wxPATH_UNIX
;
2363 #ifdef wxHAS_FILESYSTEM_VOLUMES
2366 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2368 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2370 wxString
vol(drive
);
2371 vol
+= wxFILE_SEP_DSK
;
2372 if ( flags
& wxPATH_GET_SEPARATOR
)
2373 vol
+= wxFILE_SEP_PATH
;
2378 #endif // wxHAS_FILESYSTEM_VOLUMES
2380 // ----------------------------------------------------------------------------
2381 // path splitting function
2382 // ----------------------------------------------------------------------------
2386 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2387 wxString
*pstrVolume
,
2389 wxPathFormat format
)
2391 format
= GetFormat(format
);
2393 wxString fullpath
= fullpathWithVolume
;
2395 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2397 // special Windows unique volume names hack: transform
2398 // \\?\Volume{guid}\path into Volume{guid}:path
2399 // note: this check must be done before the check for UNC path
2401 // we know the last backslash from the unique volume name is located
2402 // there from IsMSWUniqueVolumeNamePath
2403 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2405 // paths starting with a unique volume name should always be absolute
2406 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2408 // remove the leading "\\?\" part
2409 fullpath
.erase(0, 4);
2411 else if ( IsUNCPath(fullpath
, format
) )
2413 // special Windows UNC paths hack: transform \\share\path into share:path
2415 fullpath
.erase(0, 2);
2417 size_t posFirstSlash
=
2418 fullpath
.find_first_of(GetPathTerminators(format
));
2419 if ( posFirstSlash
!= wxString::npos
)
2421 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2423 // UNC paths are always absolute, right? (FIXME)
2424 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2428 // We separate the volume here
2429 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2431 wxString sepVol
= GetVolumeSeparator(format
);
2433 // we have to exclude the case of a colon in the very beginning of the
2434 // string as it can't be a volume separator (nor can this be a valid
2435 // DOS file name at all but we'll leave dealing with this to our caller)
2436 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2437 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2441 *pstrVolume
= fullpath
.Left(posFirstColon
);
2444 // remove the volume name and the separator from the full path
2445 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2450 *pstrPath
= fullpath
;
2454 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2455 wxString
*pstrVolume
,
2460 wxPathFormat format
)
2462 format
= GetFormat(format
);
2465 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2467 // find the positions of the last dot and last path separator in the path
2468 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2469 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2471 // check whether this dot occurs at the very beginning of a path component
2472 if ( (posLastDot
!= wxString::npos
) &&
2474 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2475 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2477 // dot may be (and commonly -- at least under Unix -- is) the first
2478 // character of the filename, don't treat the entire filename as
2479 // extension in this case
2480 posLastDot
= wxString::npos
;
2483 // if we do have a dot and a slash, check that the dot is in the name part
2484 if ( (posLastDot
!= wxString::npos
) &&
2485 (posLastSlash
!= wxString::npos
) &&
2486 (posLastDot
< posLastSlash
) )
2488 // the dot is part of the path, not the start of the extension
2489 posLastDot
= wxString::npos
;
2492 // now fill in the variables provided by user
2495 if ( posLastSlash
== wxString::npos
)
2502 // take everything up to the path separator but take care to make
2503 // the path equal to something like '/', not empty, for the files
2504 // immediately under root directory
2505 size_t len
= posLastSlash
;
2507 // this rule does not apply to mac since we do not start with colons (sep)
2508 // except for relative paths
2509 if ( !len
&& format
!= wxPATH_MAC
)
2512 *pstrPath
= fullpath
.Left(len
);
2514 // special VMS hack: remove the initial bracket
2515 if ( format
== wxPATH_VMS
)
2517 if ( (*pstrPath
)[0u] == wxT('[') )
2518 pstrPath
->erase(0, 1);
2525 // take all characters starting from the one after the last slash and
2526 // up to, but excluding, the last dot
2527 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2529 if ( posLastDot
== wxString::npos
)
2531 // take all until the end
2532 count
= wxString::npos
;
2534 else if ( posLastSlash
== wxString::npos
)
2538 else // have both dot and slash
2540 count
= posLastDot
- posLastSlash
- 1;
2543 *pstrName
= fullpath
.Mid(nStart
, count
);
2546 // finally deal with the extension here: we have an added complication that
2547 // extension may be empty (but present) as in "foo." where trailing dot
2548 // indicates the empty extension at the end -- and hence we must remember
2549 // that we have it independently of pstrExt
2550 if ( posLastDot
== wxString::npos
)
2560 // take everything after the dot
2562 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2569 void wxFileName::SplitPath(const wxString
& fullpath
,
2573 wxPathFormat format
)
2576 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2580 path
->Prepend(wxGetVolumeString(volume
, format
));
2585 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2587 wxFileName
fn(fullpath
);
2589 return fn
.GetFullPath();
2592 // ----------------------------------------------------------------------------
2594 // ----------------------------------------------------------------------------
2598 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2599 const wxDateTime
*dtMod
,
2600 const wxDateTime
*dtCreate
) const
2602 #if defined(__WIN32__)
2603 FILETIME ftAccess
, ftCreate
, ftWrite
;
2606 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2608 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2610 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2616 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2618 wxLogError(_("Setting directory access times is not supported "
2619 "under this OS version"));
2624 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2628 path
= GetFullPath();
2632 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2635 if ( ::SetFileTime(fh
,
2636 dtCreate
? &ftCreate
: NULL
,
2637 dtAccess
? &ftAccess
: NULL
,
2638 dtMod
? &ftWrite
: NULL
) )
2643 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2644 wxUnusedVar(dtCreate
);
2646 if ( !dtAccess
&& !dtMod
)
2648 // can't modify the creation time anyhow, don't try
2652 // if dtAccess or dtMod is not specified, use the other one (which must be
2653 // non NULL because of the test above) for both times
2655 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2656 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2657 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2661 #else // other platform
2662 wxUnusedVar(dtAccess
);
2664 wxUnusedVar(dtCreate
);
2667 wxLogSysError(_("Failed to modify file times for '%s'"),
2668 GetFullPath().c_str());
2673 bool wxFileName::Touch() const
2675 #if defined(__UNIX_LIKE__)
2676 // under Unix touching file is simple: just pass NULL to utime()
2677 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2682 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2685 #else // other platform
2686 wxDateTime dtNow
= wxDateTime::Now();
2688 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2692 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2694 wxDateTime
*dtCreate
) const
2696 #if defined(__WIN32__)
2697 // we must use different methods for the files and directories under
2698 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2699 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2702 FILETIME ftAccess
, ftCreate
, ftWrite
;
2705 // implemented in msw/dir.cpp
2706 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2707 FILETIME
*, FILETIME
*, FILETIME
*);
2709 // we should pass the path without the trailing separator to
2710 // wxGetDirectoryTimes()
2711 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2712 &ftAccess
, &ftCreate
, &ftWrite
);
2716 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2719 ok
= ::GetFileTime(fh
,
2720 dtCreate
? &ftCreate
: NULL
,
2721 dtAccess
? &ftAccess
: NULL
,
2722 dtMod
? &ftWrite
: NULL
) != 0;
2733 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2735 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2737 ConvertFileTimeToWx(dtMod
, ftWrite
);
2741 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2742 // no need to test for IsDir() here
2744 if ( StatAny(stBuf
, *this) )
2746 // Android defines st_*time fields as unsigned long, but time_t as long,
2747 // hence the static_casts.
2749 dtAccess
->Set(static_cast<time_t>(stBuf
.st_atime
));
2751 dtMod
->Set(static_cast<time_t>(stBuf
.st_mtime
));
2753 dtCreate
->Set(static_cast<time_t>(stBuf
.st_ctime
));
2757 #else // other platform
2758 wxUnusedVar(dtAccess
);
2760 wxUnusedVar(dtCreate
);
2763 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2764 GetFullPath().c_str());
2769 #endif // wxUSE_DATETIME
2772 // ----------------------------------------------------------------------------
2773 // file size functions
2774 // ----------------------------------------------------------------------------
2779 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2781 if (!wxFileExists(filename
))
2782 return wxInvalidSize
;
2784 #if defined(__WIN32__)
2785 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2787 return wxInvalidSize
;
2789 DWORD lpFileSizeHigh
;
2790 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2791 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2792 return wxInvalidSize
;
2794 return wxULongLong(lpFileSizeHigh
, ret
);
2795 #else // ! __WIN32__
2797 if (wxStat( filename
, &st
) != 0)
2798 return wxInvalidSize
;
2799 return wxULongLong(st
.st_size
);
2804 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2805 const wxString
&nullsize
,
2807 wxSizeConvention conv
)
2809 // deal with trivial case first
2810 if ( bs
== 0 || bs
== wxInvalidSize
)
2813 // depending on the convention used the multiplier may be either 1000 or
2814 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2815 double multiplier
= 1024.;
2820 case wxSIZE_CONV_TRADITIONAL
:
2821 // nothing to do, this corresponds to the default values of both
2822 // the multiplier and infix string
2825 case wxSIZE_CONV_IEC
:
2829 case wxSIZE_CONV_SI
:
2834 const double kiloByteSize
= multiplier
;
2835 const double megaByteSize
= multiplier
* kiloByteSize
;
2836 const double gigaByteSize
= multiplier
* megaByteSize
;
2837 const double teraByteSize
= multiplier
* gigaByteSize
;
2839 const double bytesize
= bs
.ToDouble();
2842 if ( bytesize
< kiloByteSize
)
2843 result
.Printf("%s B", bs
.ToString());
2844 else if ( bytesize
< megaByteSize
)
2845 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2846 else if (bytesize
< gigaByteSize
)
2847 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2848 else if (bytesize
< teraByteSize
)
2849 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2851 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2856 wxULongLong
wxFileName::GetSize() const
2858 return GetSize(GetFullPath());
2861 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2863 wxSizeConvention conv
) const
2865 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2868 #endif // wxUSE_LONGLONG
2870 // ----------------------------------------------------------------------------
2871 // Mac-specific functions
2872 // ----------------------------------------------------------------------------
2874 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2879 class MacDefaultExtensionRecord
2882 MacDefaultExtensionRecord()
2888 // default copy ctor, assignment operator and dtor are ok
2890 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2894 m_creator
= creator
;
2902 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2904 bool gMacDefaultExtensionsInited
= false;
2906 #include "wx/arrimpl.cpp"
2908 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2910 MacDefaultExtensionArray gMacDefaultExtensions
;
2912 // load the default extensions
2913 const MacDefaultExtensionRecord gDefaults
[] =
2915 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2916 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2917 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2920 void MacEnsureDefaultExtensionsLoaded()
2922 if ( !gMacDefaultExtensionsInited
)
2924 // we could load the pc exchange prefs here too
2925 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2927 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2929 gMacDefaultExtensionsInited
= true;
2933 } // anonymous namespace
2935 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2938 FSCatalogInfo catInfo
;
2941 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2943 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2945 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2946 finfo
->fileType
= type
;
2947 finfo
->fileCreator
= creator
;
2948 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2955 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2958 FSCatalogInfo catInfo
;
2961 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2963 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2965 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2966 *type
= finfo
->fileType
;
2967 *creator
= finfo
->fileCreator
;
2974 bool wxFileName::MacSetDefaultTypeAndCreator()
2976 wxUint32 type
, creator
;
2977 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2980 return MacSetTypeAndCreator( type
, creator
) ;
2985 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2987 MacEnsureDefaultExtensionsLoaded() ;
2988 wxString extl
= ext
.Lower() ;
2989 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2991 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2993 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2994 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
3001 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
3003 MacEnsureDefaultExtensionsLoaded();
3004 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
3005 gMacDefaultExtensions
.Add( rec
);
3008 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON