1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filename.cpp
3 // Purpose: wxFileName - encapsulates a file path
4 // Author: Robert Roebling, Vadim Zeitlin
8 // Copyright: (c) 2000 Robert Roebling
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 Here are brief descriptions of the filename formats supported by this class:
15 wxPATH_UNIX: standard Unix format, used under Darwin as well, absolute file
17 /dir1/dir2/.../dirN/filename, "." and ".." stand for the
18 current and parent directory respectively, "~" is parsed as the
19 user HOME and "~username" as the HOME of that user
21 wxPATH_DOS: DOS/Windows format, absolute file names have the form:
22 drive:\dir1\dir2\...\dirN\filename.ext where drive is a single
23 letter. "." and ".." as for Unix but no "~".
25 There are also UNC names of the form \\share\fullpath and
26 MSW unique volume names of the form \\?\Volume{GUID}\fullpath.
28 The latter provide a uniform way to access a volume regardless of
29 its current mount point, i.e. you can change a volume's mount
30 point from D: to E:, or even remove it, and still be able to
31 access it through its unique volume name. More on the subject can
32 be found in MSDN's article "Naming a Volume" that is currently at
33 http://msdn.microsoft.com/en-us/library/aa365248(VS.85).aspx.
36 wxPATH_MAC: Mac OS 8/9 only, not used any longer, absolute file
38 volume:dir1:...:dirN:filename
39 and the relative file names are either
40 :dir1:...:dirN:filename
43 (although :filename works as well).
44 Since the volume is just part of the file path, it is not
45 treated like a separate entity as it is done under DOS and
46 VMS, it is just treated as another dir.
48 wxPATH_VMS: VMS native format, absolute file names have the form
49 <device>:[dir1.dir2.dir3]file.txt
51 <device>:[000000.dir1.dir2.dir3]file.txt
53 the <device> is the physical device (i.e. disk). 000000 is the
54 root directory on the device which can be omitted.
56 Note that VMS uses different separators unlike Unix:
57 : always after the device. If the path does not contain : than
58 the default (the device of the current directory) is assumed.
59 [ start of directory specification
60 . separator between directory and subdirectory
61 ] between directory and file
64 // ============================================================================
66 // ============================================================================
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // For compilers that support precompilation, includes "wx.h".
73 #include "wx/wxprec.h"
81 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
83 #include "wx/dynarray.h"
90 #include "wx/filename.h"
91 #include "wx/private/filename.h"
92 #include "wx/tokenzr.h"
93 #include "wx/config.h" // for wxExpandEnvVars
94 #include "wx/dynlib.h"
97 #if defined(__WIN32__) && defined(__MINGW32__)
98 #include "wx/msw/gccpriv.h"
102 #include "wx/msw/private.h"
105 #if defined(__WXMAC__)
106 #include "wx/osx/private.h" // includes mac headers
109 // utime() is POSIX so should normally be available on all Unices
111 #include <sys/types.h>
113 #include <sys/stat.h>
123 #include <sys/utime.h>
124 #include <sys/stat.h>
135 #define MAX_PATH _MAX_PATH
139 #define S_ISREG(mode) ((mode) & S_IFREG)
142 #define S_ISDIR(mode) ((mode) & S_IFDIR)
146 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
147 #endif // wxUSE_LONGLONG
152 // ----------------------------------------------------------------------------
154 // ----------------------------------------------------------------------------
156 // small helper class which opens and closes the file - we use it just to get
157 // a file handle for the given file name to pass it to some Win32 API function
158 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
169 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
171 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
172 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
173 // be changed when we open it because this class is used for setting
174 // access time (see #10567)
175 m_hFile
= ::CreateFile
177 filename
.t_str(), // name
178 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
179 : FILE_WRITE_ATTRIBUTES
,
180 FILE_SHARE_READ
| // sharing mode
181 FILE_SHARE_WRITE
, // (allow everything)
182 NULL
, // no secutity attr
183 OPEN_EXISTING
, // creation disposition
185 NULL
// no template file
188 if ( m_hFile
== INVALID_HANDLE_VALUE
)
190 if ( mode
== ReadAttr
)
192 wxLogSysError(_("Failed to open '%s' for reading"),
197 wxLogSysError(_("Failed to open '%s' for writing"),
205 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
207 if ( !::CloseHandle(m_hFile
) )
209 wxLogSysError(_("Failed to close file handle"));
214 // return true only if the file could be opened successfully
215 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
218 operator HANDLE() const { return m_hFile
; }
226 // ----------------------------------------------------------------------------
228 // ----------------------------------------------------------------------------
230 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
232 // convert between wxDateTime and FILETIME which is a 64-bit value representing
233 // the number of 100-nanosecond intervals since January 1, 1601.
235 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
237 FILETIME ftcopy
= ft
;
239 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
241 wxLogLastError(wxT("FileTimeToLocalFileTime"));
245 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
247 wxLogLastError(wxT("FileTimeToSystemTime"));
250 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
251 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
254 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
257 st
.wDay
= dt
.GetDay();
258 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
259 st
.wYear
= (WORD
)dt
.GetYear();
260 st
.wHour
= dt
.GetHour();
261 st
.wMinute
= dt
.GetMinute();
262 st
.wSecond
= dt
.GetSecond();
263 st
.wMilliseconds
= dt
.GetMillisecond();
266 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
268 wxLogLastError(wxT("SystemTimeToFileTime"));
271 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
273 wxLogLastError(wxT("LocalFileTimeToFileTime"));
277 #endif // wxUSE_DATETIME && __WIN32__
279 // return a string with the volume par
280 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
284 if ( !volume
.empty() )
286 format
= wxFileName::GetFormat(format
);
288 // Special Windows UNC paths hack, part 2: undo what we did in
289 // SplitPath() and make an UNC path if we have a drive which is not a
290 // single letter (hopefully the network shares can't be one letter only
291 // although I didn't find any authoritative docs on this)
292 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
294 // We also have to check for Windows unique volume names here and
295 // return it with '\\?\' prepended to it
296 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume
+ "\\",
299 path
<< "\\\\?\\" << volume
;
303 // it must be a UNC path
304 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
307 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
309 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
317 // return true if the character is a DOS path separator i.e. either a slash or
319 inline bool IsDOSPathSep(wxUniChar ch
)
321 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
324 // return true if the format used is the DOS/Windows one and the string looks
326 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
328 return format
== wxPATH_DOS
&&
329 path
.length() >= 4 && // "\\a" can't be a UNC path
330 IsDOSPathSep(path
[0u]) &&
331 IsDOSPathSep(path
[1u]) &&
332 !IsDOSPathSep(path
[2u]);
337 // Under Unix-ish systems (basically everything except Windows) we may work
338 // either with the file itself or its target in case it's a symbolic link, as
339 // determined by wxFileName::ShouldFollowLink(). StatAny() can be used to stat
340 // the appropriate file with an extra twist that it also works (by following
341 // the symlink by default) when there is no wxFileName object at all, as is the
342 // case in static methods.
344 // Private implementation, don't call directly, use one of the overloads below.
345 bool DoStatAny(wxStructStat
& st
, wxString path
, const wxFileName
* fn
)
347 // We need to remove any trailing slashes from the path because they could
348 // interfere with the symlink following decision: even if we use lstat(),
349 // it would still follow the symlink if we pass it a path with a slash at
350 // the end because the symlink resolution would happen while following the
351 // path and not for the last path element itself.
353 while ( wxEndsWithPathSeparator(path
) )
356 int ret
= !fn
|| fn
->ShouldFollowLink() ? wxStat(path
, &st
)
357 : wxLstat(path
, &st
);
361 // Overloads to use for a case when we don't have wxFileName object and when we
364 bool StatAny(wxStructStat
& st
, const wxString
& path
)
366 return DoStatAny(st
, path
, NULL
);
370 bool StatAny(wxStructStat
& st
, const wxFileName
& fn
)
372 return DoStatAny(st
, fn
.GetFullPath(), &fn
);
377 // ----------------------------------------------------------------------------
379 // ----------------------------------------------------------------------------
381 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
382 static const size_t wxMSWUniqueVolumePrefixLength
= 49;
384 } // anonymous namespace
386 // ============================================================================
388 // ============================================================================
390 // ----------------------------------------------------------------------------
391 // wxFileName construction
392 // ----------------------------------------------------------------------------
394 void wxFileName::Assign( const wxFileName
&filepath
)
396 m_volume
= filepath
.GetVolume();
397 m_dirs
= filepath
.GetDirs();
398 m_name
= filepath
.GetName();
399 m_ext
= filepath
.GetExt();
400 m_relative
= filepath
.m_relative
;
401 m_hasExt
= filepath
.m_hasExt
;
402 m_dontFollowLinks
= filepath
.m_dontFollowLinks
;
405 void wxFileName::Assign(const wxString
& volume
,
406 const wxString
& path
,
407 const wxString
& name
,
412 // we should ignore paths which look like UNC shares because we already
413 // have the volume here and the UNC notation (\\server\path) is only valid
414 // for paths which don't start with a volume, so prevent SetPath() from
415 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
417 // note also that this is a rather ugly way to do what we want (passing
418 // some kind of flag telling to ignore UNC paths to SetPath() would be
419 // better) but this is the safest thing to do to avoid breaking backwards
420 // compatibility in 2.8
421 if ( IsUNCPath(path
, format
) )
423 // remove one of the 2 leading backslashes to ensure that it's not
424 // recognized as an UNC path by SetPath()
425 wxString
pathNonUNC(path
, 1, wxString::npos
);
426 SetPath(pathNonUNC
, format
);
428 else // no UNC complications
430 SetPath(path
, format
);
440 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
444 if ( pathOrig
.empty() )
452 format
= GetFormat( format
);
454 // 0) deal with possible volume part first
457 SplitVolume(pathOrig
, &volume
, &path
, format
);
458 if ( !volume
.empty() )
465 // 1) Determine if the path is relative or absolute.
469 // we had only the volume
473 wxChar leadingChar
= path
[0u];
478 m_relative
= leadingChar
== wxT(':');
480 // We then remove a leading ":". The reason is in our
481 // storage form for relative paths:
482 // ":dir:file.txt" actually means "./dir/file.txt" in
483 // DOS notation and should get stored as
484 // (relative) (dir) (file.txt)
485 // "::dir:file.txt" actually means "../dir/file.txt"
486 // stored as (relative) (..) (dir) (file.txt)
487 // This is important only for the Mac as an empty dir
488 // actually means <UP>, whereas under DOS, double
489 // slashes can be ignored: "\\\\" is the same as "\\".
495 // TODO: what is the relative path format here?
500 wxFAIL_MSG( wxT("Unknown path format") );
501 // !! Fall through !!
504 m_relative
= leadingChar
!= wxT('/');
508 m_relative
= !IsPathSeparator(leadingChar
, format
);
513 // 2) Break up the path into its members. If the original path
514 // was just "/" or "\\", m_dirs will be empty. We know from
515 // the m_relative field, if this means "nothing" or "root dir".
517 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
519 while ( tn
.HasMoreTokens() )
521 wxString token
= tn
.GetNextToken();
523 // Remove empty token under DOS and Unix, interpret them
527 if (format
== wxPATH_MAC
)
528 m_dirs
.Add( wxT("..") );
538 void wxFileName::Assign(const wxString
& fullpath
,
541 wxString volume
, path
, name
, ext
;
543 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
545 Assign(volume
, path
, name
, ext
, hasExt
, format
);
548 void wxFileName::Assign(const wxString
& fullpathOrig
,
549 const wxString
& fullname
,
552 // always recognize fullpath as directory, even if it doesn't end with a
554 wxString fullpath
= fullpathOrig
;
555 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
557 fullpath
+= GetPathSeparator(format
);
560 wxString volume
, path
, name
, ext
;
563 // do some consistency checks: the name should be really just the filename
564 // and the path should be really just a path
565 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
567 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
569 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
570 wxT("the file name shouldn't contain the path") );
572 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
575 // This test makes no sense on an OpenVMS system.
576 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
577 wxT("the path shouldn't contain file name nor extension") );
579 Assign(volume
, path
, name
, ext
, hasExt
, format
);
582 void wxFileName::Assign(const wxString
& pathOrig
,
583 const wxString
& name
,
589 SplitVolume(pathOrig
, &volume
, &path
, format
);
591 Assign(volume
, path
, name
, ext
, format
);
594 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
596 Assign(dir
, wxEmptyString
, format
);
599 void wxFileName::Clear()
605 m_ext
= wxEmptyString
;
607 // we don't have any absolute path for now
613 // follow symlinks by default
614 m_dontFollowLinks
= false;
618 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
620 return wxFileName(file
, format
);
624 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
627 fn
.AssignDir(dir
, format
);
631 // ----------------------------------------------------------------------------
633 // ----------------------------------------------------------------------------
638 // Flags for wxFileSystemObjectExists() asking it to check for:
641 wxFileSystemObject_File
= 1, // file existence
642 wxFileSystemObject_Dir
= 2, // directory existence
643 wxFileSystemObject_Other
= 4, // existence of something else, e.g.
644 // device, socket, FIFO under Unix
645 wxFileSystemObject_Any
= 7 // existence of anything at all
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
,
674 const wxFileName
* fn
= NULL
)
676 wxUnusedVar(fn
); // It's only used under Unix
678 // Should the existence of file/directory with this name be accepted, i.e.
679 // result in the true return value from this function?
680 const bool acceptFile
= (flags
& wxFileSystemObject_File
) != 0;
681 const bool acceptDir
= (flags
& wxFileSystemObject_Dir
) != 0;
683 wxString
strPath(path
);
685 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
688 // Ensure that the path doesn't have any trailing separators when
689 // checking for directories.
690 RemoveTrailingSeparatorsFromPath(strPath
);
693 // we must use GetFileAttributes() instead of the ANSI C functions because
694 // it can cope with network (UNC) paths unlike them
695 DWORD ret
= ::GetFileAttributes(strPath
.t_str());
697 if ( ret
== INVALID_FILE_ATTRIBUTES
)
700 if ( ret
& FILE_ATTRIBUTE_DIRECTORY
)
703 // Anything else must be a file (perhaps we should check for
704 // FILE_ATTRIBUTE_REPARSE_POINT?)
706 #elif defined(__OS2__)
709 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
710 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
714 FILESTATUS3 Info
= {{0}};
715 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
716 (void*) &Info
, sizeof(FILESTATUS3
));
718 if ( rc
== NO_ERROR
)
720 if ( Info
.attrFile
& FILE_DIRECTORY
)
726 // We consider that the path must exist if we get a sharing violation for
727 // it but we don't know what is it in this case.
728 if ( rc
== ERROR_SHARING_VIOLATION
)
729 return flags
& wxFileSystemObject_Other
;
731 // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
734 #else // Non-MSW, non-OS/2
736 if ( !DoStatAny(st
, strPath
, fn
) )
739 if ( S_ISREG(st
.st_mode
) )
741 if ( S_ISDIR(st
.st_mode
) )
744 return flags
& wxFileSystemObject_Other
;
748 } // anonymous namespace
750 bool wxFileName::FileExists() const
752 return wxFileSystemObjectExists(GetFullPath(), wxFileSystemObject_File
, this);
756 bool wxFileName::FileExists( const wxString
&filePath
)
758 return wxFileSystemObjectExists(filePath
, wxFileSystemObject_File
);
761 bool wxFileName::DirExists() const
763 return wxFileSystemObjectExists(GetPath(), wxFileSystemObject_Dir
, this);
767 bool wxFileName::DirExists( const wxString
&dirPath
)
769 return wxFileSystemObjectExists(dirPath
, wxFileSystemObject_Dir
);
772 bool wxFileName::Exists() const
774 return wxFileSystemObjectExists(GetFullPath(), wxFileSystemObject_Any
, this);
778 bool wxFileName::Exists(const wxString
& path
)
780 return wxFileSystemObjectExists(path
, wxFileSystemObject_Any
);
783 // ----------------------------------------------------------------------------
784 // CWD and HOME stuff
785 // ----------------------------------------------------------------------------
787 void wxFileName::AssignCwd(const wxString
& volume
)
789 AssignDir(wxFileName::GetCwd(volume
));
793 wxString
wxFileName::GetCwd(const wxString
& volume
)
795 // if we have the volume, we must get the current directory on this drive
796 // and to do this we have to chdir to this volume - at least under Windows,
797 // I don't know how to get the current drive on another volume elsewhere
800 if ( !volume
.empty() )
803 SetCwd(volume
+ GetVolumeSeparator());
806 wxString cwd
= ::wxGetCwd();
808 if ( !volume
.empty() )
816 bool wxFileName::SetCwd() const
818 return wxFileName::SetCwd( GetPath() );
821 bool wxFileName::SetCwd( const wxString
&cwd
)
823 return ::wxSetWorkingDirectory( cwd
);
826 void wxFileName::AssignHomeDir()
828 AssignDir(wxFileName::GetHomeDir());
831 wxString
wxFileName::GetHomeDir()
833 return ::wxGetHomeDir();
837 // ----------------------------------------------------------------------------
838 // CreateTempFileName
839 // ----------------------------------------------------------------------------
841 #if wxUSE_FILE || wxUSE_FFILE
844 #if !defined wx_fdopen && defined HAVE_FDOPEN
845 #define wx_fdopen fdopen
848 // NB: GetTempFileName() under Windows creates the file, so using
849 // O_EXCL there would fail
851 #define wxOPEN_EXCL 0
853 #define wxOPEN_EXCL O_EXCL
857 #ifdef wxOpenOSFHandle
858 #define WX_HAVE_DELETE_ON_CLOSE
859 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
861 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
863 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
865 DWORD disposition
= OPEN_ALWAYS
;
867 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
868 FILE_FLAG_DELETE_ON_CLOSE
;
870 HANDLE h
= ::CreateFile(filename
.t_str(), access
, 0, NULL
,
871 disposition
, attributes
, NULL
);
873 return wxOpenOSFHandle(h
, wxO_BINARY
);
875 #endif // wxOpenOSFHandle
878 // Helper to open the file
880 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
882 #ifdef WX_HAVE_DELETE_ON_CLOSE
884 return wxOpenWithDeleteOnClose(path
);
887 *deleteOnClose
= false;
889 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
894 // Helper to open the file and attach it to the wxFFile
896 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
899 *deleteOnClose
= false;
900 return file
->Open(path
, wxT("w+b"));
902 int fd
= wxTempOpen(path
, deleteOnClose
);
905 file
->Attach(wx_fdopen(fd
, "w+b"), path
);
906 return file
->IsOpened();
909 #endif // wxUSE_FFILE
913 #define WXFILEARGS(x, y) y
915 #define WXFILEARGS(x, y) x
917 #define WXFILEARGS(x, y) x, y
921 // Implementation of wxFileName::CreateTempFileName().
923 static wxString
wxCreateTempImpl(
924 const wxString
& prefix
,
925 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
926 bool *deleteOnClose
= NULL
)
928 #if wxUSE_FILE && wxUSE_FFILE
929 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
931 wxString path
, dir
, name
;
932 bool wantDeleteOnClose
= false;
936 // set the result to false initially
937 wantDeleteOnClose
= *deleteOnClose
;
938 *deleteOnClose
= false;
942 // easier if it alwasys points to something
943 deleteOnClose
= &wantDeleteOnClose
;
946 // use the directory specified by the prefix
947 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
951 dir
= wxFileName::GetTempDir();
954 #if defined(__WXWINCE__)
955 path
= dir
+ wxT("\\") + name
;
957 while (wxFileName::FileExists(path
))
959 path
= dir
+ wxT("\\") + name
;
964 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
965 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
966 wxStringBuffer(path
, MAX_PATH
+ 1)))
968 wxLogLastError(wxT("GetTempFileName"));
976 if ( !wxEndsWithPathSeparator(dir
) &&
977 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
979 path
+= wxFILE_SEP_PATH
;
984 #if defined(HAVE_MKSTEMP)
985 // scratch space for mkstemp()
986 path
+= wxT("XXXXXX");
988 // we need to copy the path to the buffer in which mkstemp() can modify it
989 wxCharBuffer
buf(path
.fn_str());
991 // cast is safe because the string length doesn't change
992 int fdTemp
= mkstemp( (char*)(const char*) buf
);
995 // this might be not necessary as mkstemp() on most systems should have
996 // already done it but it doesn't hurt neither...
999 else // mkstemp() succeeded
1001 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1004 // avoid leaking the fd
1007 fileTemp
->Attach(fdTemp
);
1016 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"), path
);
1018 ffileTemp
->Open(path
, wxT("r+b"));
1029 #else // !HAVE_MKSTEMP
1033 path
+= wxT("XXXXXX");
1035 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
1036 if ( !mktemp( (char*)(const char*) buf
) )
1042 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1044 #else // !HAVE_MKTEMP (includes __DOS__)
1045 // generate the unique file name ourselves
1046 #if !defined(__DOS__)
1047 path
<< (unsigned int)getpid();
1052 static const size_t numTries
= 1000;
1053 for ( size_t n
= 0; n
< numTries
; n
++ )
1055 // 3 hex digits is enough for numTries == 1000 < 4096
1056 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
1057 if ( !wxFileName::FileExists(pathTry
) )
1066 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1068 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1070 #endif // Windows/!Windows
1074 wxLogSysError(_("Failed to create a temporary file name"));
1080 // open the file - of course, there is a race condition here, this is
1081 // why we always prefer using mkstemp()...
1083 if ( fileTemp
&& !fileTemp
->IsOpened() )
1085 *deleteOnClose
= wantDeleteOnClose
;
1086 int fd
= wxTempOpen(path
, deleteOnClose
);
1088 fileTemp
->Attach(fd
);
1095 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1097 *deleteOnClose
= wantDeleteOnClose
;
1098 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1104 // FIXME: If !ok here should we loop and try again with another
1105 // file name? That is the standard recourse if open(O_EXCL)
1106 // fails, though of course it should be protected against
1107 // possible infinite looping too.
1109 wxLogError(_("Failed to open temporary file."));
1119 static bool wxCreateTempImpl(
1120 const wxString
& prefix
,
1121 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1124 bool deleteOnClose
= true;
1126 *name
= wxCreateTempImpl(prefix
,
1127 WXFILEARGS(fileTemp
, ffileTemp
),
1130 bool ok
= !name
->empty();
1135 else if (ok
&& wxRemoveFile(*name
))
1143 static void wxAssignTempImpl(
1145 const wxString
& prefix
,
1146 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1149 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1151 if ( tempname
.empty() )
1153 // error, failed to get temp file name
1158 fn
->Assign(tempname
);
1163 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1165 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1169 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1171 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1174 #endif // wxUSE_FILE || wxUSE_FFILE
1179 wxString
wxCreateTempFileName(const wxString
& prefix
,
1181 bool *deleteOnClose
)
1183 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1186 bool wxCreateTempFile(const wxString
& prefix
,
1190 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1193 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1195 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1200 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1202 return wxCreateTempFileName(prefix
, fileTemp
);
1205 #endif // wxUSE_FILE
1210 wxString
wxCreateTempFileName(const wxString
& prefix
,
1212 bool *deleteOnClose
)
1214 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1217 bool wxCreateTempFile(const wxString
& prefix
,
1221 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1225 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1227 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1232 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1234 return wxCreateTempFileName(prefix
, fileTemp
);
1237 #endif // wxUSE_FFILE
1240 // ----------------------------------------------------------------------------
1241 // directory operations
1242 // ----------------------------------------------------------------------------
1244 // helper of GetTempDir(): check if the given directory exists and return it if
1245 // it does or an empty string otherwise
1249 wxString
CheckIfDirExists(const wxString
& dir
)
1251 return wxFileName::DirExists(dir
) ? dir
: wxString();
1254 } // anonymous namespace
1256 wxString
wxFileName::GetTempDir()
1258 // first try getting it from environment: this allows overriding the values
1259 // used by default if the user wants to create temporary files in another
1261 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1264 dir
= CheckIfDirExists(wxGetenv("TMP"));
1266 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1269 // if no environment variables are set, use the system default
1272 #if defined(__WXWINCE__)
1273 dir
= CheckIfDirExists(wxT("\\temp"));
1274 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1275 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1277 wxLogLastError(wxT("GetTempPath"));
1279 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1280 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1281 #endif // systems with native way
1283 else // we got directory from an environment variable
1285 // remove any trailing path separators, we don't want to ever return
1286 // them from this function for consistency
1287 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1288 if ( lastNonSep
== wxString::npos
)
1290 // the string consists entirely of separators, leave only one
1291 dir
= GetPathSeparator();
1295 dir
.erase(lastNonSep
+ 1);
1299 // fall back to hard coded value
1302 #ifdef __UNIX_LIKE__
1303 dir
= CheckIfDirExists("/tmp");
1305 #endif // __UNIX_LIKE__
1312 bool wxFileName::Mkdir( int perm
, int flags
) const
1314 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1317 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1319 if ( flags
& wxPATH_MKDIR_FULL
)
1321 // split the path in components
1322 wxFileName filename
;
1323 filename
.AssignDir(dir
);
1326 if ( filename
.HasVolume())
1328 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1331 wxArrayString dirs
= filename
.GetDirs();
1332 size_t count
= dirs
.GetCount();
1333 for ( size_t i
= 0; i
< count
; i
++ )
1335 if ( i
> 0 || filename
.IsAbsolute() )
1336 currPath
+= wxFILE_SEP_PATH
;
1337 currPath
+= dirs
[i
];
1339 if (!DirExists(currPath
))
1341 if (!wxMkdir(currPath
, perm
))
1343 // no need to try creating further directories
1353 return ::wxMkdir( dir
, perm
);
1356 bool wxFileName::Rmdir(int flags
) const
1358 return wxFileName::Rmdir( GetPath(), flags
);
1361 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1364 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1366 // SHFileOperation needs double null termination string
1367 // but without separator at the end of the path
1369 if ( path
.Last() == wxFILE_SEP_PATH
)
1373 SHFILEOPSTRUCT fileop
;
1374 wxZeroMemory(fileop
);
1375 fileop
.wFunc
= FO_DELETE
;
1376 fileop
.pFrom
= path
.t_str();
1377 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1379 // FOF_NOERRORUI is not defined in WinCE
1380 fileop
.fFlags
|= FOF_NOERRORUI
;
1383 int ret
= SHFileOperation(&fileop
);
1386 // SHFileOperation may return non-Win32 error codes, so the error
1387 // message can be incorrect
1388 wxLogApiError(wxT("SHFileOperation"), ret
);
1394 else if ( flags
& wxPATH_RMDIR_FULL
)
1395 #else // !__WINDOWS__
1396 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1397 #endif // !__WINDOWS__
1400 if ( path
.Last() != wxFILE_SEP_PATH
)
1401 path
+= wxFILE_SEP_PATH
;
1405 if ( !d
.IsOpened() )
1410 // first delete all subdirectories
1411 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1414 wxFileName::Rmdir(path
+ filename
, flags
);
1415 cont
= d
.GetNext(&filename
);
1419 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1421 // delete all files too
1422 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1425 ::wxRemoveFile(path
+ filename
);
1426 cont
= d
.GetNext(&filename
);
1429 #endif // !__WINDOWS__
1432 return ::wxRmdir(dir
);
1435 // ----------------------------------------------------------------------------
1436 // path normalization
1437 // ----------------------------------------------------------------------------
1439 bool wxFileName::Normalize(int flags
,
1440 const wxString
& cwd
,
1441 wxPathFormat format
)
1443 // deal with env vars renaming first as this may seriously change the path
1444 if ( flags
& wxPATH_NORM_ENV_VARS
)
1446 wxString pathOrig
= GetFullPath(format
);
1447 wxString path
= wxExpandEnvVars(pathOrig
);
1448 if ( path
!= pathOrig
)
1454 // the existing path components
1455 wxArrayString dirs
= GetDirs();
1457 // the path to prepend in front to make the path absolute
1460 format
= GetFormat(format
);
1462 // set up the directory to use for making the path absolute later
1463 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1467 curDir
.AssignCwd(GetVolume());
1469 else // cwd provided
1471 curDir
.AssignDir(cwd
);
1475 // handle ~ stuff under Unix only
1476 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1478 if ( !dirs
.IsEmpty() )
1480 wxString dir
= dirs
[0u];
1481 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1483 // to make the path absolute use the home directory
1484 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1490 // transform relative path into abs one
1491 if ( curDir
.IsOk() )
1493 // this path may be relative because it doesn't have the volume name
1494 // and still have m_relative=true; in this case we shouldn't modify
1495 // our directory components but just set the current volume
1496 if ( !HasVolume() && curDir
.HasVolume() )
1498 SetVolume(curDir
.GetVolume());
1502 // yes, it was the case - we don't need curDir then
1507 // finally, prepend curDir to the dirs array
1508 wxArrayString dirsNew
= curDir
.GetDirs();
1509 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1511 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1512 // return for some reason an absolute path, then curDir maybe not be absolute!
1513 if ( !curDir
.m_relative
)
1515 // we have prepended an absolute path and thus we are now an absolute
1519 // else if (flags & wxPATH_NORM_ABSOLUTE):
1520 // should we warn the user that we didn't manage to make the path absolute?
1523 // now deal with ".", ".." and the rest
1525 size_t count
= dirs
.GetCount();
1526 for ( size_t n
= 0; n
< count
; n
++ )
1528 wxString dir
= dirs
[n
];
1530 if ( flags
& wxPATH_NORM_DOTS
)
1532 if ( dir
== wxT(".") )
1538 if ( dir
== wxT("..") )
1540 if ( m_dirs
.empty() )
1542 // We have more ".." than directory components so far.
1543 // Don't treat this as an error as the path could have been
1544 // entered by user so try to handle it reasonably: if the
1545 // path is absolute, just ignore the extra ".." because
1546 // "/.." is the same as "/". Otherwise, i.e. for relative
1547 // paths, keep ".." unchanged because removing it would
1548 // modify the file a relative path refers to.
1553 else // Normal case, go one step up.
1564 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1565 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1568 if (GetShortcutTarget(GetFullPath(format
), filename
))
1576 #if defined(__WIN32__)
1577 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1579 Assign(GetLongPath());
1583 // Change case (this should be kept at the end of the function, to ensure
1584 // that the path doesn't change any more after we normalize its case)
1585 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1587 m_volume
.MakeLower();
1591 // directory entries must be made lower case as well
1592 count
= m_dirs
.GetCount();
1593 for ( size_t i
= 0; i
< count
; i
++ )
1595 m_dirs
[i
].MakeLower();
1603 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1604 const wxString
& replacementFmtString
,
1605 wxPathFormat format
)
1607 // look into stringForm for the contents of the given environment variable
1609 if (envname
.empty() ||
1610 !wxGetEnv(envname
, &val
))
1615 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1616 // do not touch the file name and the extension
1618 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1619 stringForm
.Replace(val
, replacement
);
1621 // Now assign ourselves the modified path:
1622 Assign(stringForm
, GetFullName(), format
);
1628 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1630 wxString homedir
= wxGetHomeDir();
1631 if (homedir
.empty())
1634 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1635 // do not touch the file name and the extension
1637 stringForm
.Replace(homedir
, "~");
1639 // Now assign ourselves the modified path:
1640 Assign(stringForm
, GetFullName(), format
);
1645 // ----------------------------------------------------------------------------
1646 // get the shortcut target
1647 // ----------------------------------------------------------------------------
1649 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1650 // The .lnk file is a plain text file so it should be easy to
1651 // make it work. Hint from Google Groups:
1652 // "If you open up a lnk file, you'll see a
1653 // number, followed by a pound sign (#), followed by more text. The
1654 // number is the number of characters that follows the pound sign. The
1655 // characters after the pound sign are the command line (which _can_
1656 // include arguments) to be executed. Any path (e.g. \windows\program
1657 // files\myapp.exe) that includes spaces needs to be enclosed in
1658 // quotation marks."
1660 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1661 // The following lines are necessary under WinCE
1662 // #include "wx/msw/private.h"
1663 // #include <ole2.h>
1665 #if defined(__WXWINCE__)
1666 #include <shlguid.h>
1669 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1670 wxString
& targetFilename
,
1671 wxString
* arguments
) const
1673 wxString path
, file
, ext
;
1674 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1678 bool success
= false;
1680 // Assume it's not a shortcut if it doesn't end with lnk
1681 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1684 // create a ShellLink object
1685 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1686 IID_IShellLink
, (LPVOID
*) &psl
);
1688 if (SUCCEEDED(hres
))
1691 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1692 if (SUCCEEDED(hres
))
1694 WCHAR wsz
[MAX_PATH
];
1696 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1699 hres
= ppf
->Load(wsz
, 0);
1702 if (SUCCEEDED(hres
))
1705 // Wrong prototype in early versions
1706 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1707 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1709 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1711 targetFilename
= wxString(buf
);
1712 success
= (shortcutPath
!= targetFilename
);
1714 psl
->GetArguments(buf
, 2048);
1716 if (!args
.empty() && arguments
)
1728 #endif // __WIN32__ && !__WXWINCE__
1731 // ----------------------------------------------------------------------------
1732 // absolute/relative paths
1733 // ----------------------------------------------------------------------------
1735 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1737 // unix paths beginning with ~ are reported as being absolute
1738 if ( format
== wxPATH_UNIX
)
1740 if ( !m_dirs
.IsEmpty() )
1742 wxString dir
= m_dirs
[0u];
1744 if (!dir
.empty() && dir
[0u] == wxT('~'))
1749 // if our path doesn't start with a path separator, it's not an absolute
1754 if ( !GetVolumeSeparator(format
).empty() )
1756 // this format has volumes and an absolute path must have one, it's not
1757 // enough to have the full path to be an absolute file under Windows
1758 if ( GetVolume().empty() )
1765 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1767 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1769 // get cwd only once - small time saving
1770 wxString cwd
= wxGetCwd();
1771 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1772 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1774 bool withCase
= IsCaseSensitive(format
);
1776 // we can't do anything if the files live on different volumes
1777 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1783 // same drive, so we don't need our volume
1786 // remove common directories starting at the top
1787 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1788 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1791 fnBase
.m_dirs
.RemoveAt(0);
1794 // add as many ".." as needed
1795 size_t count
= fnBase
.m_dirs
.GetCount();
1796 for ( size_t i
= 0; i
< count
; i
++ )
1798 m_dirs
.Insert(wxT(".."), 0u);
1801 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1803 // a directory made relative with respect to itself is '.' under Unix
1804 // and DOS, by definition (but we don't have to insert "./" for the
1806 if ( m_dirs
.IsEmpty() && IsDir() )
1808 m_dirs
.Add(wxT('.'));
1818 // ----------------------------------------------------------------------------
1819 // filename kind tests
1820 // ----------------------------------------------------------------------------
1822 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1824 wxFileName fn1
= *this,
1827 // get cwd only once - small time saving
1828 wxString cwd
= wxGetCwd();
1829 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1830 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1832 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1835 #if defined(__UNIX__)
1836 wxStructStat st1
, st2
;
1837 if ( StatAny(st1
, fn1
) && StatAny(st2
, fn2
) )
1839 if ( st1
.st_ino
== st2
.st_ino
&& st1
.st_dev
== st2
.st_dev
)
1842 //else: It's not an error if one or both files don't exist.
1843 #endif // defined __UNIX__
1849 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1851 // only Unix filenames are truly case-sensitive
1852 return GetFormat(format
) == wxPATH_UNIX
;
1856 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1858 // Inits to forbidden characters that are common to (almost) all platforms.
1859 wxString strForbiddenChars
= wxT("*?");
1861 // If asserts, wxPathFormat has been changed. In case of a new path format
1862 // addition, the following code might have to be updated.
1863 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1864 switch ( GetFormat(format
) )
1867 wxFAIL_MSG( wxT("Unknown path format") );
1868 // !! Fall through !!
1874 // On a Mac even names with * and ? are allowed (Tested with OS
1875 // 9.2.1 and OS X 10.2.5)
1876 strForbiddenChars
= wxEmptyString
;
1880 strForbiddenChars
+= wxT("\\/:\"<>|");
1887 return strForbiddenChars
;
1891 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1894 return wxEmptyString
;
1898 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1899 (GetFormat(format
) == wxPATH_VMS
) )
1901 sepVol
= wxFILE_SEP_DSK
;
1910 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1913 switch ( GetFormat(format
) )
1916 // accept both as native APIs do but put the native one first as
1917 // this is the one we use in GetFullPath()
1918 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1922 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1926 seps
= wxFILE_SEP_PATH_UNIX
;
1930 seps
= wxFILE_SEP_PATH_MAC
;
1934 seps
= wxFILE_SEP_PATH_VMS
;
1942 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1944 format
= GetFormat(format
);
1946 // under VMS the end of the path is ']', not the path separator used to
1947 // separate the components
1948 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1952 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1954 // wxString::Find() doesn't work as expected with NUL - it will always find
1955 // it, so test for it separately
1956 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1961 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
1963 // return true if the format used is the DOS/Windows one and the string begins
1964 // with a Windows unique volume name ("\\?\Volume{guid}\")
1965 return format
== wxPATH_DOS
&&
1966 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
1967 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
1968 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
1971 // ----------------------------------------------------------------------------
1972 // path components manipulation
1973 // ----------------------------------------------------------------------------
1975 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1979 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1984 const size_t len
= dir
.length();
1985 for ( size_t n
= 0; n
< len
; n
++ )
1987 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1989 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1998 void wxFileName::AppendDir( const wxString
& dir
)
2000 if ( IsValidDirComponent(dir
) )
2004 void wxFileName::PrependDir( const wxString
& dir
)
2009 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
2011 if ( IsValidDirComponent(dir
) )
2012 m_dirs
.Insert(dir
, before
);
2015 void wxFileName::RemoveDir(size_t pos
)
2017 m_dirs
.RemoveAt(pos
);
2020 // ----------------------------------------------------------------------------
2022 // ----------------------------------------------------------------------------
2024 void wxFileName::SetFullName(const wxString
& fullname
)
2026 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
2027 &m_name
, &m_ext
, &m_hasExt
);
2030 wxString
wxFileName::GetFullName() const
2032 wxString fullname
= m_name
;
2035 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
2041 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
2043 format
= GetFormat( format
);
2047 // return the volume with the path as well if requested
2048 if ( flags
& wxPATH_GET_VOLUME
)
2050 fullpath
+= wxGetVolumeString(GetVolume(), format
);
2053 // the leading character
2058 fullpath
+= wxFILE_SEP_PATH_MAC
;
2063 fullpath
+= wxFILE_SEP_PATH_DOS
;
2067 wxFAIL_MSG( wxT("Unknown path format") );
2073 fullpath
+= wxFILE_SEP_PATH_UNIX
;
2078 // no leading character here but use this place to unset
2079 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2080 // as, if I understand correctly, there should never be a dot
2081 // before the closing bracket
2082 flags
&= ~wxPATH_GET_SEPARATOR
;
2085 if ( m_dirs
.empty() )
2087 // there is nothing more
2091 // then concatenate all the path components using the path separator
2092 if ( format
== wxPATH_VMS
)
2094 fullpath
+= wxT('[');
2097 const size_t dirCount
= m_dirs
.GetCount();
2098 for ( size_t i
= 0; i
< dirCount
; i
++ )
2103 if ( m_dirs
[i
] == wxT(".") )
2105 // skip appending ':', this shouldn't be done in this
2106 // case as "::" is interpreted as ".." under Unix
2110 // convert back from ".." to nothing
2111 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2112 fullpath
+= m_dirs
[i
];
2116 wxFAIL_MSG( wxT("Unexpected path format") );
2117 // still fall through
2121 fullpath
+= m_dirs
[i
];
2125 // TODO: What to do with ".." under VMS
2127 // convert back from ".." to nothing
2128 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2129 fullpath
+= m_dirs
[i
];
2133 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2134 fullpath
+= GetPathSeparator(format
);
2137 if ( format
== wxPATH_VMS
)
2139 fullpath
+= wxT(']');
2145 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2147 // we already have a function to get the path
2148 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2151 // now just add the file name and extension to it
2152 fullpath
+= GetFullName();
2157 // Return the short form of the path (returns identity on non-Windows platforms)
2158 wxString
wxFileName::GetShortPath() const
2160 wxString
path(GetFullPath());
2162 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2163 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2167 if ( ::GetShortPathName
2170 wxStringBuffer(pathOut
, sz
),
2182 // Return the long form of the path (returns identity on non-Windows platforms)
2183 wxString
wxFileName::GetLongPath() const
2186 path
= GetFullPath();
2188 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2190 #if wxUSE_DYNLIB_CLASS
2191 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2193 // this is MT-safe as in the worst case we're going to resolve the function
2194 // twice -- but as the result is the same in both threads, it's ok
2195 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2196 if ( !s_pfnGetLongPathName
)
2198 static bool s_triedToLoad
= false;
2200 if ( !s_triedToLoad
)
2202 s_triedToLoad
= true;
2204 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2206 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2211 #endif // Unicode/ANSI
2213 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2215 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2216 dllKernel
.GetSymbol(GetLongPathName
);
2219 // note that kernel32.dll can be unloaded, it stays in memory
2220 // anyhow as all Win32 programs link to it and so it's safe to call
2221 // GetLongPathName() even after unloading it
2225 if ( s_pfnGetLongPathName
)
2227 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2230 if ( (*s_pfnGetLongPathName
)
2233 wxStringBuffer(pathOut
, dwSize
),
2241 #endif // wxUSE_DYNLIB_CLASS
2243 // The OS didn't support GetLongPathName, or some other error.
2244 // We need to call FindFirstFile on each component in turn.
2246 WIN32_FIND_DATA findFileData
;
2250 pathOut
= GetVolume() +
2251 GetVolumeSeparator(wxPATH_DOS
) +
2252 GetPathSeparator(wxPATH_DOS
);
2254 pathOut
= wxEmptyString
;
2256 wxArrayString dirs
= GetDirs();
2257 dirs
.Add(GetFullName());
2261 size_t count
= dirs
.GetCount();
2262 for ( size_t i
= 0; i
< count
; i
++ )
2264 const wxString
& dir
= dirs
[i
];
2266 // We're using pathOut to collect the long-name path, but using a
2267 // temporary for appending the last path component which may be
2269 tmpPath
= pathOut
+ dir
;
2271 // We must not process "." or ".." here as they would be (unexpectedly)
2272 // replaced by the corresponding directory names so just leave them
2275 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2276 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2277 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2279 tmpPath
+= wxFILE_SEP_PATH
;
2284 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2285 if (hFind
== INVALID_HANDLE_VALUE
)
2287 // Error: most likely reason is that path doesn't exist, so
2288 // append any unprocessed parts and return
2289 for ( i
+= 1; i
< count
; i
++ )
2290 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2295 pathOut
+= findFileData
.cFileName
;
2296 if ( (i
< (count
-1)) )
2297 pathOut
+= wxFILE_SEP_PATH
;
2303 #endif // Win32/!Win32
2308 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2310 if (format
== wxPATH_NATIVE
)
2312 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2313 format
= wxPATH_DOS
;
2314 #elif defined(__VMS)
2315 format
= wxPATH_VMS
;
2317 format
= wxPATH_UNIX
;
2323 #ifdef wxHAS_FILESYSTEM_VOLUMES
2326 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2328 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2330 wxString
vol(drive
);
2331 vol
+= wxFILE_SEP_DSK
;
2332 if ( flags
& wxPATH_GET_SEPARATOR
)
2333 vol
+= wxFILE_SEP_PATH
;
2338 #endif // wxHAS_FILESYSTEM_VOLUMES
2340 // ----------------------------------------------------------------------------
2341 // path splitting function
2342 // ----------------------------------------------------------------------------
2346 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2347 wxString
*pstrVolume
,
2349 wxPathFormat format
)
2351 format
= GetFormat(format
);
2353 wxString fullpath
= fullpathWithVolume
;
2355 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2357 // special Windows unique volume names hack: transform
2358 // \\?\Volume{guid}\path into Volume{guid}:path
2359 // note: this check must be done before the check for UNC path
2361 // we know the last backslash from the unique volume name is located
2362 // there from IsMSWUniqueVolumeNamePath
2363 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2365 // paths starting with a unique volume name should always be absolute
2366 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2368 // remove the leading "\\?\" part
2369 fullpath
.erase(0, 4);
2371 else if ( IsUNCPath(fullpath
, format
) )
2373 // special Windows UNC paths hack: transform \\share\path into share:path
2375 fullpath
.erase(0, 2);
2377 size_t posFirstSlash
=
2378 fullpath
.find_first_of(GetPathTerminators(format
));
2379 if ( posFirstSlash
!= wxString::npos
)
2381 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2383 // UNC paths are always absolute, right? (FIXME)
2384 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2388 // We separate the volume here
2389 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2391 wxString sepVol
= GetVolumeSeparator(format
);
2393 // we have to exclude the case of a colon in the very beginning of the
2394 // string as it can't be a volume separator (nor can this be a valid
2395 // DOS file name at all but we'll leave dealing with this to our caller)
2396 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2397 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2401 *pstrVolume
= fullpath
.Left(posFirstColon
);
2404 // remove the volume name and the separator from the full path
2405 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2410 *pstrPath
= fullpath
;
2414 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2415 wxString
*pstrVolume
,
2420 wxPathFormat format
)
2422 format
= GetFormat(format
);
2425 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2427 // find the positions of the last dot and last path separator in the path
2428 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2429 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2431 // check whether this dot occurs at the very beginning of a path component
2432 if ( (posLastDot
!= wxString::npos
) &&
2434 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2435 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2437 // dot may be (and commonly -- at least under Unix -- is) the first
2438 // character of the filename, don't treat the entire filename as
2439 // extension in this case
2440 posLastDot
= wxString::npos
;
2443 // if we do have a dot and a slash, check that the dot is in the name part
2444 if ( (posLastDot
!= wxString::npos
) &&
2445 (posLastSlash
!= wxString::npos
) &&
2446 (posLastDot
< posLastSlash
) )
2448 // the dot is part of the path, not the start of the extension
2449 posLastDot
= wxString::npos
;
2452 // now fill in the variables provided by user
2455 if ( posLastSlash
== wxString::npos
)
2462 // take everything up to the path separator but take care to make
2463 // the path equal to something like '/', not empty, for the files
2464 // immediately under root directory
2465 size_t len
= posLastSlash
;
2467 // this rule does not apply to mac since we do not start with colons (sep)
2468 // except for relative paths
2469 if ( !len
&& format
!= wxPATH_MAC
)
2472 *pstrPath
= fullpath
.Left(len
);
2474 // special VMS hack: remove the initial bracket
2475 if ( format
== wxPATH_VMS
)
2477 if ( (*pstrPath
)[0u] == wxT('[') )
2478 pstrPath
->erase(0, 1);
2485 // take all characters starting from the one after the last slash and
2486 // up to, but excluding, the last dot
2487 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2489 if ( posLastDot
== wxString::npos
)
2491 // take all until the end
2492 count
= wxString::npos
;
2494 else if ( posLastSlash
== wxString::npos
)
2498 else // have both dot and slash
2500 count
= posLastDot
- posLastSlash
- 1;
2503 *pstrName
= fullpath
.Mid(nStart
, count
);
2506 // finally deal with the extension here: we have an added complication that
2507 // extension may be empty (but present) as in "foo." where trailing dot
2508 // indicates the empty extension at the end -- and hence we must remember
2509 // that we have it independently of pstrExt
2510 if ( posLastDot
== wxString::npos
)
2520 // take everything after the dot
2522 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2529 void wxFileName::SplitPath(const wxString
& fullpath
,
2533 wxPathFormat format
)
2536 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2540 path
->Prepend(wxGetVolumeString(volume
, format
));
2545 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2547 wxFileName
fn(fullpath
);
2549 return fn
.GetFullPath();
2552 // ----------------------------------------------------------------------------
2554 // ----------------------------------------------------------------------------
2558 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2559 const wxDateTime
*dtMod
,
2560 const wxDateTime
*dtCreate
) const
2562 #if defined(__WIN32__)
2563 FILETIME ftAccess
, ftCreate
, ftWrite
;
2566 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2568 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2570 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2576 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2578 wxLogError(_("Setting directory access times is not supported "
2579 "under this OS version"));
2584 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2588 path
= GetFullPath();
2592 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2595 if ( ::SetFileTime(fh
,
2596 dtCreate
? &ftCreate
: NULL
,
2597 dtAccess
? &ftAccess
: NULL
,
2598 dtMod
? &ftWrite
: NULL
) )
2603 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2604 wxUnusedVar(dtCreate
);
2606 if ( !dtAccess
&& !dtMod
)
2608 // can't modify the creation time anyhow, don't try
2612 // if dtAccess or dtMod is not specified, use the other one (which must be
2613 // non NULL because of the test above) for both times
2615 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2616 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2617 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2621 #else // other platform
2622 wxUnusedVar(dtAccess
);
2624 wxUnusedVar(dtCreate
);
2627 wxLogSysError(_("Failed to modify file times for '%s'"),
2628 GetFullPath().c_str());
2633 bool wxFileName::Touch() const
2635 #if defined(__UNIX_LIKE__)
2636 // under Unix touching file is simple: just pass NULL to utime()
2637 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2642 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2645 #else // other platform
2646 wxDateTime dtNow
= wxDateTime::Now();
2648 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2652 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2654 wxDateTime
*dtCreate
) const
2656 #if defined(__WIN32__)
2657 // we must use different methods for the files and directories under
2658 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2659 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2662 FILETIME ftAccess
, ftCreate
, ftWrite
;
2665 // implemented in msw/dir.cpp
2666 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2667 FILETIME
*, FILETIME
*, FILETIME
*);
2669 // we should pass the path without the trailing separator to
2670 // wxGetDirectoryTimes()
2671 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2672 &ftAccess
, &ftCreate
, &ftWrite
);
2676 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2679 ok
= ::GetFileTime(fh
,
2680 dtCreate
? &ftCreate
: NULL
,
2681 dtAccess
? &ftAccess
: NULL
,
2682 dtMod
? &ftWrite
: NULL
) != 0;
2693 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2695 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2697 ConvertFileTimeToWx(dtMod
, ftWrite
);
2701 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2702 // no need to test for IsDir() here
2704 if ( StatAny(stBuf
, *this) )
2706 // Android defines st_*time fields as unsigned long, but time_t as long,
2707 // hence the static_casts.
2709 dtAccess
->Set(static_cast<time_t>(stBuf
.st_atime
));
2711 dtMod
->Set(static_cast<time_t>(stBuf
.st_mtime
));
2713 dtCreate
->Set(static_cast<time_t>(stBuf
.st_ctime
));
2717 #else // other platform
2718 wxUnusedVar(dtAccess
);
2720 wxUnusedVar(dtCreate
);
2723 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2724 GetFullPath().c_str());
2729 #endif // wxUSE_DATETIME
2732 // ----------------------------------------------------------------------------
2733 // file size functions
2734 // ----------------------------------------------------------------------------
2739 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2741 if (!wxFileExists(filename
))
2742 return wxInvalidSize
;
2744 #if defined(__WIN32__)
2745 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2747 return wxInvalidSize
;
2749 DWORD lpFileSizeHigh
;
2750 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2751 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2752 return wxInvalidSize
;
2754 return wxULongLong(lpFileSizeHigh
, ret
);
2755 #else // ! __WIN32__
2757 if (wxStat( filename
, &st
) != 0)
2758 return wxInvalidSize
;
2759 return wxULongLong(st
.st_size
);
2764 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2765 const wxString
&nullsize
,
2767 wxSizeConvention conv
)
2769 // deal with trivial case first
2770 if ( bs
== 0 || bs
== wxInvalidSize
)
2773 // depending on the convention used the multiplier may be either 1000 or
2774 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2775 double multiplier
= 1024.;
2780 case wxSIZE_CONV_TRADITIONAL
:
2781 // nothing to do, this corresponds to the default values of both
2782 // the multiplier and infix string
2785 case wxSIZE_CONV_IEC
:
2789 case wxSIZE_CONV_SI
:
2794 const double kiloByteSize
= multiplier
;
2795 const double megaByteSize
= multiplier
* kiloByteSize
;
2796 const double gigaByteSize
= multiplier
* megaByteSize
;
2797 const double teraByteSize
= multiplier
* gigaByteSize
;
2799 const double bytesize
= bs
.ToDouble();
2802 if ( bytesize
< kiloByteSize
)
2803 result
.Printf("%s B", bs
.ToString());
2804 else if ( bytesize
< megaByteSize
)
2805 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2806 else if (bytesize
< gigaByteSize
)
2807 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2808 else if (bytesize
< teraByteSize
)
2809 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2811 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2816 wxULongLong
wxFileName::GetSize() const
2818 return GetSize(GetFullPath());
2821 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2823 wxSizeConvention conv
) const
2825 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2828 #endif // wxUSE_LONGLONG
2830 // ----------------------------------------------------------------------------
2831 // Mac-specific functions
2832 // ----------------------------------------------------------------------------
2834 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2839 class MacDefaultExtensionRecord
2842 MacDefaultExtensionRecord()
2848 // default copy ctor, assignment operator and dtor are ok
2850 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2854 m_creator
= creator
;
2862 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2864 bool gMacDefaultExtensionsInited
= false;
2866 #include "wx/arrimpl.cpp"
2868 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2870 MacDefaultExtensionArray gMacDefaultExtensions
;
2872 // load the default extensions
2873 const MacDefaultExtensionRecord gDefaults
[] =
2875 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2876 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2877 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2880 void MacEnsureDefaultExtensionsLoaded()
2882 if ( !gMacDefaultExtensionsInited
)
2884 // we could load the pc exchange prefs here too
2885 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2887 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2889 gMacDefaultExtensionsInited
= true;
2893 } // anonymous namespace
2895 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2898 FSCatalogInfo catInfo
;
2901 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2903 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2905 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2906 finfo
->fileType
= type
;
2907 finfo
->fileCreator
= creator
;
2908 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2915 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2918 FSCatalogInfo catInfo
;
2921 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2923 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2925 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2926 *type
= finfo
->fileType
;
2927 *creator
= finfo
->fileCreator
;
2934 bool wxFileName::MacSetDefaultTypeAndCreator()
2936 wxUint32 type
, creator
;
2937 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2940 return MacSetTypeAndCreator( type
, creator
) ;
2945 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2947 MacEnsureDefaultExtensionsLoaded() ;
2948 wxString extl
= ext
.Lower() ;
2949 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2951 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2953 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2954 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2961 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2963 MacEnsureDefaultExtensionsLoaded();
2964 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2965 gMacDefaultExtensions
.Add( rec
);
2968 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON