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 "wx/msw/missing.h"
106 #if defined(__WXMAC__)
107 #include "wx/osx/private.h" // includes mac headers
110 // utime() is POSIX so should normally be available on all Unices
112 #include <sys/types.h>
114 #include <sys/stat.h>
124 #include <sys/utime.h>
125 #include <sys/stat.h>
136 #define MAX_PATH _MAX_PATH
140 #define S_ISREG(mode) ((mode) & S_IFREG)
143 #define S_ISDIR(mode) ((mode) & S_IFDIR)
147 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
148 #endif // wxUSE_LONGLONG
153 // ----------------------------------------------------------------------------
155 // ----------------------------------------------------------------------------
157 // small helper class which opens and closes the file - we use it just to get
158 // a file handle for the given file name to pass it to some Win32 API function
159 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
170 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
172 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
173 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
174 // be changed when we open it because this class is used for setting
175 // access time (see #10567)
176 m_hFile
= ::CreateFile
178 filename
.t_str(), // name
179 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
180 : FILE_WRITE_ATTRIBUTES
,
181 FILE_SHARE_READ
| // sharing mode
182 FILE_SHARE_WRITE
, // (allow everything)
183 NULL
, // no secutity attr
184 OPEN_EXISTING
, // creation disposition
186 NULL
// no template file
189 if ( m_hFile
== INVALID_HANDLE_VALUE
)
191 if ( mode
== ReadAttr
)
193 wxLogSysError(_("Failed to open '%s' for reading"),
198 wxLogSysError(_("Failed to open '%s' for writing"),
206 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
208 if ( !::CloseHandle(m_hFile
) )
210 wxLogSysError(_("Failed to close file handle"));
215 // return true only if the file could be opened successfully
216 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
219 operator HANDLE() const { return m_hFile
; }
227 // ----------------------------------------------------------------------------
229 // ----------------------------------------------------------------------------
231 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
233 // convert between wxDateTime and FILETIME which is a 64-bit value representing
234 // the number of 100-nanosecond intervals since January 1, 1601.
236 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
238 FILETIME ftcopy
= ft
;
240 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
242 wxLogLastError(wxT("FileTimeToLocalFileTime"));
246 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
248 wxLogLastError(wxT("FileTimeToSystemTime"));
251 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
252 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
255 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
258 st
.wDay
= dt
.GetDay();
259 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
260 st
.wYear
= (WORD
)dt
.GetYear();
261 st
.wHour
= dt
.GetHour();
262 st
.wMinute
= dt
.GetMinute();
263 st
.wSecond
= dt
.GetSecond();
264 st
.wMilliseconds
= dt
.GetMillisecond();
267 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
269 wxLogLastError(wxT("SystemTimeToFileTime"));
272 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
274 wxLogLastError(wxT("LocalFileTimeToFileTime"));
278 #endif // wxUSE_DATETIME && __WIN32__
280 // return a string with the volume par
281 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
285 if ( !volume
.empty() )
287 format
= wxFileName::GetFormat(format
);
289 // Special Windows UNC paths hack, part 2: undo what we did in
290 // SplitPath() and make an UNC path if we have a drive which is not a
291 // single letter (hopefully the network shares can't be one letter only
292 // although I didn't find any authoritative docs on this)
293 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
295 // We also have to check for Windows unique volume names here and
296 // return it with '\\?\' prepended to it
297 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume
+ "\\",
300 path
<< "\\\\?\\" << volume
;
304 // it must be a UNC path
305 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
308 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
310 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
318 // return true if the character is a DOS path separator i.e. either a slash or
320 inline bool IsDOSPathSep(wxUniChar ch
)
322 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
325 // return true if the format used is the DOS/Windows one and the string looks
327 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
329 return format
== wxPATH_DOS
&&
330 path
.length() >= 4 && // "\\a" can't be a UNC path
331 IsDOSPathSep(path
[0u]) &&
332 IsDOSPathSep(path
[1u]) &&
333 !IsDOSPathSep(path
[2u]);
338 // Under Unix-ish systems (basically everything except Windows) we may work
339 // either with the file itself or its target if it's a symbolic link and we
340 // should dereference it, as determined by wxFileName::ShouldFollowLink() and
341 // the absence of the wxFILE_EXISTS_NO_FOLLOW flag. StatAny() can be used to
342 // stat the appropriate file with an extra twist that it also works when there
343 // is no wxFileName object at all, as is the case in static methods.
345 // Private implementation, don't call directly, use one of the overloads below.
346 bool DoStatAny(wxStructStat
& st
, wxString path
, bool dereference
)
348 // We need to remove any trailing slashes from the path because they could
349 // interfere with the symlink following decision: even if we use lstat(),
350 // it would still follow the symlink if we pass it a path with a slash at
351 // the end because the symlink resolution would happen while following the
352 // path and not for the last path element itself.
354 while ( wxEndsWithPathSeparator(path
) )
356 const size_t posLast
= path
.length() - 1;
359 // Don't turn "/" into empty string.
366 int ret
= dereference
? wxStat(path
, &st
) : wxLstat(path
, &st
);
370 // Overloads to use for a case when we don't have wxFileName object and when we
373 bool StatAny(wxStructStat
& st
, const wxString
& path
, int flags
)
375 return DoStatAny(st
, path
, !(flags
& wxFILE_EXISTS_NO_FOLLOW
));
379 bool StatAny(wxStructStat
& st
, const wxFileName
& fn
)
381 return DoStatAny(st
, fn
.GetFullPath(), fn
.ShouldFollowLink());
386 // ----------------------------------------------------------------------------
388 // ----------------------------------------------------------------------------
390 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
391 static const size_t wxMSWUniqueVolumePrefixLength
= 49;
393 } // anonymous namespace
395 // ============================================================================
397 // ============================================================================
399 // ----------------------------------------------------------------------------
400 // wxFileName construction
401 // ----------------------------------------------------------------------------
403 void wxFileName::Assign( const wxFileName
&filepath
)
405 m_volume
= filepath
.GetVolume();
406 m_dirs
= filepath
.GetDirs();
407 m_name
= filepath
.GetName();
408 m_ext
= filepath
.GetExt();
409 m_relative
= filepath
.m_relative
;
410 m_hasExt
= filepath
.m_hasExt
;
411 m_dontFollowLinks
= filepath
.m_dontFollowLinks
;
414 void wxFileName::Assign(const wxString
& volume
,
415 const wxString
& path
,
416 const wxString
& name
,
421 // we should ignore paths which look like UNC shares because we already
422 // have the volume here and the UNC notation (\\server\path) is only valid
423 // for paths which don't start with a volume, so prevent SetPath() from
424 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
426 // note also that this is a rather ugly way to do what we want (passing
427 // some kind of flag telling to ignore UNC paths to SetPath() would be
428 // better) but this is the safest thing to do to avoid breaking backwards
429 // compatibility in 2.8
430 if ( IsUNCPath(path
, format
) )
432 // remove one of the 2 leading backslashes to ensure that it's not
433 // recognized as an UNC path by SetPath()
434 wxString
pathNonUNC(path
, 1, wxString::npos
);
435 SetPath(pathNonUNC
, format
);
437 else // no UNC complications
439 SetPath(path
, format
);
449 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
453 if ( pathOrig
.empty() )
461 format
= GetFormat( format
);
463 // 0) deal with possible volume part first
466 SplitVolume(pathOrig
, &volume
, &path
, format
);
467 if ( !volume
.empty() )
474 // 1) Determine if the path is relative or absolute.
478 // we had only the volume
482 wxChar leadingChar
= path
[0u];
487 m_relative
= leadingChar
== wxT(':');
489 // We then remove a leading ":". The reason is in our
490 // storage form for relative paths:
491 // ":dir:file.txt" actually means "./dir/file.txt" in
492 // DOS notation and should get stored as
493 // (relative) (dir) (file.txt)
494 // "::dir:file.txt" actually means "../dir/file.txt"
495 // stored as (relative) (..) (dir) (file.txt)
496 // This is important only for the Mac as an empty dir
497 // actually means <UP>, whereas under DOS, double
498 // slashes can be ignored: "\\\\" is the same as "\\".
504 // TODO: what is the relative path format here?
509 wxFAIL_MSG( wxT("Unknown path format") );
510 // !! Fall through !!
513 m_relative
= leadingChar
!= wxT('/');
517 m_relative
= !IsPathSeparator(leadingChar
, format
);
522 // 2) Break up the path into its members. If the original path
523 // was just "/" or "\\", m_dirs will be empty. We know from
524 // the m_relative field, if this means "nothing" or "root dir".
526 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
528 while ( tn
.HasMoreTokens() )
530 wxString token
= tn
.GetNextToken();
532 // Remove empty token under DOS and Unix, interpret them
536 if (format
== wxPATH_MAC
)
537 m_dirs
.Add( wxT("..") );
547 void wxFileName::Assign(const wxString
& fullpath
,
550 wxString volume
, path
, name
, ext
;
552 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
554 Assign(volume
, path
, name
, ext
, hasExt
, format
);
557 void wxFileName::Assign(const wxString
& fullpathOrig
,
558 const wxString
& fullname
,
561 // always recognize fullpath as directory, even if it doesn't end with a
563 wxString fullpath
= fullpathOrig
;
564 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
566 fullpath
+= GetPathSeparator(format
);
569 wxString volume
, path
, name
, ext
;
572 // do some consistency checks: the name should be really just the filename
573 // and the path should be really just a path
574 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
576 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
578 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
579 wxT("the file name shouldn't contain the path") );
581 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
584 // This test makes no sense on an OpenVMS system.
585 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
586 wxT("the path shouldn't contain file name nor extension") );
588 Assign(volume
, path
, name
, ext
, hasExt
, format
);
591 void wxFileName::Assign(const wxString
& pathOrig
,
592 const wxString
& name
,
598 SplitVolume(pathOrig
, &volume
, &path
, format
);
600 Assign(volume
, path
, name
, ext
, format
);
603 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
605 Assign(dir
, wxEmptyString
, format
);
608 void wxFileName::Clear()
614 m_ext
= wxEmptyString
;
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
1706 // The following lines are necessary under WinCE
1707 // #include "wx/msw/private.h"
1708 // #include <ole2.h>
1710 #if defined(__WXWINCE__)
1711 #include <shlguid.h>
1714 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1715 wxString
& targetFilename
,
1716 wxString
* arguments
) const
1718 wxString path
, file
, ext
;
1719 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1723 bool success
= false;
1725 // Assume it's not a shortcut if it doesn't end with lnk
1726 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1729 // create a ShellLink object
1730 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1731 IID_IShellLink
, (LPVOID
*) &psl
);
1733 if (SUCCEEDED(hres
))
1736 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1737 if (SUCCEEDED(hres
))
1739 WCHAR wsz
[MAX_PATH
];
1741 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1744 hres
= ppf
->Load(wsz
, 0);
1747 if (SUCCEEDED(hres
))
1750 // Wrong prototype in early versions
1751 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1752 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1754 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1756 targetFilename
= wxString(buf
);
1757 success
= (shortcutPath
!= targetFilename
);
1759 psl
->GetArguments(buf
, 2048);
1761 if (!args
.empty() && arguments
)
1773 #endif // __WIN32__ && !__WXWINCE__
1776 // ----------------------------------------------------------------------------
1777 // absolute/relative paths
1778 // ----------------------------------------------------------------------------
1780 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1782 // unix paths beginning with ~ are reported as being absolute
1783 if ( format
== wxPATH_UNIX
)
1785 if ( !m_dirs
.IsEmpty() )
1787 wxString dir
= m_dirs
[0u];
1789 if (!dir
.empty() && dir
[0u] == wxT('~'))
1794 // if our path doesn't start with a path separator, it's not an absolute
1799 if ( !GetVolumeSeparator(format
).empty() )
1801 // this format has volumes and an absolute path must have one, it's not
1802 // enough to have the full path to be an absolute file under Windows
1803 if ( GetVolume().empty() )
1810 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1812 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1814 // get cwd only once - small time saving
1815 wxString cwd
= wxGetCwd();
1816 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1817 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1819 bool withCase
= IsCaseSensitive(format
);
1821 // we can't do anything if the files live on different volumes
1822 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1828 // same drive, so we don't need our volume
1831 // remove common directories starting at the top
1832 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1833 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1836 fnBase
.m_dirs
.RemoveAt(0);
1839 // add as many ".." as needed
1840 size_t count
= fnBase
.m_dirs
.GetCount();
1841 for ( size_t i
= 0; i
< count
; i
++ )
1843 m_dirs
.Insert(wxT(".."), 0u);
1846 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1848 // a directory made relative with respect to itself is '.' under Unix
1849 // and DOS, by definition (but we don't have to insert "./" for the
1851 if ( m_dirs
.IsEmpty() && IsDir() )
1853 m_dirs
.Add(wxT('.'));
1863 // ----------------------------------------------------------------------------
1864 // filename kind tests
1865 // ----------------------------------------------------------------------------
1867 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1869 wxFileName fn1
= *this,
1872 // get cwd only once - small time saving
1873 wxString cwd
= wxGetCwd();
1874 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1875 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1877 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1880 #if defined(__UNIX__)
1881 wxStructStat st1
, st2
;
1882 if ( StatAny(st1
, fn1
) && StatAny(st2
, fn2
) )
1884 if ( st1
.st_ino
== st2
.st_ino
&& st1
.st_dev
== st2
.st_dev
)
1887 //else: It's not an error if one or both files don't exist.
1888 #endif // defined __UNIX__
1894 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1896 // only Unix filenames are truly case-sensitive
1897 return GetFormat(format
) == wxPATH_UNIX
;
1901 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1903 // Inits to forbidden characters that are common to (almost) all platforms.
1904 wxString strForbiddenChars
= wxT("*?");
1906 // If asserts, wxPathFormat has been changed. In case of a new path format
1907 // addition, the following code might have to be updated.
1908 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1909 switch ( GetFormat(format
) )
1912 wxFAIL_MSG( wxT("Unknown path format") );
1913 // !! Fall through !!
1919 // On a Mac even names with * and ? are allowed (Tested with OS
1920 // 9.2.1 and OS X 10.2.5)
1921 strForbiddenChars
= wxEmptyString
;
1925 strForbiddenChars
+= wxT("\\/:\"<>|");
1932 return strForbiddenChars
;
1936 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1939 return wxEmptyString
;
1943 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1944 (GetFormat(format
) == wxPATH_VMS
) )
1946 sepVol
= wxFILE_SEP_DSK
;
1955 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1958 switch ( GetFormat(format
) )
1961 // accept both as native APIs do but put the native one first as
1962 // this is the one we use in GetFullPath()
1963 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1967 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1971 seps
= wxFILE_SEP_PATH_UNIX
;
1975 seps
= wxFILE_SEP_PATH_MAC
;
1979 seps
= wxFILE_SEP_PATH_VMS
;
1987 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1989 format
= GetFormat(format
);
1991 // under VMS the end of the path is ']', not the path separator used to
1992 // separate the components
1993 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1997 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1999 // wxString::Find() doesn't work as expected with NUL - it will always find
2000 // it, so test for it separately
2001 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
2006 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
2008 // return true if the format used is the DOS/Windows one and the string begins
2009 // with a Windows unique volume name ("\\?\Volume{guid}\")
2010 return format
== wxPATH_DOS
&&
2011 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
2012 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
2013 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
2016 // ----------------------------------------------------------------------------
2017 // path components manipulation
2018 // ----------------------------------------------------------------------------
2020 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
2024 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
2029 const size_t len
= dir
.length();
2030 for ( size_t n
= 0; n
< len
; n
++ )
2032 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
2034 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
2043 void wxFileName::AppendDir( const wxString
& dir
)
2045 if ( IsValidDirComponent(dir
) )
2049 void wxFileName::PrependDir( const wxString
& dir
)
2054 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
2056 if ( IsValidDirComponent(dir
) )
2057 m_dirs
.Insert(dir
, before
);
2060 void wxFileName::RemoveDir(size_t pos
)
2062 m_dirs
.RemoveAt(pos
);
2065 // ----------------------------------------------------------------------------
2067 // ----------------------------------------------------------------------------
2069 void wxFileName::SetFullName(const wxString
& fullname
)
2071 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
2072 &m_name
, &m_ext
, &m_hasExt
);
2075 wxString
wxFileName::GetFullName() const
2077 wxString fullname
= m_name
;
2080 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
2086 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
2088 format
= GetFormat( format
);
2092 // return the volume with the path as well if requested
2093 if ( flags
& wxPATH_GET_VOLUME
)
2095 fullpath
+= wxGetVolumeString(GetVolume(), format
);
2098 // the leading character
2103 fullpath
+= wxFILE_SEP_PATH_MAC
;
2108 fullpath
+= wxFILE_SEP_PATH_DOS
;
2112 wxFAIL_MSG( wxT("Unknown path format") );
2118 fullpath
+= wxFILE_SEP_PATH_UNIX
;
2123 // no leading character here but use this place to unset
2124 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2125 // as, if I understand correctly, there should never be a dot
2126 // before the closing bracket
2127 flags
&= ~wxPATH_GET_SEPARATOR
;
2130 if ( m_dirs
.empty() )
2132 // there is nothing more
2136 // then concatenate all the path components using the path separator
2137 if ( format
== wxPATH_VMS
)
2139 fullpath
+= wxT('[');
2142 const size_t dirCount
= m_dirs
.GetCount();
2143 for ( size_t i
= 0; i
< dirCount
; i
++ )
2148 if ( m_dirs
[i
] == wxT(".") )
2150 // skip appending ':', this shouldn't be done in this
2151 // case as "::" is interpreted as ".." under Unix
2155 // convert back from ".." to nothing
2156 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2157 fullpath
+= m_dirs
[i
];
2161 wxFAIL_MSG( wxT("Unexpected path format") );
2162 // still fall through
2166 fullpath
+= m_dirs
[i
];
2170 // TODO: What to do with ".." under VMS
2172 // convert back from ".." to nothing
2173 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2174 fullpath
+= m_dirs
[i
];
2178 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2179 fullpath
+= GetPathSeparator(format
);
2182 if ( format
== wxPATH_VMS
)
2184 fullpath
+= wxT(']');
2190 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2192 // we already have a function to get the path
2193 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2196 // now just add the file name and extension to it
2197 fullpath
+= GetFullName();
2202 // Return the short form of the path (returns identity on non-Windows platforms)
2203 wxString
wxFileName::GetShortPath() const
2205 wxString
path(GetFullPath());
2207 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2208 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2212 if ( ::GetShortPathName
2215 wxStringBuffer(pathOut
, sz
),
2227 // Return the long form of the path (returns identity on non-Windows platforms)
2228 wxString
wxFileName::GetLongPath() const
2231 path
= GetFullPath();
2233 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2235 #if wxUSE_DYNLIB_CLASS
2236 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2238 // this is MT-safe as in the worst case we're going to resolve the function
2239 // twice -- but as the result is the same in both threads, it's ok
2240 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2241 if ( !s_pfnGetLongPathName
)
2243 static bool s_triedToLoad
= false;
2245 if ( !s_triedToLoad
)
2247 s_triedToLoad
= true;
2249 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2251 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2256 #endif // Unicode/ANSI
2258 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2260 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2261 dllKernel
.GetSymbol(GetLongPathName
);
2264 // note that kernel32.dll can be unloaded, it stays in memory
2265 // anyhow as all Win32 programs link to it and so it's safe to call
2266 // GetLongPathName() even after unloading it
2270 if ( s_pfnGetLongPathName
)
2272 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2275 if ( (*s_pfnGetLongPathName
)
2278 wxStringBuffer(pathOut
, dwSize
),
2286 #endif // wxUSE_DYNLIB_CLASS
2288 // The OS didn't support GetLongPathName, or some other error.
2289 // We need to call FindFirstFile on each component in turn.
2291 WIN32_FIND_DATA findFileData
;
2295 pathOut
= GetVolume() +
2296 GetVolumeSeparator(wxPATH_DOS
) +
2297 GetPathSeparator(wxPATH_DOS
);
2299 pathOut
= wxEmptyString
;
2301 wxArrayString dirs
= GetDirs();
2302 dirs
.Add(GetFullName());
2306 size_t count
= dirs
.GetCount();
2307 for ( size_t i
= 0; i
< count
; i
++ )
2309 const wxString
& dir
= dirs
[i
];
2311 // We're using pathOut to collect the long-name path, but using a
2312 // temporary for appending the last path component which may be
2314 tmpPath
= pathOut
+ dir
;
2316 // We must not process "." or ".." here as they would be (unexpectedly)
2317 // replaced by the corresponding directory names so just leave them
2320 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2321 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2322 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2324 tmpPath
+= wxFILE_SEP_PATH
;
2329 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2330 if (hFind
== INVALID_HANDLE_VALUE
)
2332 // Error: most likely reason is that path doesn't exist, so
2333 // append any unprocessed parts and return
2334 for ( i
+= 1; i
< count
; i
++ )
2335 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2340 pathOut
+= findFileData
.cFileName
;
2341 if ( (i
< (count
-1)) )
2342 pathOut
+= wxFILE_SEP_PATH
;
2348 #endif // Win32/!Win32
2353 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2355 if (format
== wxPATH_NATIVE
)
2357 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2358 format
= wxPATH_DOS
;
2359 #elif defined(__VMS)
2360 format
= wxPATH_VMS
;
2362 format
= wxPATH_UNIX
;
2368 #ifdef wxHAS_FILESYSTEM_VOLUMES
2371 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2373 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2375 wxString
vol(drive
);
2376 vol
+= wxFILE_SEP_DSK
;
2377 if ( flags
& wxPATH_GET_SEPARATOR
)
2378 vol
+= wxFILE_SEP_PATH
;
2383 #endif // wxHAS_FILESYSTEM_VOLUMES
2385 // ----------------------------------------------------------------------------
2386 // path splitting function
2387 // ----------------------------------------------------------------------------
2391 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2392 wxString
*pstrVolume
,
2394 wxPathFormat format
)
2396 format
= GetFormat(format
);
2398 wxString fullpath
= fullpathWithVolume
;
2400 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2402 // special Windows unique volume names hack: transform
2403 // \\?\Volume{guid}\path into Volume{guid}:path
2404 // note: this check must be done before the check for UNC path
2406 // we know the last backslash from the unique volume name is located
2407 // there from IsMSWUniqueVolumeNamePath
2408 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2410 // paths starting with a unique volume name should always be absolute
2411 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2413 // remove the leading "\\?\" part
2414 fullpath
.erase(0, 4);
2416 else if ( IsUNCPath(fullpath
, format
) )
2418 // special Windows UNC paths hack: transform \\share\path into share:path
2420 fullpath
.erase(0, 2);
2422 size_t posFirstSlash
=
2423 fullpath
.find_first_of(GetPathTerminators(format
));
2424 if ( posFirstSlash
!= wxString::npos
)
2426 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2428 // UNC paths are always absolute, right? (FIXME)
2429 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2433 // We separate the volume here
2434 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2436 wxString sepVol
= GetVolumeSeparator(format
);
2438 // we have to exclude the case of a colon in the very beginning of the
2439 // string as it can't be a volume separator (nor can this be a valid
2440 // DOS file name at all but we'll leave dealing with this to our caller)
2441 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2442 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2446 *pstrVolume
= fullpath
.Left(posFirstColon
);
2449 // remove the volume name and the separator from the full path
2450 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2455 *pstrPath
= fullpath
;
2459 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2460 wxString
*pstrVolume
,
2465 wxPathFormat format
)
2467 format
= GetFormat(format
);
2470 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2472 // find the positions of the last dot and last path separator in the path
2473 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2474 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2476 // check whether this dot occurs at the very beginning of a path component
2477 if ( (posLastDot
!= wxString::npos
) &&
2479 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2480 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2482 // dot may be (and commonly -- at least under Unix -- is) the first
2483 // character of the filename, don't treat the entire filename as
2484 // extension in this case
2485 posLastDot
= wxString::npos
;
2488 // if we do have a dot and a slash, check that the dot is in the name part
2489 if ( (posLastDot
!= wxString::npos
) &&
2490 (posLastSlash
!= wxString::npos
) &&
2491 (posLastDot
< posLastSlash
) )
2493 // the dot is part of the path, not the start of the extension
2494 posLastDot
= wxString::npos
;
2497 // now fill in the variables provided by user
2500 if ( posLastSlash
== wxString::npos
)
2507 // take everything up to the path separator but take care to make
2508 // the path equal to something like '/', not empty, for the files
2509 // immediately under root directory
2510 size_t len
= posLastSlash
;
2512 // this rule does not apply to mac since we do not start with colons (sep)
2513 // except for relative paths
2514 if ( !len
&& format
!= wxPATH_MAC
)
2517 *pstrPath
= fullpath
.Left(len
);
2519 // special VMS hack: remove the initial bracket
2520 if ( format
== wxPATH_VMS
)
2522 if ( (*pstrPath
)[0u] == wxT('[') )
2523 pstrPath
->erase(0, 1);
2530 // take all characters starting from the one after the last slash and
2531 // up to, but excluding, the last dot
2532 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2534 if ( posLastDot
== wxString::npos
)
2536 // take all until the end
2537 count
= wxString::npos
;
2539 else if ( posLastSlash
== wxString::npos
)
2543 else // have both dot and slash
2545 count
= posLastDot
- posLastSlash
- 1;
2548 *pstrName
= fullpath
.Mid(nStart
, count
);
2551 // finally deal with the extension here: we have an added complication that
2552 // extension may be empty (but present) as in "foo." where trailing dot
2553 // indicates the empty extension at the end -- and hence we must remember
2554 // that we have it independently of pstrExt
2555 if ( posLastDot
== wxString::npos
)
2565 // take everything after the dot
2567 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2574 void wxFileName::SplitPath(const wxString
& fullpath
,
2578 wxPathFormat format
)
2581 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2585 path
->Prepend(wxGetVolumeString(volume
, format
));
2590 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2592 wxFileName
fn(fullpath
);
2594 return fn
.GetFullPath();
2597 // ----------------------------------------------------------------------------
2599 // ----------------------------------------------------------------------------
2603 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2604 const wxDateTime
*dtMod
,
2605 const wxDateTime
*dtCreate
) const
2607 #if defined(__WIN32__)
2608 FILETIME ftAccess
, ftCreate
, ftWrite
;
2611 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2613 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2615 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2621 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2623 wxLogError(_("Setting directory access times is not supported "
2624 "under this OS version"));
2629 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2633 path
= GetFullPath();
2637 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2640 if ( ::SetFileTime(fh
,
2641 dtCreate
? &ftCreate
: NULL
,
2642 dtAccess
? &ftAccess
: NULL
,
2643 dtMod
? &ftWrite
: NULL
) )
2648 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2649 wxUnusedVar(dtCreate
);
2651 if ( !dtAccess
&& !dtMod
)
2653 // can't modify the creation time anyhow, don't try
2657 // if dtAccess or dtMod is not specified, use the other one (which must be
2658 // non NULL because of the test above) for both times
2660 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2661 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2662 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2666 #else // other platform
2667 wxUnusedVar(dtAccess
);
2669 wxUnusedVar(dtCreate
);
2672 wxLogSysError(_("Failed to modify file times for '%s'"),
2673 GetFullPath().c_str());
2678 bool wxFileName::Touch() const
2680 #if defined(__UNIX_LIKE__)
2681 // under Unix touching file is simple: just pass NULL to utime()
2682 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2687 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2690 #else // other platform
2691 wxDateTime dtNow
= wxDateTime::Now();
2693 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2697 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2699 wxDateTime
*dtCreate
) const
2701 #if defined(__WIN32__)
2702 // we must use different methods for the files and directories under
2703 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2704 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2707 FILETIME ftAccess
, ftCreate
, ftWrite
;
2710 // implemented in msw/dir.cpp
2711 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2712 FILETIME
*, FILETIME
*, FILETIME
*);
2714 // we should pass the path without the trailing separator to
2715 // wxGetDirectoryTimes()
2716 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2717 &ftAccess
, &ftCreate
, &ftWrite
);
2721 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2724 ok
= ::GetFileTime(fh
,
2725 dtCreate
? &ftCreate
: NULL
,
2726 dtAccess
? &ftAccess
: NULL
,
2727 dtMod
? &ftWrite
: NULL
) != 0;
2738 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2740 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2742 ConvertFileTimeToWx(dtMod
, ftWrite
);
2746 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2747 // no need to test for IsDir() here
2749 if ( StatAny(stBuf
, *this) )
2751 // Android defines st_*time fields as unsigned long, but time_t as long,
2752 // hence the static_casts.
2754 dtAccess
->Set(static_cast<time_t>(stBuf
.st_atime
));
2756 dtMod
->Set(static_cast<time_t>(stBuf
.st_mtime
));
2758 dtCreate
->Set(static_cast<time_t>(stBuf
.st_ctime
));
2762 #else // other platform
2763 wxUnusedVar(dtAccess
);
2765 wxUnusedVar(dtCreate
);
2768 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2769 GetFullPath().c_str());
2774 #endif // wxUSE_DATETIME
2777 // ----------------------------------------------------------------------------
2778 // file size functions
2779 // ----------------------------------------------------------------------------
2784 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2786 if (!wxFileExists(filename
))
2787 return wxInvalidSize
;
2789 #if defined(__WIN32__)
2790 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2792 return wxInvalidSize
;
2794 DWORD lpFileSizeHigh
;
2795 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2796 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2797 return wxInvalidSize
;
2799 return wxULongLong(lpFileSizeHigh
, ret
);
2800 #else // ! __WIN32__
2802 if (wxStat( filename
, &st
) != 0)
2803 return wxInvalidSize
;
2804 return wxULongLong(st
.st_size
);
2809 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2810 const wxString
&nullsize
,
2812 wxSizeConvention conv
)
2814 // deal with trivial case first
2815 if ( bs
== 0 || bs
== wxInvalidSize
)
2818 // depending on the convention used the multiplier may be either 1000 or
2819 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2820 double multiplier
= 1024.;
2825 case wxSIZE_CONV_TRADITIONAL
:
2826 // nothing to do, this corresponds to the default values of both
2827 // the multiplier and infix string
2830 case wxSIZE_CONV_IEC
:
2834 case wxSIZE_CONV_SI
:
2839 const double kiloByteSize
= multiplier
;
2840 const double megaByteSize
= multiplier
* kiloByteSize
;
2841 const double gigaByteSize
= multiplier
* megaByteSize
;
2842 const double teraByteSize
= multiplier
* gigaByteSize
;
2844 const double bytesize
= bs
.ToDouble();
2847 if ( bytesize
< kiloByteSize
)
2848 result
.Printf("%s B", bs
.ToString());
2849 else if ( bytesize
< megaByteSize
)
2850 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2851 else if (bytesize
< gigaByteSize
)
2852 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2853 else if (bytesize
< teraByteSize
)
2854 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2856 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2861 wxULongLong
wxFileName::GetSize() const
2863 return GetSize(GetFullPath());
2866 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2868 wxSizeConvention conv
) const
2870 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2873 #endif // wxUSE_LONGLONG
2875 // ----------------------------------------------------------------------------
2876 // Mac-specific functions
2877 // ----------------------------------------------------------------------------
2879 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2884 class MacDefaultExtensionRecord
2887 MacDefaultExtensionRecord()
2893 // default copy ctor, assignment operator and dtor are ok
2895 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2899 m_creator
= creator
;
2907 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2909 bool gMacDefaultExtensionsInited
= false;
2911 #include "wx/arrimpl.cpp"
2913 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2915 MacDefaultExtensionArray gMacDefaultExtensions
;
2917 // load the default extensions
2918 const MacDefaultExtensionRecord gDefaults
[] =
2920 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2921 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2922 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2925 void MacEnsureDefaultExtensionsLoaded()
2927 if ( !gMacDefaultExtensionsInited
)
2929 // we could load the pc exchange prefs here too
2930 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2932 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2934 gMacDefaultExtensionsInited
= true;
2938 } // anonymous namespace
2940 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2943 FSCatalogInfo catInfo
;
2946 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2948 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2950 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2951 finfo
->fileType
= type
;
2952 finfo
->fileCreator
= creator
;
2953 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2960 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2963 FSCatalogInfo catInfo
;
2966 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2968 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2970 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2971 *type
= finfo
->fileType
;
2972 *creator
= finfo
->fileCreator
;
2979 bool wxFileName::MacSetDefaultTypeAndCreator()
2981 wxUint32 type
, creator
;
2982 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2985 return MacSetTypeAndCreator( type
, creator
) ;
2990 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2992 MacEnsureDefaultExtensionsLoaded() ;
2993 wxString extl
= ext
.Lower() ;
2994 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2996 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2998 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2999 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
3006 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
3008 MacEnsureDefaultExtensionsLoaded();
3009 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
3010 gMacDefaultExtensions
.Add( rec
);
3013 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON