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()
615 m_ext
= wxEmptyString
;
617 // we don't have any absolute path for now
623 // follow symlinks by default
624 m_dontFollowLinks
= false;
628 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
630 return wxFileName(file
, format
);
634 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
637 fn
.AssignDir(dir
, format
);
641 // ----------------------------------------------------------------------------
643 // ----------------------------------------------------------------------------
648 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
650 void RemoveTrailingSeparatorsFromPath(wxString
& strPath
)
652 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
653 // so remove all trailing backslashes from the path - but don't do this for
654 // the paths "d:\" (which are different from "d:"), for just "\" or for
655 // windows unique volume names ("\\?\Volume{GUID}\")
656 while ( wxEndsWithPathSeparator( strPath
) )
658 size_t len
= strPath
.length();
659 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) ||
660 (len
== wxMSWUniqueVolumePrefixLength
&&
661 wxFileName::IsMSWUniqueVolumeNamePath(strPath
)))
666 strPath
.Truncate(len
- 1);
670 #endif // __WINDOWS__ || __OS2__
673 wxFileSystemObjectExists(const wxString
& path
, int flags
)
676 // Should the existence of file/directory with this name be accepted, i.e.
677 // result in the true return value from this function?
678 const bool acceptFile
= (flags
& wxFILE_EXISTS_REGULAR
) != 0;
679 const bool acceptDir
= (flags
& wxFILE_EXISTS_DIR
) != 0;
681 wxString
strPath(path
);
683 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
686 // Ensure that the path doesn't have any trailing separators when
687 // checking for directories.
688 RemoveTrailingSeparatorsFromPath(strPath
);
691 // we must use GetFileAttributes() instead of the ANSI C functions because
692 // it can cope with network (UNC) paths unlike them
693 DWORD ret
= ::GetFileAttributes(strPath
.t_str());
695 if ( ret
== INVALID_FILE_ATTRIBUTES
)
698 if ( ret
& FILE_ATTRIBUTE_DIRECTORY
)
701 // Anything else must be a file (perhaps we should check for
702 // FILE_ATTRIBUTE_REPARSE_POINT?)
704 #elif defined(__OS2__)
707 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
708 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
712 FILESTATUS3 Info
= {{0}};
713 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
714 (void*) &Info
, sizeof(FILESTATUS3
));
716 if ( rc
== NO_ERROR
)
718 if ( Info
.attrFile
& FILE_DIRECTORY
)
724 // We consider that the path must exist if we get a sharing violation for
725 // it but we don't know what is it in this case.
726 if ( rc
== ERROR_SHARING_VIOLATION
)
727 return flags
& wxFILE_EXISTS_ANY
;
729 // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
732 #else // Non-MSW, non-OS/2
734 if ( !StatAny(st
, strPath
, flags
) )
737 if ( S_ISREG(st
.st_mode
) )
739 if ( S_ISDIR(st
.st_mode
) )
741 if ( S_ISLNK(st
.st_mode
) )
743 // Take care to not test for "!= 0" here as this would erroneously
744 // return true if only wxFILE_EXISTS_NO_FOLLOW, which is part of
745 // wxFILE_EXISTS_SYMLINK, is set too.
746 return (flags
& wxFILE_EXISTS_SYMLINK
) == wxFILE_EXISTS_SYMLINK
;
748 if ( S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
) )
749 return (flags
& wxFILE_EXISTS_DEVICE
) != 0;
750 if ( S_ISFIFO(st
.st_mode
) )
751 return (flags
& wxFILE_EXISTS_FIFO
) != 0;
752 if ( S_ISSOCK(st
.st_mode
) )
753 return (flags
& wxFILE_EXISTS_SOCKET
) != 0;
755 return flags
& wxFILE_EXISTS_ANY
;
759 } // anonymous namespace
761 bool wxFileName::FileExists() const
763 int flags
= wxFILE_EXISTS_REGULAR
;
764 if ( !ShouldFollowLink() )
765 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
767 return wxFileSystemObjectExists(GetFullPath(), flags
);
771 bool wxFileName::FileExists( const wxString
&filePath
)
773 return wxFileSystemObjectExists(filePath
, wxFILE_EXISTS_REGULAR
);
776 bool wxFileName::DirExists() const
778 int flags
= wxFILE_EXISTS_DIR
;
779 if ( !ShouldFollowLink() )
780 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
782 return Exists(GetPath(), flags
);
786 bool wxFileName::DirExists( const wxString
&dirPath
)
788 return wxFileSystemObjectExists(dirPath
, wxFILE_EXISTS_DIR
);
791 bool wxFileName::Exists(int flags
) const
793 // Notice that wxFILE_EXISTS_NO_FOLLOW may be specified in the flags even
794 // if our DontFollowLink() hadn't been called and we do honour it then. But
795 // if the user took the care of calling DontFollowLink(), it is always
796 // taken into account.
797 if ( !ShouldFollowLink() )
798 flags
|= wxFILE_EXISTS_NO_FOLLOW
;
800 return wxFileSystemObjectExists(GetFullPath(), flags
);
804 bool wxFileName::Exists(const wxString
& path
, int flags
)
806 return wxFileSystemObjectExists(path
, flags
);
809 // ----------------------------------------------------------------------------
810 // CWD and HOME stuff
811 // ----------------------------------------------------------------------------
813 void wxFileName::AssignCwd(const wxString
& volume
)
815 AssignDir(wxFileName::GetCwd(volume
));
819 wxString
wxFileName::GetCwd(const wxString
& volume
)
821 // if we have the volume, we must get the current directory on this drive
822 // and to do this we have to chdir to this volume - at least under Windows,
823 // I don't know how to get the current drive on another volume elsewhere
826 if ( !volume
.empty() )
829 SetCwd(volume
+ GetVolumeSeparator());
832 wxString cwd
= ::wxGetCwd();
834 if ( !volume
.empty() )
842 bool wxFileName::SetCwd() const
844 return wxFileName::SetCwd( GetPath() );
847 bool wxFileName::SetCwd( const wxString
&cwd
)
849 return ::wxSetWorkingDirectory( cwd
);
852 void wxFileName::AssignHomeDir()
854 AssignDir(wxFileName::GetHomeDir());
857 wxString
wxFileName::GetHomeDir()
859 return ::wxGetHomeDir();
863 // ----------------------------------------------------------------------------
864 // CreateTempFileName
865 // ----------------------------------------------------------------------------
867 #if wxUSE_FILE || wxUSE_FFILE
870 #if !defined wx_fdopen && defined HAVE_FDOPEN
871 #define wx_fdopen fdopen
874 // NB: GetTempFileName() under Windows creates the file, so using
875 // O_EXCL there would fail
877 #define wxOPEN_EXCL 0
879 #define wxOPEN_EXCL O_EXCL
883 #ifdef wxOpenOSFHandle
884 #define WX_HAVE_DELETE_ON_CLOSE
885 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
887 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
889 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
891 DWORD disposition
= OPEN_ALWAYS
;
893 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
894 FILE_FLAG_DELETE_ON_CLOSE
;
896 HANDLE h
= ::CreateFile(filename
.t_str(), access
, 0, NULL
,
897 disposition
, attributes
, NULL
);
899 return wxOpenOSFHandle(h
, wxO_BINARY
);
901 #endif // wxOpenOSFHandle
904 // Helper to open the file
906 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
908 #ifdef WX_HAVE_DELETE_ON_CLOSE
910 return wxOpenWithDeleteOnClose(path
);
913 *deleteOnClose
= false;
915 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
920 // Helper to open the file and attach it to the wxFFile
922 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
925 *deleteOnClose
= false;
926 return file
->Open(path
, wxT("w+b"));
928 int fd
= wxTempOpen(path
, deleteOnClose
);
931 file
->Attach(wx_fdopen(fd
, "w+b"), path
);
932 return file
->IsOpened();
935 #endif // wxUSE_FFILE
939 #define WXFILEARGS(x, y) y
941 #define WXFILEARGS(x, y) x
943 #define WXFILEARGS(x, y) x, y
947 // Implementation of wxFileName::CreateTempFileName().
949 static wxString
wxCreateTempImpl(
950 const wxString
& prefix
,
951 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
952 bool *deleteOnClose
= NULL
)
954 #if wxUSE_FILE && wxUSE_FFILE
955 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
957 wxString path
, dir
, name
;
958 bool wantDeleteOnClose
= false;
962 // set the result to false initially
963 wantDeleteOnClose
= *deleteOnClose
;
964 *deleteOnClose
= false;
968 // easier if it alwasys points to something
969 deleteOnClose
= &wantDeleteOnClose
;
972 // use the directory specified by the prefix
973 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
977 dir
= wxFileName::GetTempDir();
980 #if defined(__WXWINCE__)
981 path
= dir
+ wxT("\\") + name
;
983 while (wxFileName::FileExists(path
))
985 path
= dir
+ wxT("\\") + name
;
990 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
991 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
992 wxStringBuffer(path
, MAX_PATH
+ 1)))
994 wxLogLastError(wxT("GetTempFileName"));
1002 if ( !wxEndsWithPathSeparator(dir
) &&
1003 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
1005 path
+= wxFILE_SEP_PATH
;
1010 #if defined(HAVE_MKSTEMP)
1011 // scratch space for mkstemp()
1012 path
+= wxT("XXXXXX");
1014 // we need to copy the path to the buffer in which mkstemp() can modify it
1015 wxCharBuffer
buf(path
.fn_str());
1017 // cast is safe because the string length doesn't change
1018 int fdTemp
= mkstemp( (char*)(const char*) buf
);
1021 // this might be not necessary as mkstemp() on most systems should have
1022 // already done it but it doesn't hurt neither...
1025 else // mkstemp() succeeded
1027 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1030 // avoid leaking the fd
1033 fileTemp
->Attach(fdTemp
);
1042 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"), path
);
1044 ffileTemp
->Open(path
, wxT("r+b"));
1055 #else // !HAVE_MKSTEMP
1059 path
+= wxT("XXXXXX");
1061 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
1062 if ( !mktemp( (char*)(const char*) buf
) )
1068 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1070 #else // !HAVE_MKTEMP (includes __DOS__)
1071 // generate the unique file name ourselves
1072 #if !defined(__DOS__)
1073 path
<< (unsigned int)getpid();
1078 static const size_t numTries
= 1000;
1079 for ( size_t n
= 0; n
< numTries
; n
++ )
1081 // 3 hex digits is enough for numTries == 1000 < 4096
1082 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
1083 if ( !wxFileName::FileExists(pathTry
) )
1092 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1094 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1096 #endif // Windows/!Windows
1100 wxLogSysError(_("Failed to create a temporary file name"));
1106 // open the file - of course, there is a race condition here, this is
1107 // why we always prefer using mkstemp()...
1109 if ( fileTemp
&& !fileTemp
->IsOpened() )
1111 *deleteOnClose
= wantDeleteOnClose
;
1112 int fd
= wxTempOpen(path
, deleteOnClose
);
1114 fileTemp
->Attach(fd
);
1121 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1123 *deleteOnClose
= wantDeleteOnClose
;
1124 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1130 // FIXME: If !ok here should we loop and try again with another
1131 // file name? That is the standard recourse if open(O_EXCL)
1132 // fails, though of course it should be protected against
1133 // possible infinite looping too.
1135 wxLogError(_("Failed to open temporary file."));
1145 static bool wxCreateTempImpl(
1146 const wxString
& prefix
,
1147 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1150 bool deleteOnClose
= true;
1152 *name
= wxCreateTempImpl(prefix
,
1153 WXFILEARGS(fileTemp
, ffileTemp
),
1156 bool ok
= !name
->empty();
1161 else if (ok
&& wxRemoveFile(*name
))
1169 static void wxAssignTempImpl(
1171 const wxString
& prefix
,
1172 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1175 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1177 if ( tempname
.empty() )
1179 // error, failed to get temp file name
1184 fn
->Assign(tempname
);
1189 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1191 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1195 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1197 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1200 #endif // wxUSE_FILE || wxUSE_FFILE
1205 wxString
wxCreateTempFileName(const wxString
& prefix
,
1207 bool *deleteOnClose
)
1209 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1212 bool wxCreateTempFile(const wxString
& prefix
,
1216 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1219 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1221 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1226 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1228 return wxCreateTempFileName(prefix
, fileTemp
);
1231 #endif // wxUSE_FILE
1236 wxString
wxCreateTempFileName(const wxString
& prefix
,
1238 bool *deleteOnClose
)
1240 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1243 bool wxCreateTempFile(const wxString
& prefix
,
1247 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1251 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1253 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1258 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1260 return wxCreateTempFileName(prefix
, fileTemp
);
1263 #endif // wxUSE_FFILE
1266 // ----------------------------------------------------------------------------
1267 // directory operations
1268 // ----------------------------------------------------------------------------
1270 // helper of GetTempDir(): check if the given directory exists and return it if
1271 // it does or an empty string otherwise
1275 wxString
CheckIfDirExists(const wxString
& dir
)
1277 return wxFileName::DirExists(dir
) ? dir
: wxString();
1280 } // anonymous namespace
1282 wxString
wxFileName::GetTempDir()
1284 // first try getting it from environment: this allows overriding the values
1285 // used by default if the user wants to create temporary files in another
1287 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1290 dir
= CheckIfDirExists(wxGetenv("TMP"));
1292 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1295 // if no environment variables are set, use the system default
1298 #if defined(__WXWINCE__)
1299 dir
= CheckIfDirExists(wxT("\\temp"));
1300 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1301 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1303 wxLogLastError(wxT("GetTempPath"));
1305 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1306 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1307 #endif // systems with native way
1309 else // we got directory from an environment variable
1311 // remove any trailing path separators, we don't want to ever return
1312 // them from this function for consistency
1313 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1314 if ( lastNonSep
== wxString::npos
)
1316 // the string consists entirely of separators, leave only one
1317 dir
= GetPathSeparator();
1321 dir
.erase(lastNonSep
+ 1);
1325 // fall back to hard coded value
1328 #ifdef __UNIX_LIKE__
1329 dir
= CheckIfDirExists("/tmp");
1331 #endif // __UNIX_LIKE__
1338 bool wxFileName::Mkdir( int perm
, int flags
) const
1340 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1343 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1345 if ( flags
& wxPATH_MKDIR_FULL
)
1347 // split the path in components
1348 wxFileName filename
;
1349 filename
.AssignDir(dir
);
1352 if ( filename
.HasVolume())
1354 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1357 wxArrayString dirs
= filename
.GetDirs();
1358 size_t count
= dirs
.GetCount();
1359 for ( size_t i
= 0; i
< count
; i
++ )
1361 if ( i
> 0 || filename
.IsAbsolute() )
1362 currPath
+= wxFILE_SEP_PATH
;
1363 currPath
+= dirs
[i
];
1365 if (!DirExists(currPath
))
1367 if (!wxMkdir(currPath
, perm
))
1369 // no need to try creating further directories
1379 return ::wxMkdir( dir
, perm
);
1382 bool wxFileName::Rmdir(int flags
) const
1384 return wxFileName::Rmdir( GetPath(), flags
);
1387 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1390 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1392 // SHFileOperation needs double null termination string
1393 // but without separator at the end of the path
1395 if ( path
.Last() == wxFILE_SEP_PATH
)
1399 SHFILEOPSTRUCT fileop
;
1400 wxZeroMemory(fileop
);
1401 fileop
.wFunc
= FO_DELETE
;
1402 fileop
.pFrom
= path
.t_str();
1403 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1405 // FOF_NOERRORUI is not defined in WinCE
1406 fileop
.fFlags
|= FOF_NOERRORUI
;
1409 int ret
= SHFileOperation(&fileop
);
1412 // SHFileOperation may return non-Win32 error codes, so the error
1413 // message can be incorrect
1414 wxLogApiError(wxT("SHFileOperation"), ret
);
1420 else if ( flags
& wxPATH_RMDIR_FULL
)
1421 #else // !__WINDOWS__
1422 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1423 #endif // !__WINDOWS__
1426 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1428 // When deleting the tree recursively, we are supposed to delete
1429 // this directory itself even when it is a symlink -- but without
1430 // following it. Do it here as wxRmdir() would simply follow if
1431 // called for a symlink.
1432 if ( wxFileName::Exists(dir
, wxFILE_EXISTS_SYMLINK
) )
1434 return wxRemoveFile(dir
);
1437 #endif // !__WINDOWS__
1440 if ( path
.Last() != wxFILE_SEP_PATH
)
1441 path
+= wxFILE_SEP_PATH
;
1445 if ( !d
.IsOpened() )
1450 // First delete all subdirectories: notice that we don't follow
1451 // symbolic links, potentially leading outside this directory, to avoid
1452 // unpleasant surprises.
1453 bool cont
= d
.GetFirst(&filename
, wxString(),
1454 wxDIR_DIRS
| wxDIR_HIDDEN
| wxDIR_NO_FOLLOW
);
1457 wxFileName::Rmdir(path
+ filename
, flags
);
1458 cont
= d
.GetNext(&filename
);
1462 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1464 // Delete all files too and, for the same reasons as above, don't
1465 // follow symlinks which could refer to the files outside of this
1466 // directory and just delete the symlinks themselves.
1467 cont
= d
.GetFirst(&filename
, wxString(),
1468 wxDIR_FILES
| wxDIR_HIDDEN
| wxDIR_NO_FOLLOW
);
1471 ::wxRemoveFile(path
+ filename
);
1472 cont
= d
.GetNext(&filename
);
1475 #endif // !__WINDOWS__
1478 return ::wxRmdir(dir
);
1481 // ----------------------------------------------------------------------------
1482 // path normalization
1483 // ----------------------------------------------------------------------------
1485 bool wxFileName::Normalize(int flags
,
1486 const wxString
& cwd
,
1487 wxPathFormat format
)
1489 // deal with env vars renaming first as this may seriously change the path
1490 if ( flags
& wxPATH_NORM_ENV_VARS
)
1492 wxString pathOrig
= GetFullPath(format
);
1493 wxString path
= wxExpandEnvVars(pathOrig
);
1494 if ( path
!= pathOrig
)
1500 // the existing path components
1501 wxArrayString dirs
= GetDirs();
1503 // the path to prepend in front to make the path absolute
1506 format
= GetFormat(format
);
1508 // set up the directory to use for making the path absolute later
1509 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1513 curDir
.AssignCwd(GetVolume());
1515 else // cwd provided
1517 curDir
.AssignDir(cwd
);
1521 // handle ~ stuff under Unix only
1522 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1524 if ( !dirs
.IsEmpty() )
1526 wxString dir
= dirs
[0u];
1527 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1529 // to make the path absolute use the home directory
1530 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1536 // transform relative path into abs one
1537 if ( curDir
.IsOk() )
1539 // this path may be relative because it doesn't have the volume name
1540 // and still have m_relative=true; in this case we shouldn't modify
1541 // our directory components but just set the current volume
1542 if ( !HasVolume() && curDir
.HasVolume() )
1544 SetVolume(curDir
.GetVolume());
1548 // yes, it was the case - we don't need curDir then
1553 // finally, prepend curDir to the dirs array
1554 wxArrayString dirsNew
= curDir
.GetDirs();
1555 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1557 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1558 // return for some reason an absolute path, then curDir maybe not be absolute!
1559 if ( !curDir
.m_relative
)
1561 // we have prepended an absolute path and thus we are now an absolute
1565 // else if (flags & wxPATH_NORM_ABSOLUTE):
1566 // should we warn the user that we didn't manage to make the path absolute?
1569 // now deal with ".", ".." and the rest
1571 size_t count
= dirs
.GetCount();
1572 for ( size_t n
= 0; n
< count
; n
++ )
1574 wxString dir
= dirs
[n
];
1576 if ( flags
& wxPATH_NORM_DOTS
)
1578 if ( dir
== wxT(".") )
1584 if ( dir
== wxT("..") )
1586 if ( m_dirs
.empty() )
1588 // We have more ".." than directory components so far.
1589 // Don't treat this as an error as the path could have been
1590 // entered by user so try to handle it reasonably: if the
1591 // path is absolute, just ignore the extra ".." because
1592 // "/.." is the same as "/". Otherwise, i.e. for relative
1593 // paths, keep ".." unchanged because removing it would
1594 // modify the file a relative path refers to.
1599 else // Normal case, go one step up.
1610 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1611 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1614 if (GetShortcutTarget(GetFullPath(format
), filename
))
1622 #if defined(__WIN32__)
1623 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1625 Assign(GetLongPath());
1629 // Change case (this should be kept at the end of the function, to ensure
1630 // that the path doesn't change any more after we normalize its case)
1631 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1633 m_volume
.MakeLower();
1637 // directory entries must be made lower case as well
1638 count
= m_dirs
.GetCount();
1639 for ( size_t i
= 0; i
< count
; i
++ )
1641 m_dirs
[i
].MakeLower();
1649 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1650 const wxString
& replacementFmtString
,
1651 wxPathFormat format
)
1653 // look into stringForm for the contents of the given environment variable
1655 if (envname
.empty() ||
1656 !wxGetEnv(envname
, &val
))
1661 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1662 // do not touch the file name and the extension
1664 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1665 stringForm
.Replace(val
, replacement
);
1667 // Now assign ourselves the modified path:
1668 Assign(stringForm
, GetFullName(), format
);
1674 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1676 wxString homedir
= wxGetHomeDir();
1677 if (homedir
.empty())
1680 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1681 // do not touch the file name and the extension
1683 stringForm
.Replace(homedir
, "~");
1685 // Now assign ourselves the modified path:
1686 Assign(stringForm
, GetFullName(), format
);
1691 // ----------------------------------------------------------------------------
1692 // get the shortcut target
1693 // ----------------------------------------------------------------------------
1695 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1696 // The .lnk file is a plain text file so it should be easy to
1697 // make it work. Hint from Google Groups:
1698 // "If you open up a lnk file, you'll see a
1699 // number, followed by a pound sign (#), followed by more text. The
1700 // number is the number of characters that follows the pound sign. The
1701 // characters after the pound sign are the command line (which _can_
1702 // include arguments) to be executed. Any path (e.g. \windows\program
1703 // files\myapp.exe) that includes spaces needs to be enclosed in
1704 // quotation marks."
1706 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1708 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1709 wxString
& targetFilename
,
1710 wxString
* arguments
) const
1712 wxString path
, file
, ext
;
1713 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1717 bool success
= false;
1719 // Assume it's not a shortcut if it doesn't end with lnk
1720 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1723 // create a ShellLink object
1724 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1725 IID_IShellLink
, (LPVOID
*) &psl
);
1727 if (SUCCEEDED(hres
))
1730 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1731 if (SUCCEEDED(hres
))
1733 WCHAR wsz
[MAX_PATH
];
1735 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1738 hres
= ppf
->Load(wsz
, 0);
1741 if (SUCCEEDED(hres
))
1744 // Wrong prototype in early versions
1745 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1746 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1748 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1750 targetFilename
= wxString(buf
);
1751 success
= (shortcutPath
!= targetFilename
);
1753 psl
->GetArguments(buf
, 2048);
1755 if (!args
.empty() && arguments
)
1767 #endif // __WIN32__ && !__WXWINCE__
1770 // ----------------------------------------------------------------------------
1771 // absolute/relative paths
1772 // ----------------------------------------------------------------------------
1774 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1776 // unix paths beginning with ~ are reported as being absolute
1777 if ( format
== wxPATH_UNIX
)
1779 if ( !m_dirs
.IsEmpty() )
1781 wxString dir
= m_dirs
[0u];
1783 if (!dir
.empty() && dir
[0u] == wxT('~'))
1788 // if our path doesn't start with a path separator, it's not an absolute
1793 if ( !GetVolumeSeparator(format
).empty() )
1795 // this format has volumes and an absolute path must have one, it's not
1796 // enough to have the full path to be an absolute file under Windows
1797 if ( GetVolume().empty() )
1804 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1806 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1808 // get cwd only once - small time saving
1809 wxString cwd
= wxGetCwd();
1810 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1811 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1813 bool withCase
= IsCaseSensitive(format
);
1815 // we can't do anything if the files live on different volumes
1816 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1822 // same drive, so we don't need our volume
1825 // remove common directories starting at the top
1826 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1827 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1830 fnBase
.m_dirs
.RemoveAt(0);
1833 // add as many ".." as needed
1834 size_t count
= fnBase
.m_dirs
.GetCount();
1835 for ( size_t i
= 0; i
< count
; i
++ )
1837 m_dirs
.Insert(wxT(".."), 0u);
1840 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1842 // a directory made relative with respect to itself is '.' under Unix
1843 // and DOS, by definition (but we don't have to insert "./" for the
1845 if ( m_dirs
.IsEmpty() && IsDir() )
1847 m_dirs
.Add(wxT('.'));
1857 // ----------------------------------------------------------------------------
1858 // filename kind tests
1859 // ----------------------------------------------------------------------------
1861 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1863 wxFileName fn1
= *this,
1866 // get cwd only once - small time saving
1867 wxString cwd
= wxGetCwd();
1868 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1869 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1871 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1874 #if defined(__UNIX__)
1875 wxStructStat st1
, st2
;
1876 if ( StatAny(st1
, fn1
) && StatAny(st2
, fn2
) )
1878 if ( st1
.st_ino
== st2
.st_ino
&& st1
.st_dev
== st2
.st_dev
)
1881 //else: It's not an error if one or both files don't exist.
1882 #endif // defined __UNIX__
1888 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1890 // only Unix filenames are truly case-sensitive
1891 return GetFormat(format
) == wxPATH_UNIX
;
1895 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1897 // Inits to forbidden characters that are common to (almost) all platforms.
1898 wxString strForbiddenChars
= wxT("*?");
1900 // If asserts, wxPathFormat has been changed. In case of a new path format
1901 // addition, the following code might have to be updated.
1902 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1903 switch ( GetFormat(format
) )
1906 wxFAIL_MSG( wxT("Unknown path format") );
1907 // !! Fall through !!
1913 // On a Mac even names with * and ? are allowed (Tested with OS
1914 // 9.2.1 and OS X 10.2.5)
1915 strForbiddenChars
= wxEmptyString
;
1919 strForbiddenChars
+= wxT("\\/:\"<>|");
1926 return strForbiddenChars
;
1930 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1933 return wxEmptyString
;
1937 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1938 (GetFormat(format
) == wxPATH_VMS
) )
1940 sepVol
= wxFILE_SEP_DSK
;
1949 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1952 switch ( GetFormat(format
) )
1955 // accept both as native APIs do but put the native one first as
1956 // this is the one we use in GetFullPath()
1957 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1961 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1965 seps
= wxFILE_SEP_PATH_UNIX
;
1969 seps
= wxFILE_SEP_PATH_MAC
;
1973 seps
= wxFILE_SEP_PATH_VMS
;
1981 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1983 format
= GetFormat(format
);
1985 // under VMS the end of the path is ']', not the path separator used to
1986 // separate the components
1987 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1991 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1993 // wxString::Find() doesn't work as expected with NUL - it will always find
1994 // it, so test for it separately
1995 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
2000 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
2002 // return true if the format used is the DOS/Windows one and the string begins
2003 // with a Windows unique volume name ("\\?\Volume{guid}\")
2004 return format
== wxPATH_DOS
&&
2005 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
2006 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
2007 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
2010 // ----------------------------------------------------------------------------
2011 // path components manipulation
2012 // ----------------------------------------------------------------------------
2014 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
2018 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
2023 const size_t len
= dir
.length();
2024 for ( size_t n
= 0; n
< len
; n
++ )
2026 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
2028 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
2037 bool wxFileName::AppendDir( const wxString
& dir
)
2039 if (!IsValidDirComponent(dir
))
2045 void wxFileName::PrependDir( const wxString
& dir
)
2050 bool wxFileName::InsertDir(size_t before
, const wxString
& dir
)
2052 if (!IsValidDirComponent(dir
))
2054 m_dirs
.Insert(dir
, before
);
2058 void wxFileName::RemoveDir(size_t pos
)
2060 m_dirs
.RemoveAt(pos
);
2063 // ----------------------------------------------------------------------------
2065 // ----------------------------------------------------------------------------
2067 void wxFileName::SetFullName(const wxString
& fullname
)
2069 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
2070 &m_name
, &m_ext
, &m_hasExt
);
2073 wxString
wxFileName::GetFullName() const
2075 wxString fullname
= m_name
;
2078 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
2084 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
2086 format
= GetFormat( format
);
2090 // return the volume with the path as well if requested
2091 if ( flags
& wxPATH_GET_VOLUME
)
2093 fullpath
+= wxGetVolumeString(GetVolume(), format
);
2096 // the leading character
2101 fullpath
+= wxFILE_SEP_PATH_MAC
;
2106 fullpath
+= wxFILE_SEP_PATH_DOS
;
2110 wxFAIL_MSG( wxT("Unknown path format") );
2116 fullpath
+= wxFILE_SEP_PATH_UNIX
;
2121 // no leading character here but use this place to unset
2122 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2123 // as, if I understand correctly, there should never be a dot
2124 // before the closing bracket
2125 flags
&= ~wxPATH_GET_SEPARATOR
;
2128 if ( m_dirs
.empty() )
2130 // there is nothing more
2134 // then concatenate all the path components using the path separator
2135 if ( format
== wxPATH_VMS
)
2137 fullpath
+= wxT('[');
2140 const size_t dirCount
= m_dirs
.GetCount();
2141 for ( size_t i
= 0; i
< dirCount
; i
++ )
2146 if ( m_dirs
[i
] == wxT(".") )
2148 // skip appending ':', this shouldn't be done in this
2149 // case as "::" is interpreted as ".." under Unix
2153 // convert back from ".." to nothing
2154 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2155 fullpath
+= m_dirs
[i
];
2159 wxFAIL_MSG( wxT("Unexpected path format") );
2160 // still fall through
2164 fullpath
+= m_dirs
[i
];
2168 // TODO: What to do with ".." under VMS
2170 // convert back from ".." to nothing
2171 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2172 fullpath
+= m_dirs
[i
];
2176 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2177 fullpath
+= GetPathSeparator(format
);
2180 if ( format
== wxPATH_VMS
)
2182 fullpath
+= wxT(']');
2188 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2190 // we already have a function to get the path
2191 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2194 // now just add the file name and extension to it
2195 fullpath
+= GetFullName();
2200 // Return the short form of the path (returns identity on non-Windows platforms)
2201 wxString
wxFileName::GetShortPath() const
2203 wxString
path(GetFullPath());
2205 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2206 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2210 if ( ::GetShortPathName
2213 wxStringBuffer(pathOut
, sz
),
2225 // Return the long form of the path (returns identity on non-Windows platforms)
2226 wxString
wxFileName::GetLongPath() const
2229 path
= GetFullPath();
2231 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2233 #if wxUSE_DYNLIB_CLASS
2234 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2236 // this is MT-safe as in the worst case we're going to resolve the function
2237 // twice -- but as the result is the same in both threads, it's ok
2238 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2239 if ( !s_pfnGetLongPathName
)
2241 static bool s_triedToLoad
= false;
2243 if ( !s_triedToLoad
)
2245 s_triedToLoad
= true;
2247 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2249 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2254 #endif // Unicode/ANSI
2256 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2258 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2259 dllKernel
.GetSymbol(GetLongPathName
);
2262 // note that kernel32.dll can be unloaded, it stays in memory
2263 // anyhow as all Win32 programs link to it and so it's safe to call
2264 // GetLongPathName() even after unloading it
2268 if ( s_pfnGetLongPathName
)
2270 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2273 if ( (*s_pfnGetLongPathName
)
2276 wxStringBuffer(pathOut
, dwSize
),
2284 #endif // wxUSE_DYNLIB_CLASS
2286 // The OS didn't support GetLongPathName, or some other error.
2287 // We need to call FindFirstFile on each component in turn.
2289 WIN32_FIND_DATA findFileData
;
2293 pathOut
= GetVolume() +
2294 GetVolumeSeparator(wxPATH_DOS
) +
2295 GetPathSeparator(wxPATH_DOS
);
2297 pathOut
= wxEmptyString
;
2299 wxArrayString dirs
= GetDirs();
2300 dirs
.Add(GetFullName());
2304 size_t count
= dirs
.GetCount();
2305 for ( size_t i
= 0; i
< count
; i
++ )
2307 const wxString
& dir
= dirs
[i
];
2309 // We're using pathOut to collect the long-name path, but using a
2310 // temporary for appending the last path component which may be
2312 tmpPath
= pathOut
+ dir
;
2314 // We must not process "." or ".." here as they would be (unexpectedly)
2315 // replaced by the corresponding directory names so just leave them
2318 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2319 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2320 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2322 tmpPath
+= wxFILE_SEP_PATH
;
2327 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2328 if (hFind
== INVALID_HANDLE_VALUE
)
2330 // Error: most likely reason is that path doesn't exist, so
2331 // append any unprocessed parts and return
2332 for ( i
+= 1; i
< count
; i
++ )
2333 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2338 pathOut
+= findFileData
.cFileName
;
2339 if ( (i
< (count
-1)) )
2340 pathOut
+= wxFILE_SEP_PATH
;
2346 #endif // Win32/!Win32
2351 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2353 if (format
== wxPATH_NATIVE
)
2355 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2356 format
= wxPATH_DOS
;
2357 #elif defined(__VMS)
2358 format
= wxPATH_VMS
;
2360 format
= wxPATH_UNIX
;
2366 #ifdef wxHAS_FILESYSTEM_VOLUMES
2369 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2371 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2373 wxString
vol(drive
);
2374 vol
+= wxFILE_SEP_DSK
;
2375 if ( flags
& wxPATH_GET_SEPARATOR
)
2376 vol
+= wxFILE_SEP_PATH
;
2381 #endif // wxHAS_FILESYSTEM_VOLUMES
2383 // ----------------------------------------------------------------------------
2384 // path splitting function
2385 // ----------------------------------------------------------------------------
2389 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2390 wxString
*pstrVolume
,
2392 wxPathFormat format
)
2394 format
= GetFormat(format
);
2396 wxString fullpath
= fullpathWithVolume
;
2398 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2400 // special Windows unique volume names hack: transform
2401 // \\?\Volume{guid}\path into Volume{guid}:path
2402 // note: this check must be done before the check for UNC path
2404 // we know the last backslash from the unique volume name is located
2405 // there from IsMSWUniqueVolumeNamePath
2406 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2408 // paths starting with a unique volume name should always be absolute
2409 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2411 // remove the leading "\\?\" part
2412 fullpath
.erase(0, 4);
2414 else if ( IsUNCPath(fullpath
, format
) )
2416 // special Windows UNC paths hack: transform \\share\path into share:path
2418 fullpath
.erase(0, 2);
2420 size_t posFirstSlash
=
2421 fullpath
.find_first_of(GetPathTerminators(format
));
2422 if ( posFirstSlash
!= wxString::npos
)
2424 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2426 // UNC paths are always absolute, right? (FIXME)
2427 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2431 // We separate the volume here
2432 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2434 wxString sepVol
= GetVolumeSeparator(format
);
2436 // we have to exclude the case of a colon in the very beginning of the
2437 // string as it can't be a volume separator (nor can this be a valid
2438 // DOS file name at all but we'll leave dealing with this to our caller)
2439 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2440 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2444 *pstrVolume
= fullpath
.Left(posFirstColon
);
2447 // remove the volume name and the separator from the full path
2448 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2453 *pstrPath
= fullpath
;
2457 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2458 wxString
*pstrVolume
,
2463 wxPathFormat format
)
2465 format
= GetFormat(format
);
2468 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2470 // find the positions of the last dot and last path separator in the path
2471 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2472 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2474 // check whether this dot occurs at the very beginning of a path component
2475 if ( (posLastDot
!= wxString::npos
) &&
2477 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2478 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2480 // dot may be (and commonly -- at least under Unix -- is) the first
2481 // character of the filename, don't treat the entire filename as
2482 // extension in this case
2483 posLastDot
= wxString::npos
;
2486 // if we do have a dot and a slash, check that the dot is in the name part
2487 if ( (posLastDot
!= wxString::npos
) &&
2488 (posLastSlash
!= wxString::npos
) &&
2489 (posLastDot
< posLastSlash
) )
2491 // the dot is part of the path, not the start of the extension
2492 posLastDot
= wxString::npos
;
2495 // now fill in the variables provided by user
2498 if ( posLastSlash
== wxString::npos
)
2505 // take everything up to the path separator but take care to make
2506 // the path equal to something like '/', not empty, for the files
2507 // immediately under root directory
2508 size_t len
= posLastSlash
;
2510 // this rule does not apply to mac since we do not start with colons (sep)
2511 // except for relative paths
2512 if ( !len
&& format
!= wxPATH_MAC
)
2515 *pstrPath
= fullpath
.Left(len
);
2517 // special VMS hack: remove the initial bracket
2518 if ( format
== wxPATH_VMS
)
2520 if ( (*pstrPath
)[0u] == wxT('[') )
2521 pstrPath
->erase(0, 1);
2528 // take all characters starting from the one after the last slash and
2529 // up to, but excluding, the last dot
2530 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2532 if ( posLastDot
== wxString::npos
)
2534 // take all until the end
2535 count
= wxString::npos
;
2537 else if ( posLastSlash
== wxString::npos
)
2541 else // have both dot and slash
2543 count
= posLastDot
- posLastSlash
- 1;
2546 *pstrName
= fullpath
.Mid(nStart
, count
);
2549 // finally deal with the extension here: we have an added complication that
2550 // extension may be empty (but present) as in "foo." where trailing dot
2551 // indicates the empty extension at the end -- and hence we must remember
2552 // that we have it independently of pstrExt
2553 if ( posLastDot
== wxString::npos
)
2563 // take everything after the dot
2565 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2572 void wxFileName::SplitPath(const wxString
& fullpath
,
2576 wxPathFormat format
)
2579 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2583 path
->Prepend(wxGetVolumeString(volume
, format
));
2588 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2590 wxFileName
fn(fullpath
);
2592 return fn
.GetFullPath();
2595 // ----------------------------------------------------------------------------
2597 // ----------------------------------------------------------------------------
2601 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2602 const wxDateTime
*dtMod
,
2603 const wxDateTime
*dtCreate
) const
2605 #if defined(__WIN32__)
2606 FILETIME ftAccess
, ftCreate
, ftWrite
;
2609 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2611 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2613 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2619 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2621 wxLogError(_("Setting directory access times is not supported "
2622 "under this OS version"));
2627 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2631 path
= GetFullPath();
2635 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2638 if ( ::SetFileTime(fh
,
2639 dtCreate
? &ftCreate
: NULL
,
2640 dtAccess
? &ftAccess
: NULL
,
2641 dtMod
? &ftWrite
: NULL
) )
2646 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2647 wxUnusedVar(dtCreate
);
2649 if ( !dtAccess
&& !dtMod
)
2651 // can't modify the creation time anyhow, don't try
2655 // if dtAccess or dtMod is not specified, use the other one (which must be
2656 // non NULL because of the test above) for both times
2658 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2659 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2660 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2664 #else // other platform
2665 wxUnusedVar(dtAccess
);
2667 wxUnusedVar(dtCreate
);
2670 wxLogSysError(_("Failed to modify file times for '%s'"),
2671 GetFullPath().c_str());
2676 bool wxFileName::Touch() const
2678 #if defined(__UNIX_LIKE__)
2679 // under Unix touching file is simple: just pass NULL to utime()
2680 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2685 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2688 #else // other platform
2689 wxDateTime dtNow
= wxDateTime::Now();
2691 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2695 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2697 wxDateTime
*dtCreate
) const
2699 #if defined(__WIN32__)
2700 // we must use different methods for the files and directories under
2701 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2702 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2705 FILETIME ftAccess
, ftCreate
, ftWrite
;
2708 // implemented in msw/dir.cpp
2709 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2710 FILETIME
*, FILETIME
*, FILETIME
*);
2712 // we should pass the path without the trailing separator to
2713 // wxGetDirectoryTimes()
2714 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2715 &ftAccess
, &ftCreate
, &ftWrite
);
2719 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2722 ok
= ::GetFileTime(fh
,
2723 dtCreate
? &ftCreate
: NULL
,
2724 dtAccess
? &ftAccess
: NULL
,
2725 dtMod
? &ftWrite
: NULL
) != 0;
2736 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2738 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2740 ConvertFileTimeToWx(dtMod
, ftWrite
);
2744 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2745 // no need to test for IsDir() here
2747 if ( StatAny(stBuf
, *this) )
2749 // Android defines st_*time fields as unsigned long, but time_t as long,
2750 // hence the static_casts.
2752 dtAccess
->Set(static_cast<time_t>(stBuf
.st_atime
));
2754 dtMod
->Set(static_cast<time_t>(stBuf
.st_mtime
));
2756 dtCreate
->Set(static_cast<time_t>(stBuf
.st_ctime
));
2760 #else // other platform
2761 wxUnusedVar(dtAccess
);
2763 wxUnusedVar(dtCreate
);
2766 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2767 GetFullPath().c_str());
2772 #endif // wxUSE_DATETIME
2775 // ----------------------------------------------------------------------------
2776 // file size functions
2777 // ----------------------------------------------------------------------------
2782 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2784 if (!wxFileExists(filename
))
2785 return wxInvalidSize
;
2787 #if defined(__WIN32__)
2788 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2790 return wxInvalidSize
;
2792 DWORD lpFileSizeHigh
;
2793 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2794 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2795 return wxInvalidSize
;
2797 return wxULongLong(lpFileSizeHigh
, ret
);
2798 #else // ! __WIN32__
2800 if (wxStat( filename
, &st
) != 0)
2801 return wxInvalidSize
;
2802 return wxULongLong(st
.st_size
);
2807 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2808 const wxString
&nullsize
,
2810 wxSizeConvention conv
)
2812 // deal with trivial case first
2813 if ( bs
== 0 || bs
== wxInvalidSize
)
2816 // depending on the convention used the multiplier may be either 1000 or
2817 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2818 double multiplier
= 1024.;
2823 case wxSIZE_CONV_TRADITIONAL
:
2824 // nothing to do, this corresponds to the default values of both
2825 // the multiplier and infix string
2828 case wxSIZE_CONV_IEC
:
2832 case wxSIZE_CONV_SI
:
2837 const double kiloByteSize
= multiplier
;
2838 const double megaByteSize
= multiplier
* kiloByteSize
;
2839 const double gigaByteSize
= multiplier
* megaByteSize
;
2840 const double teraByteSize
= multiplier
* gigaByteSize
;
2842 const double bytesize
= bs
.ToDouble();
2845 if ( bytesize
< kiloByteSize
)
2846 result
.Printf("%s B", bs
.ToString());
2847 else if ( bytesize
< megaByteSize
)
2848 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2849 else if (bytesize
< gigaByteSize
)
2850 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2851 else if (bytesize
< teraByteSize
)
2852 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2854 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2859 wxULongLong
wxFileName::GetSize() const
2861 return GetSize(GetFullPath());
2864 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2866 wxSizeConvention conv
) const
2868 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2871 #endif // wxUSE_LONGLONG
2873 // ----------------------------------------------------------------------------
2874 // Mac-specific functions
2875 // ----------------------------------------------------------------------------
2877 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2882 class MacDefaultExtensionRecord
2885 MacDefaultExtensionRecord()
2891 // default copy ctor, assignment operator and dtor are ok
2893 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2897 m_creator
= creator
;
2905 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2907 bool gMacDefaultExtensionsInited
= false;
2909 #include "wx/arrimpl.cpp"
2911 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2913 MacDefaultExtensionArray gMacDefaultExtensions
;
2915 // load the default extensions
2916 const MacDefaultExtensionRecord gDefaults
[] =
2918 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2919 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2920 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2923 void MacEnsureDefaultExtensionsLoaded()
2925 if ( !gMacDefaultExtensionsInited
)
2927 // we could load the pc exchange prefs here too
2928 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2930 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2932 gMacDefaultExtensionsInited
= true;
2936 } // anonymous namespace
2938 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2941 FSCatalogInfo catInfo
;
2944 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2946 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2948 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2949 finfo
->fileType
= type
;
2950 finfo
->fileCreator
= creator
;
2951 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2958 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2961 FSCatalogInfo catInfo
;
2964 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2966 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2968 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2969 *type
= finfo
->fileType
;
2970 *creator
= finfo
->fileCreator
;
2977 bool wxFileName::MacSetDefaultTypeAndCreator()
2979 wxUint32 type
, creator
;
2980 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2983 return MacSetTypeAndCreator( type
, creator
) ;
2988 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2990 MacEnsureDefaultExtensionsLoaded() ;
2991 wxString extl
= ext
.Lower() ;
2992 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2994 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2996 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2997 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
3004 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
3006 MacEnsureDefaultExtensionsLoaded();
3007 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
3008 gMacDefaultExtensions
.Add( rec
);
3011 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON