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
) )
355 const size_t posLast
= path
.length() - 1;
358 // Don't turn "/" into empty string.
365 int ret
= !fn
|| fn
->ShouldFollowLink() ? wxStat(path
, &st
)
366 : 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
)
375 return DoStatAny(st
, path
, NULL
);
379 bool StatAny(wxStructStat
& st
, const wxFileName
& fn
)
381 return DoStatAny(st
, fn
.GetFullPath(), &fn
);
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 // Flags for wxFileSystemObjectExists() asking it to check for:
650 wxFileSystemObject_File
= 1, // file existence
651 wxFileSystemObject_Dir
= 2, // directory existence
652 wxFileSystemObject_Other
= 4, // existence of something else, e.g.
653 // device, socket, FIFO under Unix
654 wxFileSystemObject_Any
= 7 // existence of anything at all
657 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
659 void RemoveTrailingSeparatorsFromPath(wxString
& strPath
)
661 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
662 // so remove all trailing backslashes from the path - but don't do this for
663 // the paths "d:\" (which are different from "d:"), for just "\" or for
664 // windows unique volume names ("\\?\Volume{GUID}\")
665 while ( wxEndsWithPathSeparator( strPath
) )
667 size_t len
= strPath
.length();
668 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) ||
669 (len
== wxMSWUniqueVolumePrefixLength
&&
670 wxFileName::IsMSWUniqueVolumeNamePath(strPath
)))
675 strPath
.Truncate(len
- 1);
679 #endif // __WINDOWS__ || __OS2__
682 wxFileSystemObjectExists(const wxString
& path
, int flags
,
683 const wxFileName
* fn
= NULL
)
685 wxUnusedVar(fn
); // It's only used under Unix
687 // Should the existence of file/directory with this name be accepted, i.e.
688 // result in the true return value from this function?
689 const bool acceptFile
= (flags
& wxFileSystemObject_File
) != 0;
690 const bool acceptDir
= (flags
& wxFileSystemObject_Dir
) != 0;
692 wxString
strPath(path
);
694 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
697 // Ensure that the path doesn't have any trailing separators when
698 // checking for directories.
699 RemoveTrailingSeparatorsFromPath(strPath
);
702 // we must use GetFileAttributes() instead of the ANSI C functions because
703 // it can cope with network (UNC) paths unlike them
704 DWORD ret
= ::GetFileAttributes(strPath
.t_str());
706 if ( ret
== INVALID_FILE_ATTRIBUTES
)
709 if ( ret
& FILE_ATTRIBUTE_DIRECTORY
)
712 // Anything else must be a file (perhaps we should check for
713 // FILE_ATTRIBUTE_REPARSE_POINT?)
715 #elif defined(__OS2__)
718 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
719 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
723 FILESTATUS3 Info
= {{0}};
724 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
725 (void*) &Info
, sizeof(FILESTATUS3
));
727 if ( rc
== NO_ERROR
)
729 if ( Info
.attrFile
& FILE_DIRECTORY
)
735 // We consider that the path must exist if we get a sharing violation for
736 // it but we don't know what is it in this case.
737 if ( rc
== ERROR_SHARING_VIOLATION
)
738 return flags
& wxFileSystemObject_Other
;
740 // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
743 #else // Non-MSW, non-OS/2
745 if ( !DoStatAny(st
, strPath
, fn
) )
748 if ( S_ISREG(st
.st_mode
) )
750 if ( S_ISDIR(st
.st_mode
) )
753 return flags
& wxFileSystemObject_Other
;
757 } // anonymous namespace
759 bool wxFileName::FileExists() const
761 return wxFileSystemObjectExists(GetFullPath(), wxFileSystemObject_File
, this);
765 bool wxFileName::FileExists( const wxString
&filePath
)
767 return wxFileSystemObjectExists(filePath
, wxFileSystemObject_File
);
770 bool wxFileName::DirExists() const
772 return wxFileSystemObjectExists(GetPath(), wxFileSystemObject_Dir
, this);
776 bool wxFileName::DirExists( const wxString
&dirPath
)
778 return wxFileSystemObjectExists(dirPath
, wxFileSystemObject_Dir
);
781 bool wxFileName::Exists() const
783 return wxFileSystemObjectExists(GetFullPath(), wxFileSystemObject_Any
, this);
787 bool wxFileName::Exists(const wxString
& path
)
789 return wxFileSystemObjectExists(path
, wxFileSystemObject_Any
);
792 // ----------------------------------------------------------------------------
793 // CWD and HOME stuff
794 // ----------------------------------------------------------------------------
796 void wxFileName::AssignCwd(const wxString
& volume
)
798 AssignDir(wxFileName::GetCwd(volume
));
802 wxString
wxFileName::GetCwd(const wxString
& volume
)
804 // if we have the volume, we must get the current directory on this drive
805 // and to do this we have to chdir to this volume - at least under Windows,
806 // I don't know how to get the current drive on another volume elsewhere
809 if ( !volume
.empty() )
812 SetCwd(volume
+ GetVolumeSeparator());
815 wxString cwd
= ::wxGetCwd();
817 if ( !volume
.empty() )
825 bool wxFileName::SetCwd() const
827 return wxFileName::SetCwd( GetPath() );
830 bool wxFileName::SetCwd( const wxString
&cwd
)
832 return ::wxSetWorkingDirectory( cwd
);
835 void wxFileName::AssignHomeDir()
837 AssignDir(wxFileName::GetHomeDir());
840 wxString
wxFileName::GetHomeDir()
842 return ::wxGetHomeDir();
846 // ----------------------------------------------------------------------------
847 // CreateTempFileName
848 // ----------------------------------------------------------------------------
850 #if wxUSE_FILE || wxUSE_FFILE
853 #if !defined wx_fdopen && defined HAVE_FDOPEN
854 #define wx_fdopen fdopen
857 // NB: GetTempFileName() under Windows creates the file, so using
858 // O_EXCL there would fail
860 #define wxOPEN_EXCL 0
862 #define wxOPEN_EXCL O_EXCL
866 #ifdef wxOpenOSFHandle
867 #define WX_HAVE_DELETE_ON_CLOSE
868 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
870 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
872 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
874 DWORD disposition
= OPEN_ALWAYS
;
876 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
877 FILE_FLAG_DELETE_ON_CLOSE
;
879 HANDLE h
= ::CreateFile(filename
.t_str(), access
, 0, NULL
,
880 disposition
, attributes
, NULL
);
882 return wxOpenOSFHandle(h
, wxO_BINARY
);
884 #endif // wxOpenOSFHandle
887 // Helper to open the file
889 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
891 #ifdef WX_HAVE_DELETE_ON_CLOSE
893 return wxOpenWithDeleteOnClose(path
);
896 *deleteOnClose
= false;
898 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
903 // Helper to open the file and attach it to the wxFFile
905 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
908 *deleteOnClose
= false;
909 return file
->Open(path
, wxT("w+b"));
911 int fd
= wxTempOpen(path
, deleteOnClose
);
914 file
->Attach(wx_fdopen(fd
, "w+b"), path
);
915 return file
->IsOpened();
918 #endif // wxUSE_FFILE
922 #define WXFILEARGS(x, y) y
924 #define WXFILEARGS(x, y) x
926 #define WXFILEARGS(x, y) x, y
930 // Implementation of wxFileName::CreateTempFileName().
932 static wxString
wxCreateTempImpl(
933 const wxString
& prefix
,
934 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
935 bool *deleteOnClose
= NULL
)
937 #if wxUSE_FILE && wxUSE_FFILE
938 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
940 wxString path
, dir
, name
;
941 bool wantDeleteOnClose
= false;
945 // set the result to false initially
946 wantDeleteOnClose
= *deleteOnClose
;
947 *deleteOnClose
= false;
951 // easier if it alwasys points to something
952 deleteOnClose
= &wantDeleteOnClose
;
955 // use the directory specified by the prefix
956 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
960 dir
= wxFileName::GetTempDir();
963 #if defined(__WXWINCE__)
964 path
= dir
+ wxT("\\") + name
;
966 while (wxFileName::FileExists(path
))
968 path
= dir
+ wxT("\\") + name
;
973 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
974 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
975 wxStringBuffer(path
, MAX_PATH
+ 1)))
977 wxLogLastError(wxT("GetTempFileName"));
985 if ( !wxEndsWithPathSeparator(dir
) &&
986 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
988 path
+= wxFILE_SEP_PATH
;
993 #if defined(HAVE_MKSTEMP)
994 // scratch space for mkstemp()
995 path
+= wxT("XXXXXX");
997 // we need to copy the path to the buffer in which mkstemp() can modify it
998 wxCharBuffer
buf(path
.fn_str());
1000 // cast is safe because the string length doesn't change
1001 int fdTemp
= mkstemp( (char*)(const char*) buf
);
1004 // this might be not necessary as mkstemp() on most systems should have
1005 // already done it but it doesn't hurt neither...
1008 else // mkstemp() succeeded
1010 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1013 // avoid leaking the fd
1016 fileTemp
->Attach(fdTemp
);
1025 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"), path
);
1027 ffileTemp
->Open(path
, wxT("r+b"));
1038 #else // !HAVE_MKSTEMP
1042 path
+= wxT("XXXXXX");
1044 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
1045 if ( !mktemp( (char*)(const char*) buf
) )
1051 path
= wxConvFile
.cMB2WX( (const char*) buf
);
1053 #else // !HAVE_MKTEMP (includes __DOS__)
1054 // generate the unique file name ourselves
1055 #if !defined(__DOS__)
1056 path
<< (unsigned int)getpid();
1061 static const size_t numTries
= 1000;
1062 for ( size_t n
= 0; n
< numTries
; n
++ )
1064 // 3 hex digits is enough for numTries == 1000 < 4096
1065 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
1066 if ( !wxFileName::FileExists(pathTry
) )
1075 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1077 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1079 #endif // Windows/!Windows
1083 wxLogSysError(_("Failed to create a temporary file name"));
1089 // open the file - of course, there is a race condition here, this is
1090 // why we always prefer using mkstemp()...
1092 if ( fileTemp
&& !fileTemp
->IsOpened() )
1094 *deleteOnClose
= wantDeleteOnClose
;
1095 int fd
= wxTempOpen(path
, deleteOnClose
);
1097 fileTemp
->Attach(fd
);
1104 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1106 *deleteOnClose
= wantDeleteOnClose
;
1107 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1113 // FIXME: If !ok here should we loop and try again with another
1114 // file name? That is the standard recourse if open(O_EXCL)
1115 // fails, though of course it should be protected against
1116 // possible infinite looping too.
1118 wxLogError(_("Failed to open temporary file."));
1128 static bool wxCreateTempImpl(
1129 const wxString
& prefix
,
1130 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1133 bool deleteOnClose
= true;
1135 *name
= wxCreateTempImpl(prefix
,
1136 WXFILEARGS(fileTemp
, ffileTemp
),
1139 bool ok
= !name
->empty();
1144 else if (ok
&& wxRemoveFile(*name
))
1152 static void wxAssignTempImpl(
1154 const wxString
& prefix
,
1155 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1158 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1160 if ( tempname
.empty() )
1162 // error, failed to get temp file name
1167 fn
->Assign(tempname
);
1172 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1174 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1178 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1180 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1183 #endif // wxUSE_FILE || wxUSE_FFILE
1188 wxString
wxCreateTempFileName(const wxString
& prefix
,
1190 bool *deleteOnClose
)
1192 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1195 bool wxCreateTempFile(const wxString
& prefix
,
1199 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1202 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1204 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1209 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1211 return wxCreateTempFileName(prefix
, fileTemp
);
1214 #endif // wxUSE_FILE
1219 wxString
wxCreateTempFileName(const wxString
& prefix
,
1221 bool *deleteOnClose
)
1223 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1226 bool wxCreateTempFile(const wxString
& prefix
,
1230 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1234 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1236 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1241 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1243 return wxCreateTempFileName(prefix
, fileTemp
);
1246 #endif // wxUSE_FFILE
1249 // ----------------------------------------------------------------------------
1250 // directory operations
1251 // ----------------------------------------------------------------------------
1253 // helper of GetTempDir(): check if the given directory exists and return it if
1254 // it does or an empty string otherwise
1258 wxString
CheckIfDirExists(const wxString
& dir
)
1260 return wxFileName::DirExists(dir
) ? dir
: wxString();
1263 } // anonymous namespace
1265 wxString
wxFileName::GetTempDir()
1267 // first try getting it from environment: this allows overriding the values
1268 // used by default if the user wants to create temporary files in another
1270 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1273 dir
= CheckIfDirExists(wxGetenv("TMP"));
1275 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1278 // if no environment variables are set, use the system default
1281 #if defined(__WXWINCE__)
1282 dir
= CheckIfDirExists(wxT("\\temp"));
1283 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1284 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1286 wxLogLastError(wxT("GetTempPath"));
1288 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1289 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1290 #endif // systems with native way
1292 else // we got directory from an environment variable
1294 // remove any trailing path separators, we don't want to ever return
1295 // them from this function for consistency
1296 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1297 if ( lastNonSep
== wxString::npos
)
1299 // the string consists entirely of separators, leave only one
1300 dir
= GetPathSeparator();
1304 dir
.erase(lastNonSep
+ 1);
1308 // fall back to hard coded value
1311 #ifdef __UNIX_LIKE__
1312 dir
= CheckIfDirExists("/tmp");
1314 #endif // __UNIX_LIKE__
1321 bool wxFileName::Mkdir( int perm
, int flags
) const
1323 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1326 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1328 if ( flags
& wxPATH_MKDIR_FULL
)
1330 // split the path in components
1331 wxFileName filename
;
1332 filename
.AssignDir(dir
);
1335 if ( filename
.HasVolume())
1337 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1340 wxArrayString dirs
= filename
.GetDirs();
1341 size_t count
= dirs
.GetCount();
1342 for ( size_t i
= 0; i
< count
; i
++ )
1344 if ( i
> 0 || filename
.IsAbsolute() )
1345 currPath
+= wxFILE_SEP_PATH
;
1346 currPath
+= dirs
[i
];
1348 if (!DirExists(currPath
))
1350 if (!wxMkdir(currPath
, perm
))
1352 // no need to try creating further directories
1362 return ::wxMkdir( dir
, perm
);
1365 bool wxFileName::Rmdir(int flags
) const
1367 return wxFileName::Rmdir( GetPath(), flags
);
1370 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1373 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1375 // SHFileOperation needs double null termination string
1376 // but without separator at the end of the path
1378 if ( path
.Last() == wxFILE_SEP_PATH
)
1382 SHFILEOPSTRUCT fileop
;
1383 wxZeroMemory(fileop
);
1384 fileop
.wFunc
= FO_DELETE
;
1385 fileop
.pFrom
= path
.t_str();
1386 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1388 // FOF_NOERRORUI is not defined in WinCE
1389 fileop
.fFlags
|= FOF_NOERRORUI
;
1392 int ret
= SHFileOperation(&fileop
);
1395 // SHFileOperation may return non-Win32 error codes, so the error
1396 // message can be incorrect
1397 wxLogApiError(wxT("SHFileOperation"), ret
);
1403 else if ( flags
& wxPATH_RMDIR_FULL
)
1404 #else // !__WINDOWS__
1405 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1406 #endif // !__WINDOWS__
1409 if ( path
.Last() != wxFILE_SEP_PATH
)
1410 path
+= wxFILE_SEP_PATH
;
1414 if ( !d
.IsOpened() )
1419 // first delete all subdirectories
1420 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1423 wxFileName::Rmdir(path
+ filename
, flags
);
1424 cont
= d
.GetNext(&filename
);
1428 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1430 // delete all files too
1431 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1434 ::wxRemoveFile(path
+ filename
);
1435 cont
= d
.GetNext(&filename
);
1438 #endif // !__WINDOWS__
1441 return ::wxRmdir(dir
);
1444 // ----------------------------------------------------------------------------
1445 // path normalization
1446 // ----------------------------------------------------------------------------
1448 bool wxFileName::Normalize(int flags
,
1449 const wxString
& cwd
,
1450 wxPathFormat format
)
1452 // deal with env vars renaming first as this may seriously change the path
1453 if ( flags
& wxPATH_NORM_ENV_VARS
)
1455 wxString pathOrig
= GetFullPath(format
);
1456 wxString path
= wxExpandEnvVars(pathOrig
);
1457 if ( path
!= pathOrig
)
1463 // the existing path components
1464 wxArrayString dirs
= GetDirs();
1466 // the path to prepend in front to make the path absolute
1469 format
= GetFormat(format
);
1471 // set up the directory to use for making the path absolute later
1472 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1476 curDir
.AssignCwd(GetVolume());
1478 else // cwd provided
1480 curDir
.AssignDir(cwd
);
1484 // handle ~ stuff under Unix only
1485 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1487 if ( !dirs
.IsEmpty() )
1489 wxString dir
= dirs
[0u];
1490 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1492 // to make the path absolute use the home directory
1493 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1499 // transform relative path into abs one
1500 if ( curDir
.IsOk() )
1502 // this path may be relative because it doesn't have the volume name
1503 // and still have m_relative=true; in this case we shouldn't modify
1504 // our directory components but just set the current volume
1505 if ( !HasVolume() && curDir
.HasVolume() )
1507 SetVolume(curDir
.GetVolume());
1511 // yes, it was the case - we don't need curDir then
1516 // finally, prepend curDir to the dirs array
1517 wxArrayString dirsNew
= curDir
.GetDirs();
1518 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1520 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1521 // return for some reason an absolute path, then curDir maybe not be absolute!
1522 if ( !curDir
.m_relative
)
1524 // we have prepended an absolute path and thus we are now an absolute
1528 // else if (flags & wxPATH_NORM_ABSOLUTE):
1529 // should we warn the user that we didn't manage to make the path absolute?
1532 // now deal with ".", ".." and the rest
1534 size_t count
= dirs
.GetCount();
1535 for ( size_t n
= 0; n
< count
; n
++ )
1537 wxString dir
= dirs
[n
];
1539 if ( flags
& wxPATH_NORM_DOTS
)
1541 if ( dir
== wxT(".") )
1547 if ( dir
== wxT("..") )
1549 if ( m_dirs
.empty() )
1551 // We have more ".." than directory components so far.
1552 // Don't treat this as an error as the path could have been
1553 // entered by user so try to handle it reasonably: if the
1554 // path is absolute, just ignore the extra ".." because
1555 // "/.." is the same as "/". Otherwise, i.e. for relative
1556 // paths, keep ".." unchanged because removing it would
1557 // modify the file a relative path refers to.
1562 else // Normal case, go one step up.
1573 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1574 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1577 if (GetShortcutTarget(GetFullPath(format
), filename
))
1585 #if defined(__WIN32__)
1586 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1588 Assign(GetLongPath());
1592 // Change case (this should be kept at the end of the function, to ensure
1593 // that the path doesn't change any more after we normalize its case)
1594 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1596 m_volume
.MakeLower();
1600 // directory entries must be made lower case as well
1601 count
= m_dirs
.GetCount();
1602 for ( size_t i
= 0; i
< count
; i
++ )
1604 m_dirs
[i
].MakeLower();
1612 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1613 const wxString
& replacementFmtString
,
1614 wxPathFormat format
)
1616 // look into stringForm for the contents of the given environment variable
1618 if (envname
.empty() ||
1619 !wxGetEnv(envname
, &val
))
1624 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1625 // do not touch the file name and the extension
1627 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1628 stringForm
.Replace(val
, replacement
);
1630 // Now assign ourselves the modified path:
1631 Assign(stringForm
, GetFullName(), format
);
1637 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1639 wxString homedir
= wxGetHomeDir();
1640 if (homedir
.empty())
1643 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1644 // do not touch the file name and the extension
1646 stringForm
.Replace(homedir
, "~");
1648 // Now assign ourselves the modified path:
1649 Assign(stringForm
, GetFullName(), format
);
1654 // ----------------------------------------------------------------------------
1655 // get the shortcut target
1656 // ----------------------------------------------------------------------------
1658 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1659 // The .lnk file is a plain text file so it should be easy to
1660 // make it work. Hint from Google Groups:
1661 // "If you open up a lnk file, you'll see a
1662 // number, followed by a pound sign (#), followed by more text. The
1663 // number is the number of characters that follows the pound sign. The
1664 // characters after the pound sign are the command line (which _can_
1665 // include arguments) to be executed. Any path (e.g. \windows\program
1666 // files\myapp.exe) that includes spaces needs to be enclosed in
1667 // quotation marks."
1669 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1670 // The following lines are necessary under WinCE
1671 // #include "wx/msw/private.h"
1672 // #include <ole2.h>
1674 #if defined(__WXWINCE__)
1675 #include <shlguid.h>
1678 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1679 wxString
& targetFilename
,
1680 wxString
* arguments
) const
1682 wxString path
, file
, ext
;
1683 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1687 bool success
= false;
1689 // Assume it's not a shortcut if it doesn't end with lnk
1690 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1693 // create a ShellLink object
1694 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1695 IID_IShellLink
, (LPVOID
*) &psl
);
1697 if (SUCCEEDED(hres
))
1700 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1701 if (SUCCEEDED(hres
))
1703 WCHAR wsz
[MAX_PATH
];
1705 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1708 hres
= ppf
->Load(wsz
, 0);
1711 if (SUCCEEDED(hres
))
1714 // Wrong prototype in early versions
1715 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1716 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1718 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1720 targetFilename
= wxString(buf
);
1721 success
= (shortcutPath
!= targetFilename
);
1723 psl
->GetArguments(buf
, 2048);
1725 if (!args
.empty() && arguments
)
1737 #endif // __WIN32__ && !__WXWINCE__
1740 // ----------------------------------------------------------------------------
1741 // absolute/relative paths
1742 // ----------------------------------------------------------------------------
1744 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1746 // unix paths beginning with ~ are reported as being absolute
1747 if ( format
== wxPATH_UNIX
)
1749 if ( !m_dirs
.IsEmpty() )
1751 wxString dir
= m_dirs
[0u];
1753 if (!dir
.empty() && dir
[0u] == wxT('~'))
1758 // if our path doesn't start with a path separator, it's not an absolute
1763 if ( !GetVolumeSeparator(format
).empty() )
1765 // this format has volumes and an absolute path must have one, it's not
1766 // enough to have the full path to be an absolute file under Windows
1767 if ( GetVolume().empty() )
1774 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1776 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1778 // get cwd only once - small time saving
1779 wxString cwd
= wxGetCwd();
1780 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1781 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1783 bool withCase
= IsCaseSensitive(format
);
1785 // we can't do anything if the files live on different volumes
1786 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1792 // same drive, so we don't need our volume
1795 // remove common directories starting at the top
1796 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1797 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1800 fnBase
.m_dirs
.RemoveAt(0);
1803 // add as many ".." as needed
1804 size_t count
= fnBase
.m_dirs
.GetCount();
1805 for ( size_t i
= 0; i
< count
; i
++ )
1807 m_dirs
.Insert(wxT(".."), 0u);
1810 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1812 // a directory made relative with respect to itself is '.' under Unix
1813 // and DOS, by definition (but we don't have to insert "./" for the
1815 if ( m_dirs
.IsEmpty() && IsDir() )
1817 m_dirs
.Add(wxT('.'));
1827 // ----------------------------------------------------------------------------
1828 // filename kind tests
1829 // ----------------------------------------------------------------------------
1831 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1833 wxFileName fn1
= *this,
1836 // get cwd only once - small time saving
1837 wxString cwd
= wxGetCwd();
1838 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1839 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1841 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1844 #if defined(__UNIX__)
1845 wxStructStat st1
, st2
;
1846 if ( StatAny(st1
, fn1
) && StatAny(st2
, fn2
) )
1848 if ( st1
.st_ino
== st2
.st_ino
&& st1
.st_dev
== st2
.st_dev
)
1851 //else: It's not an error if one or both files don't exist.
1852 #endif // defined __UNIX__
1858 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1860 // only Unix filenames are truly case-sensitive
1861 return GetFormat(format
) == wxPATH_UNIX
;
1865 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1867 // Inits to forbidden characters that are common to (almost) all platforms.
1868 wxString strForbiddenChars
= wxT("*?");
1870 // If asserts, wxPathFormat has been changed. In case of a new path format
1871 // addition, the following code might have to be updated.
1872 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1873 switch ( GetFormat(format
) )
1876 wxFAIL_MSG( wxT("Unknown path format") );
1877 // !! Fall through !!
1883 // On a Mac even names with * and ? are allowed (Tested with OS
1884 // 9.2.1 and OS X 10.2.5)
1885 strForbiddenChars
= wxEmptyString
;
1889 strForbiddenChars
+= wxT("\\/:\"<>|");
1896 return strForbiddenChars
;
1900 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1903 return wxEmptyString
;
1907 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1908 (GetFormat(format
) == wxPATH_VMS
) )
1910 sepVol
= wxFILE_SEP_DSK
;
1919 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1922 switch ( GetFormat(format
) )
1925 // accept both as native APIs do but put the native one first as
1926 // this is the one we use in GetFullPath()
1927 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1931 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1935 seps
= wxFILE_SEP_PATH_UNIX
;
1939 seps
= wxFILE_SEP_PATH_MAC
;
1943 seps
= wxFILE_SEP_PATH_VMS
;
1951 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1953 format
= GetFormat(format
);
1955 // under VMS the end of the path is ']', not the path separator used to
1956 // separate the components
1957 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1961 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1963 // wxString::Find() doesn't work as expected with NUL - it will always find
1964 // it, so test for it separately
1965 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1970 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
1972 // return true if the format used is the DOS/Windows one and the string begins
1973 // with a Windows unique volume name ("\\?\Volume{guid}\")
1974 return format
== wxPATH_DOS
&&
1975 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
1976 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
1977 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
1980 // ----------------------------------------------------------------------------
1981 // path components manipulation
1982 // ----------------------------------------------------------------------------
1984 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1988 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1993 const size_t len
= dir
.length();
1994 for ( size_t n
= 0; n
< len
; n
++ )
1996 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1998 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
2007 void wxFileName::AppendDir( const wxString
& dir
)
2009 if ( IsValidDirComponent(dir
) )
2013 void wxFileName::PrependDir( const wxString
& dir
)
2018 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
2020 if ( IsValidDirComponent(dir
) )
2021 m_dirs
.Insert(dir
, before
);
2024 void wxFileName::RemoveDir(size_t pos
)
2026 m_dirs
.RemoveAt(pos
);
2029 // ----------------------------------------------------------------------------
2031 // ----------------------------------------------------------------------------
2033 void wxFileName::SetFullName(const wxString
& fullname
)
2035 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
2036 &m_name
, &m_ext
, &m_hasExt
);
2039 wxString
wxFileName::GetFullName() const
2041 wxString fullname
= m_name
;
2044 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
2050 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
2052 format
= GetFormat( format
);
2056 // return the volume with the path as well if requested
2057 if ( flags
& wxPATH_GET_VOLUME
)
2059 fullpath
+= wxGetVolumeString(GetVolume(), format
);
2062 // the leading character
2067 fullpath
+= wxFILE_SEP_PATH_MAC
;
2072 fullpath
+= wxFILE_SEP_PATH_DOS
;
2076 wxFAIL_MSG( wxT("Unknown path format") );
2082 fullpath
+= wxFILE_SEP_PATH_UNIX
;
2087 // no leading character here but use this place to unset
2088 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2089 // as, if I understand correctly, there should never be a dot
2090 // before the closing bracket
2091 flags
&= ~wxPATH_GET_SEPARATOR
;
2094 if ( m_dirs
.empty() )
2096 // there is nothing more
2100 // then concatenate all the path components using the path separator
2101 if ( format
== wxPATH_VMS
)
2103 fullpath
+= wxT('[');
2106 const size_t dirCount
= m_dirs
.GetCount();
2107 for ( size_t i
= 0; i
< dirCount
; i
++ )
2112 if ( m_dirs
[i
] == wxT(".") )
2114 // skip appending ':', this shouldn't be done in this
2115 // case as "::" is interpreted as ".." under Unix
2119 // convert back from ".." to nothing
2120 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2121 fullpath
+= m_dirs
[i
];
2125 wxFAIL_MSG( wxT("Unexpected path format") );
2126 // still fall through
2130 fullpath
+= m_dirs
[i
];
2134 // TODO: What to do with ".." under VMS
2136 // convert back from ".." to nothing
2137 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2138 fullpath
+= m_dirs
[i
];
2142 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2143 fullpath
+= GetPathSeparator(format
);
2146 if ( format
== wxPATH_VMS
)
2148 fullpath
+= wxT(']');
2154 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2156 // we already have a function to get the path
2157 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2160 // now just add the file name and extension to it
2161 fullpath
+= GetFullName();
2166 // Return the short form of the path (returns identity on non-Windows platforms)
2167 wxString
wxFileName::GetShortPath() const
2169 wxString
path(GetFullPath());
2171 #if defined(__WINDOWS__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2172 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2176 if ( ::GetShortPathName
2179 wxStringBuffer(pathOut
, sz
),
2191 // Return the long form of the path (returns identity on non-Windows platforms)
2192 wxString
wxFileName::GetLongPath() const
2195 path
= GetFullPath();
2197 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2199 #if wxUSE_DYNLIB_CLASS
2200 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2202 // this is MT-safe as in the worst case we're going to resolve the function
2203 // twice -- but as the result is the same in both threads, it's ok
2204 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2205 if ( !s_pfnGetLongPathName
)
2207 static bool s_triedToLoad
= false;
2209 if ( !s_triedToLoad
)
2211 s_triedToLoad
= true;
2213 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2215 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2220 #endif // Unicode/ANSI
2222 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2224 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2225 dllKernel
.GetSymbol(GetLongPathName
);
2228 // note that kernel32.dll can be unloaded, it stays in memory
2229 // anyhow as all Win32 programs link to it and so it's safe to call
2230 // GetLongPathName() even after unloading it
2234 if ( s_pfnGetLongPathName
)
2236 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2239 if ( (*s_pfnGetLongPathName
)
2242 wxStringBuffer(pathOut
, dwSize
),
2250 #endif // wxUSE_DYNLIB_CLASS
2252 // The OS didn't support GetLongPathName, or some other error.
2253 // We need to call FindFirstFile on each component in turn.
2255 WIN32_FIND_DATA findFileData
;
2259 pathOut
= GetVolume() +
2260 GetVolumeSeparator(wxPATH_DOS
) +
2261 GetPathSeparator(wxPATH_DOS
);
2263 pathOut
= wxEmptyString
;
2265 wxArrayString dirs
= GetDirs();
2266 dirs
.Add(GetFullName());
2270 size_t count
= dirs
.GetCount();
2271 for ( size_t i
= 0; i
< count
; i
++ )
2273 const wxString
& dir
= dirs
[i
];
2275 // We're using pathOut to collect the long-name path, but using a
2276 // temporary for appending the last path component which may be
2278 tmpPath
= pathOut
+ dir
;
2280 // We must not process "." or ".." here as they would be (unexpectedly)
2281 // replaced by the corresponding directory names so just leave them
2284 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2285 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2286 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2288 tmpPath
+= wxFILE_SEP_PATH
;
2293 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2294 if (hFind
== INVALID_HANDLE_VALUE
)
2296 // Error: most likely reason is that path doesn't exist, so
2297 // append any unprocessed parts and return
2298 for ( i
+= 1; i
< count
; i
++ )
2299 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2304 pathOut
+= findFileData
.cFileName
;
2305 if ( (i
< (count
-1)) )
2306 pathOut
+= wxFILE_SEP_PATH
;
2312 #endif // Win32/!Win32
2317 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2319 if (format
== wxPATH_NATIVE
)
2321 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__)
2322 format
= wxPATH_DOS
;
2323 #elif defined(__VMS)
2324 format
= wxPATH_VMS
;
2326 format
= wxPATH_UNIX
;
2332 #ifdef wxHAS_FILESYSTEM_VOLUMES
2335 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2337 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2339 wxString
vol(drive
);
2340 vol
+= wxFILE_SEP_DSK
;
2341 if ( flags
& wxPATH_GET_SEPARATOR
)
2342 vol
+= wxFILE_SEP_PATH
;
2347 #endif // wxHAS_FILESYSTEM_VOLUMES
2349 // ----------------------------------------------------------------------------
2350 // path splitting function
2351 // ----------------------------------------------------------------------------
2355 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2356 wxString
*pstrVolume
,
2358 wxPathFormat format
)
2360 format
= GetFormat(format
);
2362 wxString fullpath
= fullpathWithVolume
;
2364 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2366 // special Windows unique volume names hack: transform
2367 // \\?\Volume{guid}\path into Volume{guid}:path
2368 // note: this check must be done before the check for UNC path
2370 // we know the last backslash from the unique volume name is located
2371 // there from IsMSWUniqueVolumeNamePath
2372 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2374 // paths starting with a unique volume name should always be absolute
2375 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2377 // remove the leading "\\?\" part
2378 fullpath
.erase(0, 4);
2380 else if ( IsUNCPath(fullpath
, format
) )
2382 // special Windows UNC paths hack: transform \\share\path into share:path
2384 fullpath
.erase(0, 2);
2386 size_t posFirstSlash
=
2387 fullpath
.find_first_of(GetPathTerminators(format
));
2388 if ( posFirstSlash
!= wxString::npos
)
2390 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2392 // UNC paths are always absolute, right? (FIXME)
2393 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2397 // We separate the volume here
2398 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2400 wxString sepVol
= GetVolumeSeparator(format
);
2402 // we have to exclude the case of a colon in the very beginning of the
2403 // string as it can't be a volume separator (nor can this be a valid
2404 // DOS file name at all but we'll leave dealing with this to our caller)
2405 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2406 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2410 *pstrVolume
= fullpath
.Left(posFirstColon
);
2413 // remove the volume name and the separator from the full path
2414 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2419 *pstrPath
= fullpath
;
2423 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2424 wxString
*pstrVolume
,
2429 wxPathFormat format
)
2431 format
= GetFormat(format
);
2434 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2436 // find the positions of the last dot and last path separator in the path
2437 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2438 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2440 // check whether this dot occurs at the very beginning of a path component
2441 if ( (posLastDot
!= wxString::npos
) &&
2443 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2444 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2446 // dot may be (and commonly -- at least under Unix -- is) the first
2447 // character of the filename, don't treat the entire filename as
2448 // extension in this case
2449 posLastDot
= wxString::npos
;
2452 // if we do have a dot and a slash, check that the dot is in the name part
2453 if ( (posLastDot
!= wxString::npos
) &&
2454 (posLastSlash
!= wxString::npos
) &&
2455 (posLastDot
< posLastSlash
) )
2457 // the dot is part of the path, not the start of the extension
2458 posLastDot
= wxString::npos
;
2461 // now fill in the variables provided by user
2464 if ( posLastSlash
== wxString::npos
)
2471 // take everything up to the path separator but take care to make
2472 // the path equal to something like '/', not empty, for the files
2473 // immediately under root directory
2474 size_t len
= posLastSlash
;
2476 // this rule does not apply to mac since we do not start with colons (sep)
2477 // except for relative paths
2478 if ( !len
&& format
!= wxPATH_MAC
)
2481 *pstrPath
= fullpath
.Left(len
);
2483 // special VMS hack: remove the initial bracket
2484 if ( format
== wxPATH_VMS
)
2486 if ( (*pstrPath
)[0u] == wxT('[') )
2487 pstrPath
->erase(0, 1);
2494 // take all characters starting from the one after the last slash and
2495 // up to, but excluding, the last dot
2496 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2498 if ( posLastDot
== wxString::npos
)
2500 // take all until the end
2501 count
= wxString::npos
;
2503 else if ( posLastSlash
== wxString::npos
)
2507 else // have both dot and slash
2509 count
= posLastDot
- posLastSlash
- 1;
2512 *pstrName
= fullpath
.Mid(nStart
, count
);
2515 // finally deal with the extension here: we have an added complication that
2516 // extension may be empty (but present) as in "foo." where trailing dot
2517 // indicates the empty extension at the end -- and hence we must remember
2518 // that we have it independently of pstrExt
2519 if ( posLastDot
== wxString::npos
)
2529 // take everything after the dot
2531 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2538 void wxFileName::SplitPath(const wxString
& fullpath
,
2542 wxPathFormat format
)
2545 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2549 path
->Prepend(wxGetVolumeString(volume
, format
));
2554 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2556 wxFileName
fn(fullpath
);
2558 return fn
.GetFullPath();
2561 // ----------------------------------------------------------------------------
2563 // ----------------------------------------------------------------------------
2567 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2568 const wxDateTime
*dtMod
,
2569 const wxDateTime
*dtCreate
) const
2571 #if defined(__WIN32__)
2572 FILETIME ftAccess
, ftCreate
, ftWrite
;
2575 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2577 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2579 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2585 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2587 wxLogError(_("Setting directory access times is not supported "
2588 "under this OS version"));
2593 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2597 path
= GetFullPath();
2601 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2604 if ( ::SetFileTime(fh
,
2605 dtCreate
? &ftCreate
: NULL
,
2606 dtAccess
? &ftAccess
: NULL
,
2607 dtMod
? &ftWrite
: NULL
) )
2612 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2613 wxUnusedVar(dtCreate
);
2615 if ( !dtAccess
&& !dtMod
)
2617 // can't modify the creation time anyhow, don't try
2621 // if dtAccess or dtMod is not specified, use the other one (which must be
2622 // non NULL because of the test above) for both times
2624 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2625 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2626 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2630 #else // other platform
2631 wxUnusedVar(dtAccess
);
2633 wxUnusedVar(dtCreate
);
2636 wxLogSysError(_("Failed to modify file times for '%s'"),
2637 GetFullPath().c_str());
2642 bool wxFileName::Touch() const
2644 #if defined(__UNIX_LIKE__)
2645 // under Unix touching file is simple: just pass NULL to utime()
2646 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2651 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2654 #else // other platform
2655 wxDateTime dtNow
= wxDateTime::Now();
2657 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2661 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2663 wxDateTime
*dtCreate
) const
2665 #if defined(__WIN32__)
2666 // we must use different methods for the files and directories under
2667 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2668 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2671 FILETIME ftAccess
, ftCreate
, ftWrite
;
2674 // implemented in msw/dir.cpp
2675 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2676 FILETIME
*, FILETIME
*, FILETIME
*);
2678 // we should pass the path without the trailing separator to
2679 // wxGetDirectoryTimes()
2680 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2681 &ftAccess
, &ftCreate
, &ftWrite
);
2685 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2688 ok
= ::GetFileTime(fh
,
2689 dtCreate
? &ftCreate
: NULL
,
2690 dtAccess
? &ftAccess
: NULL
,
2691 dtMod
? &ftWrite
: NULL
) != 0;
2702 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2704 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2706 ConvertFileTimeToWx(dtMod
, ftWrite
);
2710 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2711 // no need to test for IsDir() here
2713 if ( StatAny(stBuf
, *this) )
2715 // Android defines st_*time fields as unsigned long, but time_t as long,
2716 // hence the static_casts.
2718 dtAccess
->Set(static_cast<time_t>(stBuf
.st_atime
));
2720 dtMod
->Set(static_cast<time_t>(stBuf
.st_mtime
));
2722 dtCreate
->Set(static_cast<time_t>(stBuf
.st_ctime
));
2726 #else // other platform
2727 wxUnusedVar(dtAccess
);
2729 wxUnusedVar(dtCreate
);
2732 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2733 GetFullPath().c_str());
2738 #endif // wxUSE_DATETIME
2741 // ----------------------------------------------------------------------------
2742 // file size functions
2743 // ----------------------------------------------------------------------------
2748 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2750 if (!wxFileExists(filename
))
2751 return wxInvalidSize
;
2753 #if defined(__WIN32__)
2754 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2756 return wxInvalidSize
;
2758 DWORD lpFileSizeHigh
;
2759 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2760 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2761 return wxInvalidSize
;
2763 return wxULongLong(lpFileSizeHigh
, ret
);
2764 #else // ! __WIN32__
2766 if (wxStat( filename
, &st
) != 0)
2767 return wxInvalidSize
;
2768 return wxULongLong(st
.st_size
);
2773 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2774 const wxString
&nullsize
,
2776 wxSizeConvention conv
)
2778 // deal with trivial case first
2779 if ( bs
== 0 || bs
== wxInvalidSize
)
2782 // depending on the convention used the multiplier may be either 1000 or
2783 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2784 double multiplier
= 1024.;
2789 case wxSIZE_CONV_TRADITIONAL
:
2790 // nothing to do, this corresponds to the default values of both
2791 // the multiplier and infix string
2794 case wxSIZE_CONV_IEC
:
2798 case wxSIZE_CONV_SI
:
2803 const double kiloByteSize
= multiplier
;
2804 const double megaByteSize
= multiplier
* kiloByteSize
;
2805 const double gigaByteSize
= multiplier
* megaByteSize
;
2806 const double teraByteSize
= multiplier
* gigaByteSize
;
2808 const double bytesize
= bs
.ToDouble();
2811 if ( bytesize
< kiloByteSize
)
2812 result
.Printf("%s B", bs
.ToString());
2813 else if ( bytesize
< megaByteSize
)
2814 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2815 else if (bytesize
< gigaByteSize
)
2816 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2817 else if (bytesize
< teraByteSize
)
2818 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2820 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2825 wxULongLong
wxFileName::GetSize() const
2827 return GetSize(GetFullPath());
2830 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2832 wxSizeConvention conv
) const
2834 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2837 #endif // wxUSE_LONGLONG
2839 // ----------------------------------------------------------------------------
2840 // Mac-specific functions
2841 // ----------------------------------------------------------------------------
2843 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2848 class MacDefaultExtensionRecord
2851 MacDefaultExtensionRecord()
2857 // default copy ctor, assignment operator and dtor are ok
2859 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2863 m_creator
= creator
;
2871 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2873 bool gMacDefaultExtensionsInited
= false;
2875 #include "wx/arrimpl.cpp"
2877 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2879 MacDefaultExtensionArray gMacDefaultExtensions
;
2881 // load the default extensions
2882 const MacDefaultExtensionRecord gDefaults
[] =
2884 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2885 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2886 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2889 void MacEnsureDefaultExtensionsLoaded()
2891 if ( !gMacDefaultExtensionsInited
)
2893 // we could load the pc exchange prefs here too
2894 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2896 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2898 gMacDefaultExtensionsInited
= true;
2902 } // anonymous namespace
2904 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2907 FSCatalogInfo catInfo
;
2910 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2912 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2914 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2915 finfo
->fileType
= type
;
2916 finfo
->fileCreator
= creator
;
2917 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2924 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2927 FSCatalogInfo catInfo
;
2930 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2932 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2934 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2935 *type
= finfo
->fileType
;
2936 *creator
= finfo
->fileCreator
;
2943 bool wxFileName::MacSetDefaultTypeAndCreator()
2945 wxUint32 type
, creator
;
2946 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2949 return MacSetTypeAndCreator( type
, creator
) ;
2954 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2956 MacEnsureDefaultExtensionsLoaded() ;
2957 wxString extl
= ext
.Lower() ;
2958 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2960 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2962 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2963 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2970 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2972 MacEnsureDefaultExtensionsLoaded();
2973 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2974 gMacDefaultExtensions
.Add( rec
);
2977 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON