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"
103 #include <shlobj.h> // for CLSID_ShellLink
104 #include "wx/msw/missing.h"
107 #if defined(__WXMAC__)
108 #include "wx/osx/private.h" // includes mac headers
111 // utime() is POSIX so should normally be available on all Unices
113 #include <sys/types.h>
115 #include <sys/stat.h>
125 #include <sys/utime.h>
126 #include <sys/stat.h>
137 #define MAX_PATH _MAX_PATH
141 #define S_ISREG(mode) ((mode) & S_IFREG)
144 #define S_ISDIR(mode) ((mode) & S_IFDIR)
148 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
149 #endif // wxUSE_LONGLONG
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
158 // small helper class which opens and closes the file - we use it just to get
159 // a file handle for the given file name to pass it to some Win32 API function
160 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
171 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
173 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
174 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
175 // be changed when we open it because this class is used for setting
176 // access time (see #10567)
177 m_hFile
= ::CreateFile
179 filename
.t_str(), // name
180 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
181 : FILE_WRITE_ATTRIBUTES
,
182 FILE_SHARE_READ
| // sharing mode
183 FILE_SHARE_WRITE
, // (allow everything)
184 NULL
, // no secutity attr
185 OPEN_EXISTING
, // creation disposition
187 NULL
// no template file
190 if ( m_hFile
== INVALID_HANDLE_VALUE
)
192 if ( mode
== ReadAttr
)
194 wxLogSysError(_("Failed to open '%s' for reading"),
199 wxLogSysError(_("Failed to open '%s' for writing"),
207 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
209 if ( !::CloseHandle(m_hFile
) )
211 wxLogSysError(_("Failed to close file handle"));
216 // return true only if the file could be opened successfully
217 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
220 operator HANDLE() const { return m_hFile
; }
228 // ----------------------------------------------------------------------------
230 // ----------------------------------------------------------------------------
232 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
234 // convert between wxDateTime and FILETIME which is a 64-bit value representing
235 // the number of 100-nanosecond intervals since January 1, 1601.
237 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
239 FILETIME ftcopy
= ft
;
241 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
243 wxLogLastError(wxT("FileTimeToLocalFileTime"));
247 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
249 wxLogLastError(wxT("FileTimeToSystemTime"));
252 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
253 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
256 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
259 st
.wDay
= dt
.GetDay();
260 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
261 st
.wYear
= (WORD
)dt
.GetYear();
262 st
.wHour
= dt
.GetHour();
263 st
.wMinute
= dt
.GetMinute();
264 st
.wSecond
= dt
.GetSecond();
265 st
.wMilliseconds
= dt
.GetMillisecond();
268 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
270 wxLogLastError(wxT("SystemTimeToFileTime"));
273 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
275 wxLogLastError(wxT("LocalFileTimeToFileTime"));
279 #endif // wxUSE_DATETIME && __WIN32__
281 // return a string with the volume par
282 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
286 if ( !volume
.empty() )
288 format
= wxFileName::GetFormat(format
);
290 // Special Windows UNC paths hack, part 2: undo what we did in
291 // SplitPath() and make an UNC path if we have a drive which is not a
292 // single letter (hopefully the network shares can't be one letter only
293 // although I didn't find any authoritative docs on this)
294 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
296 // We also have to check for Windows unique volume names here and
297 // return it with '\\?\' prepended to it
298 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume
+ "\\",
301 path
<< "\\\\?\\" << volume
;
305 // it must be a UNC path
306 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
309 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
311 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
319 // return true if the character is a DOS path separator i.e. either a slash or
321 inline bool IsDOSPathSep(wxUniChar ch
)
323 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
326 // return true if the format used is the DOS/Windows one and the string looks
328 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
330 return format
== wxPATH_DOS
&&
331 path
.length() >= 4 && // "\\a" can't be a UNC path
332 IsDOSPathSep(path
[0u]) &&
333 IsDOSPathSep(path
[1u]) &&
334 !IsDOSPathSep(path
[2u]);
339 // Under Unix-ish systems (basically everything except Windows) we may work
340 // either with the file itself or its target if it's a symbolic link and we
341 // should dereference it, as determined by wxFileName::ShouldFollowLink() and
342 // the absence of the wxFILE_EXISTS_NO_FOLLOW flag. StatAny() can be used to
343 // stat the appropriate file with an extra twist that it also works when there
344 // is no wxFileName object at all, as is the case in static methods.
346 // Private implementation, don't call directly, use one of the overloads below.
347 bool DoStatAny(wxStructStat
& st
, wxString path
, bool dereference
)
349 // We need to remove any trailing slashes from the path because they could
350 // interfere with the symlink following decision: even if we use lstat(),
351 // it would still follow the symlink if we pass it a path with a slash at
352 // the end because the symlink resolution would happen while following the
353 // path and not for the last path element itself.
355 while ( wxEndsWithPathSeparator(path
) )
357 const size_t posLast
= path
.length() - 1;
360 // Don't turn "/" into empty string.
367 int ret
= dereference
? wxStat(path
, &st
) : wxLstat(path
, &st
);
371 // Overloads to use for a case when we don't have wxFileName object and when we
374 bool StatAny(wxStructStat
& st
, const wxString
& path
, int flags
)
376 return DoStatAny(st
, path
, !(flags
& wxFILE_EXISTS_NO_FOLLOW
));
380 bool StatAny(wxStructStat
& st
, const wxFileName
& fn
)
382 return DoStatAny(st
, fn
.GetFullPath(), fn
.ShouldFollowLink());
387 // ----------------------------------------------------------------------------
389 // ----------------------------------------------------------------------------
391 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
392 static const size_t wxMSWUniqueVolumePrefixLength
= 49;
394 } // anonymous namespace
396 // ============================================================================
398 // ============================================================================
400 // ----------------------------------------------------------------------------
401 // wxFileName construction
402 // ----------------------------------------------------------------------------
404 void wxFileName::Assign( const wxFileName
&filepath
)
406 m_volume
= filepath
.GetVolume();
407 m_dirs
= filepath
.GetDirs();
408 m_name
= filepath
.GetName();
409 m_ext
= filepath
.GetExt();
410 m_relative
= filepath
.m_relative
;
411 m_hasExt
= filepath
.m_hasExt
;
412 m_dontFollowLinks
= filepath
.m_dontFollowLinks
;
415 void wxFileName::Assign(const wxString
& volume
,
416 const wxString
& path
,
417 const wxString
& name
,
422 // we should ignore paths which look like UNC shares because we already
423 // have the volume here and the UNC notation (\\server\path) is only valid
424 // for paths which don't start with a volume, so prevent SetPath() from
425 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
427 // note also that this is a rather ugly way to do what we want (passing
428 // some kind of flag telling to ignore UNC paths to SetPath() would be
429 // better) but this is the safest thing to do to avoid breaking backwards
430 // compatibility in 2.8
431 if ( IsUNCPath(path
, format
) )
433 // remove one of the 2 leading backslashes to ensure that it's not
434 // recognized as an UNC path by SetPath()
435 wxString
pathNonUNC(path
, 1, wxString::npos
);
436 SetPath(pathNonUNC
, format
);
438 else // no UNC complications
440 SetPath(path
, format
);
450 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
454 if ( pathOrig
.empty() )
462 format
= GetFormat( format
);
464 // 0) deal with possible volume part first
467 SplitVolume(pathOrig
, &volume
, &path
, format
);
468 if ( !volume
.empty() )
475 // 1) Determine if the path is relative or absolute.
479 // we had only the volume
483 wxChar leadingChar
= path
[0u];
488 m_relative
= leadingChar
== wxT(':');
490 // We then remove a leading ":". The reason is in our
491 // storage form for relative paths:
492 // ":dir:file.txt" actually means "./dir/file.txt" in
493 // DOS notation and should get stored as
494 // (relative) (dir) (file.txt)
495 // "::dir:file.txt" actually means "../dir/file.txt"
496 // stored as (relative) (..) (dir) (file.txt)
497 // This is important only for the Mac as an empty dir
498 // actually means <UP>, whereas under DOS, double
499 // slashes can be ignored: "\\\\" is the same as "\\".
505 // TODO: what is the relative path format here?
510 wxFAIL_MSG( wxT("Unknown path format") );
511 // !! Fall through !!
514 m_relative
= leadingChar
!= wxT('/');
518 m_relative
= !IsPathSeparator(leadingChar
, format
);
523 // 2) Break up the path into its members. If the original path
524 // was just "/" or "\\", m_dirs will be empty. We know from
525 // the m_relative field, if this means "nothing" or "root dir".
527 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
529 while ( tn
.HasMoreTokens() )
531 wxString token
= tn
.GetNextToken();
533 // Remove empty token under DOS and Unix, interpret them
537 if (format
== wxPATH_MAC
)
538 m_dirs
.Add( wxT("..") );
548 void wxFileName::Assign(const wxString
& fullpath
,
551 wxString volume
, path
, name
, ext
;
553 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
555 Assign(volume
, path
, name
, ext
, hasExt
, format
);
558 void wxFileName::Assign(const wxString
& fullpathOrig
,
559 const wxString
& fullname
,
562 // always recognize fullpath as directory, even if it doesn't end with a
564 wxString fullpath
= fullpathOrig
;
565 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
567 fullpath
+= GetPathSeparator(format
);
570 wxString volume
, path
, name
, ext
;
573 // do some consistency checks: the name should be really just the filename
574 // and the path should be really just a path
575 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
577 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
579 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
580 wxT("the file name shouldn't contain the path") );
582 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
585 // This test makes no sense on an OpenVMS system.
586 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
587 wxT("the path shouldn't contain file name nor extension") );
589 Assign(volume
, path
, name
, ext
, hasExt
, format
);
592 void wxFileName::Assign(const wxString
& pathOrig
,
593 const wxString
& name
,
599 SplitVolume(pathOrig
, &volume
, &path
, format
);
601 Assign(volume
, path
, name
, ext
, format
);
604 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
606 Assign(dir
, wxEmptyString
, format
);
609 void wxFileName::Clear()
616 // we don't have any absolute path for now
622 // follow symlinks by default
623 m_dontFollowLinks
= false;
627 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
629 return wxFileName(file
, format
);
633 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
636 fn
.AssignDir(dir
, format
);
640 // ----------------------------------------------------------------------------
642 // ----------------------------------------------------------------------------
647 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
649 void RemoveTrailingSeparatorsFromPath(wxString
& strPath
)
651 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
652 // so remove all trailing backslashes from the path - but don't do this for
653 // the paths "d:\" (which are different from "d:"), for just "\" or for
654 // windows unique volume names ("\\?\Volume{GUID}\")
655 while ( wxEndsWithPathSeparator( strPath
) )
657 size_t len
= strPath
.length();
658 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) ||
659 (len
== wxMSWUniqueVolumePrefixLength
&&
660 wxFileName::IsMSWUniqueVolumeNamePath(strPath
)))
665 strPath
.Truncate(len
- 1);
669 #endif // __WINDOWS__ || __OS2__
672 wxFileSystemObjectExists(const wxString
& path
, int flags
)
675 // Should the existence of file/directory with this name be accepted, i.e.
676 // result in the true return value from this function?
677 const bool acceptFile
= (flags
& wxFILE_EXISTS_REGULAR
) != 0;
678 const bool acceptDir
= (flags
& wxFILE_EXISTS_DIR
) != 0;
680 wxString
strPath(path
);
682 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
685 // Ensure that the path doesn't have any trailing separators when
686 // checking for directories.
687 RemoveTrailingSeparatorsFromPath(strPath
);
690 // we must use GetFileAttributes() instead of the ANSI C functions because
691 // it can cope with network (UNC) paths unlike them
692 DWORD ret
= ::GetFileAttributes(strPath
.t_str());
694 if ( ret
== INVALID_FILE_ATTRIBUTES
)
697 if ( ret
& FILE_ATTRIBUTE_DIRECTORY
)
700 // Anything else must be a file (perhaps we should check for
701 // FILE_ATTRIBUTE_REPARSE_POINT?)
703 #elif defined(__OS2__)
706 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
707 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
711 FILESTATUS3 Info
= {{0}};
712 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
713 (void*) &Info
, sizeof(FILESTATUS3
));
715 if ( rc
== NO_ERROR
)
717 if ( Info
.attrFile
& FILE_DIRECTORY
)
723 // We consider that the path must exist if we get a sharing violation for
724 // it but we don't know what is it in this case.
725 if ( rc
== ERROR_SHARING_VIOLATION
)
726 return flags
& wxFILE_EXISTS_ANY
;
728 // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
731 #else // Non-MSW, non-OS/2
733 if ( !StatAny(st
, strPath
, flags
) )
736 if ( S_ISREG(st
.st_mode
) )
738 if ( S_ISDIR(st
.st_mode
) )
740 if ( S_ISLNK(st
.st_mode
) )
742 // Take care to not test for "!= 0" here as this would erroneously
743 // return true if only wxFILE_EXISTS_NO_FOLLOW, which is part of
744 // wxFILE_EXISTS_SYMLINK, is set too.
745 return (flags
& wxFILE_EXISTS_SYMLINK
) == wxFILE_EXISTS_SYMLINK
;
747 if ( S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
) )
748 return (flags
& wxFILE_EXISTS_DEVICE
) != 0;
749 if ( S_ISFIFO(st
.st_mode
) )
750 return (flags
& wxFILE_EXISTS_FIFO
) != 0;
751 if ( S_ISSOCK(st
.st_mode
) )
752 return (flags
& wxFILE_EXISTS_SOCKET
) != 0;
754 return flags
& wxFILE_EXISTS_ANY
;
758 } // anonymous namespace
760 bool wxFileName::FileExists() const
762 int flags
= wxFILE_EXISTS_REGULAR
;
763 if ( !ShouldFollowLink() )
764 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
766 return wxFileSystemObjectExists(GetFullPath(), flags
);
770 bool wxFileName::FileExists( const wxString
&filePath
)
772 return wxFileSystemObjectExists(filePath
, wxFILE_EXISTS_REGULAR
);
775 bool wxFileName::DirExists() const
777 int flags
= wxFILE_EXISTS_DIR
;
778 if ( !ShouldFollowLink() )
779 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
781 return Exists(GetPath(), flags
);
785 bool wxFileName::DirExists( const wxString
&dirPath
)
787 return wxFileSystemObjectExists(dirPath
, wxFILE_EXISTS_DIR
);
790 bool wxFileName::Exists(int flags
) const
792 // Notice that wxFILE_EXISTS_NO_FOLLOW may be specified in the flags even
793 // if our DontFollowLink() hadn't been called and we do honour it then. But
794 // if the user took the care of calling DontFollowLink(), it is always
795 // taken into account.
796 if ( !ShouldFollowLink() )
797 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
799 return wxFileSystemObjectExists(GetFullPath(), flags
);
803 bool wxFileName::Exists(const wxString
& path
, int flags
)
805 return wxFileSystemObjectExists(path
, flags
);
808 // ----------------------------------------------------------------------------
809 // CWD and HOME stuff
810 // ----------------------------------------------------------------------------
812 void wxFileName::AssignCwd(const wxString
& volume
)
814 AssignDir(wxFileName::GetCwd(volume
));
818 wxString
wxFileName::GetCwd(const wxString
& volume
)
820 // if we have the volume, we must get the current directory on this drive
821 // and to do this we have to chdir to this volume - at least under Windows,
822 // I don't know how to get the current drive on another volume elsewhere
825 if ( !volume
.empty() )
828 SetCwd(volume
+ GetVolumeSeparator());
831 wxString cwd
= ::wxGetCwd();
833 if ( !volume
.empty() )
841 bool wxFileName::SetCwd() const
843 return wxFileName::SetCwd( GetPath() );
846 bool wxFileName::SetCwd( const wxString
&cwd
)
848 return ::wxSetWorkingDirectory( cwd
);
851 void wxFileName::AssignHomeDir()
853 AssignDir(wxFileName::GetHomeDir());
856 wxString
wxFileName::GetHomeDir()
858 return ::wxGetHomeDir();
862 // ----------------------------------------------------------------------------
863 // CreateTempFileName
864 // ----------------------------------------------------------------------------
866 #if wxUSE_FILE || wxUSE_FFILE
869 #if !defined wx_fdopen && defined HAVE_FDOPEN
870 #define wx_fdopen fdopen
873 // NB: GetTempFileName() under Windows creates the file, so using
874 // O_EXCL there would fail
876 #define wxOPEN_EXCL 0
878 #define wxOPEN_EXCL O_EXCL
882 #ifdef wxOpenOSFHandle
883 #define WX_HAVE_DELETE_ON_CLOSE
884 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
886 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
888 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
890 DWORD disposition
= OPEN_ALWAYS
;
892 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
893 FILE_FLAG_DELETE_ON_CLOSE
;
895 HANDLE h
= ::CreateFile(filename
.t_str(), access
, 0, NULL
,
896 disposition
, attributes
, NULL
);
898 return wxOpenOSFHandle(h
, wxO_BINARY
);
900 #endif // wxOpenOSFHandle
903 // Helper to open the file
905 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
907 #ifdef WX_HAVE_DELETE_ON_CLOSE
909 return wxOpenWithDeleteOnClose(path
);
912 *deleteOnClose
= false;
914 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
919 // Helper to open the file and attach it to the wxFFile
921 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
924 *deleteOnClose
= false;
925 return file
->Open(path
, wxT("w+b"));
927 int fd
= wxTempOpen(path
, deleteOnClose
);
930 file
->Attach(wx_fdopen(fd
, "w+b"), path
);
931 return file
->IsOpened();
934 #endif // wxUSE_FFILE
938 #define WXFILEARGS(x, y) y
940 #define WXFILEARGS(x, y) x
942 #define WXFILEARGS(x, y) x, y
946 // Implementation of wxFileName::CreateTempFileName().
948 static wxString
wxCreateTempImpl(
949 const wxString
& prefix
,
950 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
951 bool *deleteOnClose
= NULL
)
953 #if wxUSE_FILE && wxUSE_FFILE
954 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
956 wxString path
, dir
, name
;
957 bool wantDeleteOnClose
= false;
961 // set the result to false initially
962 wantDeleteOnClose
= *deleteOnClose
;
963 *deleteOnClose
= false;
967 // easier if it alwasys points to something
968 deleteOnClose
= &wantDeleteOnClose
;
971 // use the directory specified by the prefix
972 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
976 dir
= wxFileName::GetTempDir();
979 #if defined(__WXWINCE__)
980 path
= dir
+ wxT("\\") + name
;
982 while (wxFileName::FileExists(path
))
984 path
= dir
+ wxT("\\") + name
;
989 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
990 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
991 wxStringBuffer(path
, MAX_PATH
+ 1)))
993 wxLogLastError(wxT("GetTempFileName"));
1001 if ( !wxEndsWithPathSeparator(dir
) &&
1002 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
1004 path
+= wxFILE_SEP_PATH
;
1009 #if defined(HAVE_MKSTEMP)
1010 // scratch space for mkstemp()
1011 path
+= wxT("XXXXXX");
1013 // we need to copy the path to the buffer in which mkstemp() can modify it
1014 wxCharBuffer
buf(path
.fn_str());
1016 // cast is safe because the string length doesn't change
1017 int fdTemp
= mkstemp( (char*)(const char*) buf
);
1020 // this might be not necessary as mkstemp() on most systems should have
1021 // already done it but it doesn't hurt neither...
1024 else // mkstemp() succeeded
1026 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1029 // avoid leaking the fd
1032 fileTemp
->Attach(fdTemp
);
1041 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"), path
);
1043 ffileTemp
->Open(path
, wxT("r+b"));
1054 #else // !HAVE_MKSTEMP
1058 path
+= wxT("XXXXXX");
1060 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
1061 if ( !mktemp( (char*)(const char*) buf
) )
1067 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1069 #else // !HAVE_MKTEMP (includes __DOS__)
1070 // generate the unique file name ourselves
1071 #if !defined(__DOS__)
1072 path
<< (unsigned int)getpid();
1077 static const size_t numTries
= 1000;
1078 for ( size_t n
= 0; n
< numTries
; n
++ )
1080 // 3 hex digits is enough for numTries == 1000 < 4096
1081 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
1082 if ( !wxFileName::FileExists(pathTry
) )
1091 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1093 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1095 #endif // Windows/!Windows
1099 wxLogSysError(_("Failed to create a temporary file name"));
1105 // open the file - of course, there is a race condition here, this is
1106 // why we always prefer using mkstemp()...
1108 if ( fileTemp
&& !fileTemp
->IsOpened() )
1110 *deleteOnClose
= wantDeleteOnClose
;
1111 int fd
= wxTempOpen(path
, deleteOnClose
);
1113 fileTemp
->Attach(fd
);
1120 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1122 *deleteOnClose
= wantDeleteOnClose
;
1123 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1129 // FIXME: If !ok here should we loop and try again with another
1130 // file name? That is the standard recourse if open(O_EXCL)
1131 // fails, though of course it should be protected against
1132 // possible infinite looping too.
1134 wxLogError(_("Failed to open temporary file."));
1144 static bool wxCreateTempImpl(
1145 const wxString
& prefix
,
1146 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1149 bool deleteOnClose
= true;
1151 *name
= wxCreateTempImpl(prefix
,
1152 WXFILEARGS(fileTemp
, ffileTemp
),
1155 bool ok
= !name
->empty();
1160 else if (ok
&& wxRemoveFile(*name
))
1168 static void wxAssignTempImpl(
1170 const wxString
& prefix
,
1171 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1174 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1176 if ( tempname
.empty() )
1178 // error, failed to get temp file name
1183 fn
->Assign(tempname
);
1188 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1190 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1194 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1196 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1199 #endif // wxUSE_FILE || wxUSE_FFILE
1204 wxString
wxCreateTempFileName(const wxString
& prefix
,
1206 bool *deleteOnClose
)
1208 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1211 bool wxCreateTempFile(const wxString
& prefix
,
1215 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1218 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1220 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1225 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1227 return wxCreateTempFileName(prefix
, fileTemp
);
1230 #endif // wxUSE_FILE
1235 wxString
wxCreateTempFileName(const wxString
& prefix
,
1237 bool *deleteOnClose
)
1239 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1242 bool wxCreateTempFile(const wxString
& prefix
,
1246 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1250 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1252 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1257 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1259 return wxCreateTempFileName(prefix
, fileTemp
);
1262 #endif // wxUSE_FFILE
1265 // ----------------------------------------------------------------------------
1266 // directory operations
1267 // ----------------------------------------------------------------------------
1269 // helper of GetTempDir(): check if the given directory exists and return it if
1270 // it does or an empty string otherwise
1274 wxString
CheckIfDirExists(const wxString
& dir
)
1276 return wxFileName::DirExists(dir
) ? dir
: wxString();
1279 } // anonymous namespace
1281 wxString
wxFileName::GetTempDir()
1283 // first try getting it from environment: this allows overriding the values
1284 // used by default if the user wants to create temporary files in another
1286 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1289 dir
= CheckIfDirExists(wxGetenv("TMP"));
1291 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1294 // if no environment variables are set, use the system default
1297 #if defined(__WXWINCE__)
1298 dir
= CheckIfDirExists(wxT("\\temp"));
1299 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1300 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1302 wxLogLastError(wxT("GetTempPath"));
1304 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1305 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1306 #endif // systems with native way
1308 else // we got directory from an environment variable
1310 // remove any trailing path separators, we don't want to ever return
1311 // them from this function for consistency
1312 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1313 if ( lastNonSep
== wxString::npos
)
1315 // the string consists entirely of separators, leave only one
1316 dir
= GetPathSeparator();
1320 dir
.erase(lastNonSep
+ 1);
1324 // fall back to hard coded value
1327 #ifdef __UNIX_LIKE__
1328 dir
= CheckIfDirExists("/tmp");
1330 #endif // __UNIX_LIKE__
1337 bool wxFileName::Mkdir( int perm
, int flags
) const
1339 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1342 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1344 if ( flags
& wxPATH_MKDIR_FULL
)
1346 // split the path in components
1347 wxFileName filename
;
1348 filename
.AssignDir(dir
);
1351 if ( filename
.HasVolume())
1353 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1356 wxArrayString dirs
= filename
.GetDirs();
1357 size_t count
= dirs
.GetCount();
1358 for ( size_t i
= 0; i
< count
; i
++ )
1360 if ( i
> 0 || filename
.IsAbsolute() )
1361 currPath
+= wxFILE_SEP_PATH
;
1362 currPath
+= dirs
[i
];
1364 if (!DirExists(currPath
))
1366 if (!wxMkdir(currPath
, perm
))
1368 // no need to try creating further directories
1378 return ::wxMkdir( dir
, perm
);
1381 bool wxFileName::Rmdir(int flags
) const
1383 return wxFileName::Rmdir( GetPath(), flags
);
1386 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1389 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1391 // SHFileOperation needs double null termination string
1392 // but without separator at the end of the path
1394 if ( path
.Last() == wxFILE_SEP_PATH
)
1398 SHFILEOPSTRUCT fileop
;
1399 wxZeroMemory(fileop
);
1400 fileop
.wFunc
= FO_DELETE
;
1401 fileop
.pFrom
= path
.t_str();
1402 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1404 // FOF_NOERRORUI is not defined in WinCE
1405 fileop
.fFlags
|= FOF_NOERRORUI
;
1408 int ret
= SHFileOperation(&fileop
);
1411 // SHFileOperation may return non-Win32 error codes, so the error
1412 // message can be incorrect
1413 wxLogApiError(wxT("SHFileOperation"), ret
);
1419 else if ( flags
& wxPATH_RMDIR_FULL
)
1420 #else // !__WINDOWS__
1421 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1422 #endif // !__WINDOWS__
1425 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1427 // When deleting the tree recursively, we are supposed to delete
1428 // this directory itself even when it is a symlink -- but without
1429 // following it. Do it here as wxRmdir() would simply follow if
1430 // called for a symlink.
1431 if ( wxFileName::Exists(dir
, wxFILE_EXISTS_SYMLINK
) )
1433 return wxRemoveFile(dir
);
1436 #endif // !__WINDOWS__
1439 if ( path
.Last() != wxFILE_SEP_PATH
)
1440 path
+= wxFILE_SEP_PATH
;
1444 if ( !d
.IsOpened() )
1449 // First delete all subdirectories: notice that we don't follow
1450 // symbolic links, potentially leading outside this directory, to avoid
1451 // unpleasant surprises.
1452 bool cont
= d
.GetFirst(&filename
, wxString(),
1453 wxDIR_DIRS
| wxDIR_HIDDEN
| wxDIR_NO_FOLLOW
);
1456 wxFileName::Rmdir(path
+ filename
, flags
);
1457 cont
= d
.GetNext(&filename
);
1461 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1463 // Delete all files too and, for the same reasons as above, don't
1464 // follow symlinks which could refer to the files outside of this
1465 // directory and just delete the symlinks themselves.
1466 cont
= d
.GetFirst(&filename
, wxString(),
1467 wxDIR_FILES
| wxDIR_HIDDEN
| wxDIR_NO_FOLLOW
);
1470 ::wxRemoveFile(path
+ filename
);
1471 cont
= d
.GetNext(&filename
);
1474 #endif // !__WINDOWS__
1477 return ::wxRmdir(dir
);
1480 // ----------------------------------------------------------------------------
1481 // path normalization
1482 // ----------------------------------------------------------------------------
1484 bool wxFileName::Normalize(int flags
,
1485 const wxString
& cwd
,
1486 wxPathFormat format
)
1488 // deal with env vars renaming first as this may seriously change the path
1489 if ( flags
& wxPATH_NORM_ENV_VARS
)
1491 wxString pathOrig
= GetFullPath(format
);
1492 wxString path
= wxExpandEnvVars(pathOrig
);
1493 if ( path
!= pathOrig
)
1499 // the existing path components
1500 wxArrayString dirs
= GetDirs();
1502 // the path to prepend in front to make the path absolute
1505 format
= GetFormat(format
);
1507 // set up the directory to use for making the path absolute later
1508 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1512 curDir
.AssignCwd(GetVolume());
1514 else // cwd provided
1516 curDir
.AssignDir(cwd
);
1520 // handle ~ stuff under Unix only
1521 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1523 if ( !dirs
.IsEmpty() )
1525 wxString dir
= dirs
[0u];
1526 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1528 // to make the path absolute use the home directory
1529 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1535 // transform relative path into abs one
1536 if ( curDir
.IsOk() )
1538 // this path may be relative because it doesn't have the volume name
1539 // and still have m_relative=true; in this case we shouldn't modify
1540 // our directory components but just set the current volume
1541 if ( !HasVolume() && curDir
.HasVolume() )
1543 SetVolume(curDir
.GetVolume());
1547 // yes, it was the case - we don't need curDir then
1552 // finally, prepend curDir to the dirs array
1553 wxArrayString dirsNew
= curDir
.GetDirs();
1554 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1556 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1557 // return for some reason an absolute path, then curDir maybe not be absolute!
1558 if ( !curDir
.m_relative
)
1560 // we have prepended an absolute path and thus we are now an absolute
1564 // else if (flags & wxPATH_NORM_ABSOLUTE):
1565 // should we warn the user that we didn't manage to make the path absolute?
1568 // now deal with ".", ".." and the rest
1570 size_t count
= dirs
.GetCount();
1571 for ( size_t n
= 0; n
< count
; n
++ )
1573 wxString dir
= dirs
[n
];
1575 if ( flags
& wxPATH_NORM_DOTS
)
1577 if ( dir
== wxT(".") )
1583 if ( dir
== wxT("..") )
1585 if ( m_dirs
.empty() )
1587 // We have more ".." than directory components so far.
1588 // Don't treat this as an error as the path could have been
1589 // entered by user so try to handle it reasonably: if the
1590 // path is absolute, just ignore the extra ".." because
1591 // "/.." is the same as "/". Otherwise, i.e. for relative
1592 // paths, keep ".." unchanged because removing it would
1593 // modify the file a relative path refers to.
1598 else // Normal case, go one step up.
1609 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1610 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1613 if (GetShortcutTarget(GetFullPath(format
), filename
))
1621 #if defined(__WIN32__)
1622 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1624 Assign(GetLongPath());
1628 // Change case (this should be kept at the end of the function, to ensure
1629 // that the path doesn't change any more after we normalize its case)
1630 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1632 m_volume
.MakeLower();
1636 // directory entries must be made lower case as well
1637 count
= m_dirs
.GetCount();
1638 for ( size_t i
= 0; i
< count
; i
++ )
1640 m_dirs
[i
].MakeLower();
1648 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1649 const wxString
& replacementFmtString
,
1650 wxPathFormat format
)
1652 // look into stringForm for the contents of the given environment variable
1654 if (envname
.empty() ||
1655 !wxGetEnv(envname
, &val
))
1660 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1661 // do not touch the file name and the extension
1663 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1664 stringForm
.Replace(val
, replacement
);
1666 // Now assign ourselves the modified path:
1667 Assign(stringForm
, GetFullName(), format
);
1673 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1675 wxString homedir
= wxGetHomeDir();
1676 if (homedir
.empty())
1679 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1680 // do not touch the file name and the extension
1682 stringForm
.Replace(homedir
, "~");
1684 // Now assign ourselves the modified path:
1685 Assign(stringForm
, GetFullName(), format
);
1690 // ----------------------------------------------------------------------------
1691 // get the shortcut target
1692 // ----------------------------------------------------------------------------
1694 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1695 // The .lnk file is a plain text file so it should be easy to
1696 // make it work. Hint from Google Groups:
1697 // "If you open up a lnk file, you'll see a
1698 // number, followed by a pound sign (#), followed by more text. The
1699 // number is the number of characters that follows the pound sign. The
1700 // characters after the pound sign are the command line (which _can_
1701 // include arguments) to be executed. Any path (e.g. \windows\program
1702 // files\myapp.exe) that includes spaces needs to be enclosed in
1703 // quotation marks."
1705 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1707 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1708 wxString
& targetFilename
,
1709 wxString
* arguments
) const
1711 wxString path
, file
, ext
;
1712 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1716 bool success
= false;
1718 // Assume it's not a shortcut if it doesn't end with lnk
1719 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1722 // create a ShellLink object
1723 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1724 IID_IShellLink
, (LPVOID
*) &psl
);
1726 if (SUCCEEDED(hres
))
1729 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1730 if (SUCCEEDED(hres
))
1732 WCHAR wsz
[MAX_PATH
];
1734 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1737 hres
= ppf
->Load(wsz
, 0);
1740 if (SUCCEEDED(hres
))
1743 // Wrong prototype in early versions
1744 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1745 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1747 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1749 targetFilename
= wxString(buf
);
1750 success
= (shortcutPath
!= targetFilename
);
1752 psl
->GetArguments(buf
, 2048);
1754 if (!args
.empty() && arguments
)
1766 #endif // __WIN32__ && !__WXWINCE__
1769 // ----------------------------------------------------------------------------
1770 // absolute/relative paths
1771 // ----------------------------------------------------------------------------
1773 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1775 // unix paths beginning with ~ are reported as being absolute
1776 if ( format
== wxPATH_UNIX
)
1778 if ( !m_dirs
.IsEmpty() )
1780 wxString dir
= m_dirs
[0u];
1782 if (!dir
.empty() && dir
[0u] == wxT('~'))
1787 // if our path doesn't start with a path separator, it's not an absolute
1792 if ( !GetVolumeSeparator(format
).empty() )
1794 // this format has volumes and an absolute path must have one, it's not
1795 // enough to have the full path to be an absolute file under Windows
1796 if ( GetVolume().empty() )
1803 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1805 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1807 // get cwd only once - small time saving
1808 wxString cwd
= wxGetCwd();
1809 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1810 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1812 bool withCase
= IsCaseSensitive(format
);
1814 // we can't do anything if the files live on different volumes
1815 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1821 // same drive, so we don't need our volume
1824 // remove common directories starting at the top
1825 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1826 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1829 fnBase
.m_dirs
.RemoveAt(0);
1832 // add as many ".." as needed
1833 size_t count
= fnBase
.m_dirs
.GetCount();
1834 for ( size_t i
= 0; i
< count
; i
++ )
1836 m_dirs
.Insert(wxT(".."), 0u);
1839 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1841 // a directory made relative with respect to itself is '.' under Unix
1842 // and DOS, by definition (but we don't have to insert "./" for the
1844 if ( m_dirs
.IsEmpty() && IsDir() )
1846 m_dirs
.Add(wxT('.'));
1856 // ----------------------------------------------------------------------------
1857 // filename kind tests
1858 // ----------------------------------------------------------------------------
1860 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1862 wxFileName fn1
= *this,
1865 // get cwd only once - small time saving
1866 wxString cwd
= wxGetCwd();
1867 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1868 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1870 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1873 #if defined(__UNIX__)
1874 wxStructStat st1
, st2
;
1875 if ( StatAny(st1
, fn1
) && StatAny(st2
, fn2
) )
1877 if ( st1
.st_ino
== st2
.st_ino
&& st1
.st_dev
== st2
.st_dev
)
1880 //else: It's not an error if one or both files don't exist.
1881 #endif // defined __UNIX__
1887 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1889 // only Unix filenames are truly case-sensitive
1890 return GetFormat(format
) == wxPATH_UNIX
;
1894 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1896 // Inits to forbidden characters that are common to (almost) all platforms.
1897 wxString strForbiddenChars
= wxT("*?");
1899 // If asserts, wxPathFormat has been changed. In case of a new path format
1900 // addition, the following code might have to be updated.
1901 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1902 switch ( GetFormat(format
) )
1905 wxFAIL_MSG( wxT("Unknown path format") );
1906 // !! Fall through !!
1912 // On a Mac even names with * and ? are allowed (Tested with OS
1913 // 9.2.1 and OS X 10.2.5)
1914 strForbiddenChars
.clear();
1918 strForbiddenChars
+= wxT("\\/:\"<>|");
1925 return strForbiddenChars
;
1929 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1932 return wxEmptyString
;
1936 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1937 (GetFormat(format
) == wxPATH_VMS
) )
1939 sepVol
= wxFILE_SEP_DSK
;
1948 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1951 switch ( GetFormat(format
) )
1954 // accept both as native APIs do but put the native one first as
1955 // this is the one we use in GetFullPath()
1956 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1960 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1964 seps
= wxFILE_SEP_PATH_UNIX
;
1968 seps
= wxFILE_SEP_PATH_MAC
;
1972 seps
= wxFILE_SEP_PATH_VMS
;
1980 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1982 format
= GetFormat(format
);
1984 // under VMS the end of the path is ']', not the path separator used to
1985 // separate the components
1986 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1990 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1992 // wxString::Find() doesn't work as expected with NUL - it will always find
1993 // it, so test for it separately
1994 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1999 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
2001 // return true if the format used is the DOS/Windows one and the string begins
2002 // with a Windows unique volume name ("\\?\Volume{guid}\")
2003 return format
== wxPATH_DOS
&&
2004 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
2005 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
2006 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
2009 // ----------------------------------------------------------------------------
2010 // path components manipulation
2011 // ----------------------------------------------------------------------------
2013 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
2017 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
2022 const size_t len
= dir
.length();
2023 for ( size_t n
= 0; n
< len
; n
++ )
2025 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
2027 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
2036 bool wxFileName::AppendDir( const wxString
& dir
)
2038 if (!IsValidDirComponent(dir
))
2044 void wxFileName::PrependDir( const wxString
& dir
)
2049 bool wxFileName::InsertDir(size_t before
, const wxString
& dir
)
2051 if (!IsValidDirComponent(dir
))
2053 m_dirs
.Insert(dir
, before
);
2057 void wxFileName::RemoveDir(size_t pos
)
2059 m_dirs
.RemoveAt(pos
);
2062 // ----------------------------------------------------------------------------
2064 // ----------------------------------------------------------------------------
2066 void wxFileName::SetFullName(const wxString
& fullname
)
2068 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
2069 &m_name
, &m_ext
, &m_hasExt
);
2072 wxString
wxFileName::GetFullName() const
2074 wxString fullname
= m_name
;
2077 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
2083 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
2085 format
= GetFormat( format
);
2089 // return the volume with the path as well if requested
2090 if ( flags
& wxPATH_GET_VOLUME
)
2092 fullpath
+= wxGetVolumeString(GetVolume(), format
);
2095 // the leading character
2100 fullpath
+= wxFILE_SEP_PATH_MAC
;
2105 fullpath
+= wxFILE_SEP_PATH_DOS
;
2109 wxFAIL_MSG( wxT("Unknown path format") );
2115 fullpath
+= wxFILE_SEP_PATH_UNIX
;
2120 // no leading character here but use this place to unset
2121 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2122 // as, if I understand correctly, there should never be a dot
2123 // before the closing bracket
2124 flags
&= ~wxPATH_GET_SEPARATOR
;
2127 if ( m_dirs
.empty() )
2129 // there is nothing more
2133 // then concatenate all the path components using the path separator
2134 if ( format
== wxPATH_VMS
)
2136 fullpath
+= wxT('[');
2139 const size_t dirCount
= m_dirs
.GetCount();
2140 for ( size_t i
= 0; i
< dirCount
; i
++ )
2145 if ( m_dirs
[i
] == wxT(".") )
2147 // skip appending ':', this shouldn't be done in this
2148 // case as "::" is interpreted as ".." under Unix
2152 // convert back from ".." to nothing
2153 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2154 fullpath
+= m_dirs
[i
];
2158 wxFAIL_MSG( wxT("Unexpected path format") );
2159 // still fall through
2163 fullpath
+= m_dirs
[i
];
2167 // TODO: What to do with ".." under VMS
2169 // convert back from ".." to nothing
2170 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2171 fullpath
+= m_dirs
[i
];
2175 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2176 fullpath
+= GetPathSeparator(format
);
2179 if ( format
== wxPATH_VMS
)
2181 fullpath
+= wxT(']');
2187 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2189 // we already have a function to get the path
2190 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2193 // now just add the file name and extension to it
2194 fullpath
+= GetFullName();
2199 // Return the short form of the path (returns identity on non-Windows platforms)
2200 wxString
wxFileName::GetShortPath() const
2202 wxString
path(GetFullPath());
2204 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2205 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2209 if ( ::GetShortPathName
2212 wxStringBuffer(pathOut
, sz
),
2224 // Return the long form of the path (returns identity on non-Windows platforms)
2225 wxString
wxFileName::GetLongPath() const
2228 path
= GetFullPath();
2230 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2232 #if wxUSE_DYNLIB_CLASS
2233 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2235 // this is MT-safe as in the worst case we're going to resolve the function
2236 // twice -- but as the result is the same in both threads, it's ok
2237 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2238 if ( !s_pfnGetLongPathName
)
2240 static bool s_triedToLoad
= false;
2242 if ( !s_triedToLoad
)
2244 s_triedToLoad
= true;
2246 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2248 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2253 #endif // Unicode/ANSI
2255 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2257 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2258 dllKernel
.GetSymbol(GetLongPathName
);
2261 // note that kernel32.dll can be unloaded, it stays in memory
2262 // anyhow as all Win32 programs link to it and so it's safe to call
2263 // GetLongPathName() even after unloading it
2267 if ( s_pfnGetLongPathName
)
2269 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2272 if ( (*s_pfnGetLongPathName
)
2275 wxStringBuffer(pathOut
, dwSize
),
2283 #endif // wxUSE_DYNLIB_CLASS
2285 // The OS didn't support GetLongPathName, or some other error.
2286 // We need to call FindFirstFile on each component in turn.
2288 WIN32_FIND_DATA findFileData
;
2292 pathOut
= GetVolume() +
2293 GetVolumeSeparator(wxPATH_DOS
) +
2294 GetPathSeparator(wxPATH_DOS
);
2298 wxArrayString dirs
= GetDirs();
2299 dirs
.Add(GetFullName());
2303 size_t count
= dirs
.GetCount();
2304 for ( size_t i
= 0; i
< count
; i
++ )
2306 const wxString
& dir
= dirs
[i
];
2308 // We're using pathOut to collect the long-name path, but using a
2309 // temporary for appending the last path component which may be
2311 tmpPath
= pathOut
+ dir
;
2313 // We must not process "." or ".." here as they would be (unexpectedly)
2314 // replaced by the corresponding directory names so just leave them
2317 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2318 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2319 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2321 tmpPath
+= wxFILE_SEP_PATH
;
2326 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2327 if (hFind
== INVALID_HANDLE_VALUE
)
2329 // Error: most likely reason is that path doesn't exist, so
2330 // append any unprocessed parts and return
2331 for ( i
+= 1; i
< count
; i
++ )
2332 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2337 pathOut
+= findFileData
.cFileName
;
2338 if ( (i
< (count
-1)) )
2339 pathOut
+= wxFILE_SEP_PATH
;
2345 #endif // Win32/!Win32
2350 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2352 if (format
== wxPATH_NATIVE
)
2354 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2355 format
= wxPATH_DOS
;
2356 #elif defined(__VMS)
2357 format
= wxPATH_VMS
;
2359 format
= wxPATH_UNIX
;
2365 #ifdef wxHAS_FILESYSTEM_VOLUMES
2368 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2370 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2372 wxString
vol(drive
);
2373 vol
+= wxFILE_SEP_DSK
;
2374 if ( flags
& wxPATH_GET_SEPARATOR
)
2375 vol
+= wxFILE_SEP_PATH
;
2380 #endif // wxHAS_FILESYSTEM_VOLUMES
2382 // ----------------------------------------------------------------------------
2383 // path splitting function
2384 // ----------------------------------------------------------------------------
2388 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2389 wxString
*pstrVolume
,
2391 wxPathFormat format
)
2393 format
= GetFormat(format
);
2395 wxString fullpath
= fullpathWithVolume
;
2397 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2399 // special Windows unique volume names hack: transform
2400 // \\?\Volume{guid}\path into Volume{guid}:path
2401 // note: this check must be done before the check for UNC path
2403 // we know the last backslash from the unique volume name is located
2404 // there from IsMSWUniqueVolumeNamePath
2405 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2407 // paths starting with a unique volume name should always be absolute
2408 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2410 // remove the leading "\\?\" part
2411 fullpath
.erase(0, 4);
2413 else if ( IsUNCPath(fullpath
, format
) )
2415 // special Windows UNC paths hack: transform \\share\path into share:path
2417 fullpath
.erase(0, 2);
2419 size_t posFirstSlash
=
2420 fullpath
.find_first_of(GetPathTerminators(format
));
2421 if ( posFirstSlash
!= wxString::npos
)
2423 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2425 // UNC paths are always absolute, right? (FIXME)
2426 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2430 // We separate the volume here
2431 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2433 wxString sepVol
= GetVolumeSeparator(format
);
2435 // we have to exclude the case of a colon in the very beginning of the
2436 // string as it can't be a volume separator (nor can this be a valid
2437 // DOS file name at all but we'll leave dealing with this to our caller)
2438 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2439 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2443 *pstrVolume
= fullpath
.Left(posFirstColon
);
2446 // remove the volume name and the separator from the full path
2447 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2452 *pstrPath
= fullpath
;
2456 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2457 wxString
*pstrVolume
,
2462 wxPathFormat format
)
2464 format
= GetFormat(format
);
2467 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2469 // find the positions of the last dot and last path separator in the path
2470 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2471 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2473 // check whether this dot occurs at the very beginning of a path component
2474 if ( (posLastDot
!= wxString::npos
) &&
2476 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2477 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2479 // dot may be (and commonly -- at least under Unix -- is) the first
2480 // character of the filename, don't treat the entire filename as
2481 // extension in this case
2482 posLastDot
= wxString::npos
;
2485 // if we do have a dot and a slash, check that the dot is in the name part
2486 if ( (posLastDot
!= wxString::npos
) &&
2487 (posLastSlash
!= wxString::npos
) &&
2488 (posLastDot
< posLastSlash
) )
2490 // the dot is part of the path, not the start of the extension
2491 posLastDot
= wxString::npos
;
2494 // now fill in the variables provided by user
2497 if ( posLastSlash
== wxString::npos
)
2504 // take everything up to the path separator but take care to make
2505 // the path equal to something like '/', not empty, for the files
2506 // immediately under root directory
2507 size_t len
= posLastSlash
;
2509 // this rule does not apply to mac since we do not start with colons (sep)
2510 // except for relative paths
2511 if ( !len
&& format
!= wxPATH_MAC
)
2514 *pstrPath
= fullpath
.Left(len
);
2516 // special VMS hack: remove the initial bracket
2517 if ( format
== wxPATH_VMS
)
2519 if ( (*pstrPath
)[0u] == wxT('[') )
2520 pstrPath
->erase(0, 1);
2527 // take all characters starting from the one after the last slash and
2528 // up to, but excluding, the last dot
2529 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2531 if ( posLastDot
== wxString::npos
)
2533 // take all until the end
2534 count
= wxString::npos
;
2536 else if ( posLastSlash
== wxString::npos
)
2540 else // have both dot and slash
2542 count
= posLastDot
- posLastSlash
- 1;
2545 *pstrName
= fullpath
.Mid(nStart
, count
);
2548 // finally deal with the extension here: we have an added complication that
2549 // extension may be empty (but present) as in "foo." where trailing dot
2550 // indicates the empty extension at the end -- and hence we must remember
2551 // that we have it independently of pstrExt
2552 if ( posLastDot
== wxString::npos
)
2562 // take everything after the dot
2564 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2571 void wxFileName::SplitPath(const wxString
& fullpath
,
2575 wxPathFormat format
)
2578 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2582 path
->Prepend(wxGetVolumeString(volume
, format
));
2587 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2589 wxFileName
fn(fullpath
);
2591 return fn
.GetFullPath();
2594 // ----------------------------------------------------------------------------
2596 // ----------------------------------------------------------------------------
2600 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2601 const wxDateTime
*dtMod
,
2602 const wxDateTime
*dtCreate
) const
2604 #if defined(__WIN32__)
2605 FILETIME ftAccess
, ftCreate
, ftWrite
;
2608 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2610 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2612 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2618 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2620 wxLogError(_("Setting directory access times is not supported "
2621 "under this OS version"));
2626 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2630 path
= GetFullPath();
2634 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2637 if ( ::SetFileTime(fh
,
2638 dtCreate
? &ftCreate
: NULL
,
2639 dtAccess
? &ftAccess
: NULL
,
2640 dtMod
? &ftWrite
: NULL
) )
2645 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2646 wxUnusedVar(dtCreate
);
2648 if ( !dtAccess
&& !dtMod
)
2650 // can't modify the creation time anyhow, don't try
2654 // if dtAccess or dtMod is not specified, use the other one (which must be
2655 // non NULL because of the test above) for both times
2657 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2658 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2659 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2663 #else // other platform
2664 wxUnusedVar(dtAccess
);
2666 wxUnusedVar(dtCreate
);
2669 wxLogSysError(_("Failed to modify file times for '%s'"),
2670 GetFullPath().c_str());
2675 bool wxFileName::Touch() const
2677 #if defined(__UNIX_LIKE__)
2678 // under Unix touching file is simple: just pass NULL to utime()
2679 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2684 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2687 #else // other platform
2688 wxDateTime dtNow
= wxDateTime::Now();
2690 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2694 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2696 wxDateTime
*dtCreate
) const
2698 #if defined(__WIN32__)
2699 // we must use different methods for the files and directories under
2700 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2701 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2704 FILETIME ftAccess
, ftCreate
, ftWrite
;
2707 // implemented in msw/dir.cpp
2708 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2709 FILETIME
*, FILETIME
*, FILETIME
*);
2711 // we should pass the path without the trailing separator to
2712 // wxGetDirectoryTimes()
2713 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2714 &ftAccess
, &ftCreate
, &ftWrite
);
2718 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2721 ok
= ::GetFileTime(fh
,
2722 dtCreate
? &ftCreate
: NULL
,
2723 dtAccess
? &ftAccess
: NULL
,
2724 dtMod
? &ftWrite
: NULL
) != 0;
2735 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2737 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2739 ConvertFileTimeToWx(dtMod
, ftWrite
);
2743 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2744 // no need to test for IsDir() here
2746 if ( StatAny(stBuf
, *this) )
2748 // Android defines st_*time fields as unsigned long, but time_t as long,
2749 // hence the static_casts.
2751 dtAccess
->Set(static_cast<time_t>(stBuf
.st_atime
));
2753 dtMod
->Set(static_cast<time_t>(stBuf
.st_mtime
));
2755 dtCreate
->Set(static_cast<time_t>(stBuf
.st_ctime
));
2759 #else // other platform
2760 wxUnusedVar(dtAccess
);
2762 wxUnusedVar(dtCreate
);
2765 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2766 GetFullPath().c_str());
2771 #endif // wxUSE_DATETIME
2774 // ----------------------------------------------------------------------------
2775 // file size functions
2776 // ----------------------------------------------------------------------------
2781 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2783 if (!wxFileExists(filename
))
2784 return wxInvalidSize
;
2786 #if defined(__WIN32__)
2787 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2789 return wxInvalidSize
;
2791 DWORD lpFileSizeHigh
;
2792 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2793 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2794 return wxInvalidSize
;
2796 return wxULongLong(lpFileSizeHigh
, ret
);
2797 #else // ! __WIN32__
2799 if (wxStat( filename
, &st
) != 0)
2800 return wxInvalidSize
;
2801 return wxULongLong(st
.st_size
);
2806 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2807 const wxString
&nullsize
,
2809 wxSizeConvention conv
)
2811 // deal with trivial case first
2812 if ( bs
== 0 || bs
== wxInvalidSize
)
2815 // depending on the convention used the multiplier may be either 1000 or
2816 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2817 double multiplier
= 1024.;
2822 case wxSIZE_CONV_TRADITIONAL
:
2823 // nothing to do, this corresponds to the default values of both
2824 // the multiplier and infix string
2827 case wxSIZE_CONV_IEC
:
2831 case wxSIZE_CONV_SI
:
2836 const double kiloByteSize
= multiplier
;
2837 const double megaByteSize
= multiplier
* kiloByteSize
;
2838 const double gigaByteSize
= multiplier
* megaByteSize
;
2839 const double teraByteSize
= multiplier
* gigaByteSize
;
2841 const double bytesize
= bs
.ToDouble();
2844 if ( bytesize
< kiloByteSize
)
2845 result
.Printf("%s B", bs
.ToString());
2846 else if ( bytesize
< megaByteSize
)
2847 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2848 else if (bytesize
< gigaByteSize
)
2849 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2850 else if (bytesize
< teraByteSize
)
2851 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2853 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2858 wxULongLong
wxFileName::GetSize() const
2860 return GetSize(GetFullPath());
2863 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2865 wxSizeConvention conv
) const
2867 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2870 #endif // wxUSE_LONGLONG
2872 // ----------------------------------------------------------------------------
2873 // Mac-specific functions
2874 // ----------------------------------------------------------------------------
2876 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2881 class MacDefaultExtensionRecord
2884 MacDefaultExtensionRecord()
2890 // default copy ctor, assignment operator and dtor are ok
2892 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2896 m_creator
= creator
;
2904 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2906 bool gMacDefaultExtensionsInited
= false;
2908 #include "wx/arrimpl.cpp"
2910 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2912 MacDefaultExtensionArray gMacDefaultExtensions
;
2914 // load the default extensions
2915 const MacDefaultExtensionRecord gDefaults
[] =
2917 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2918 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2919 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2922 void MacEnsureDefaultExtensionsLoaded()
2924 if ( !gMacDefaultExtensionsInited
)
2926 // we could load the pc exchange prefs here too
2927 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2929 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2931 gMacDefaultExtensionsInited
= true;
2935 } // anonymous namespace
2937 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2940 FSCatalogInfo catInfo
;
2943 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2945 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2947 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2948 finfo
->fileType
= type
;
2949 finfo
->fileCreator
= creator
;
2950 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2957 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2960 FSCatalogInfo catInfo
;
2963 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2965 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2967 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2968 *type
= finfo
->fileType
;
2969 *creator
= finfo
->fileCreator
;
2976 bool wxFileName::MacSetDefaultTypeAndCreator()
2978 wxUint32 type
, creator
;
2979 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2982 return MacSetTypeAndCreator( type
, creator
) ;
2987 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2989 MacEnsureDefaultExtensionsLoaded() ;
2990 wxString extl
= ext
.Lower() ;
2991 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2993 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2995 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2996 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
3003 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
3005 MacEnsureDefaultExtensionsLoaded();
3006 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
3007 gMacDefaultExtensions
.Add( rec
);
3010 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON