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 and Mac OS X under CodeWarrior 7 format, 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/types.h>
125 #include <sys/stat.h>
136 #include <sys/utime.h>
137 #include <sys/stat.h>
148 #define MAX_PATH _MAX_PATH
153 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
154 #endif // wxUSE_LONGLONG
157 // this define is missing from VC6 headers
158 #ifndef INVALID_FILE_ATTRIBUTES
159 #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
166 // ----------------------------------------------------------------------------
168 // ----------------------------------------------------------------------------
170 // small helper class which opens and closes the file - we use it just to get
171 // a file handle for the given file name to pass it to some Win32 API function
172 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
183 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
185 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
186 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
187 // be changed when we open it because this class is used for setting
188 // access time (see #10567)
189 m_hFile
= ::CreateFile
191 filename
.t_str(), // name
192 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
193 : FILE_WRITE_ATTRIBUTES
,
194 FILE_SHARE_READ
| // sharing mode
195 FILE_SHARE_WRITE
, // (allow everything)
196 NULL
, // no secutity attr
197 OPEN_EXISTING
, // creation disposition
199 NULL
// no template file
202 if ( m_hFile
== INVALID_HANDLE_VALUE
)
204 if ( mode
== ReadAttr
)
206 wxLogSysError(_("Failed to open '%s' for reading"),
211 wxLogSysError(_("Failed to open '%s' for writing"),
219 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
221 if ( !::CloseHandle(m_hFile
) )
223 wxLogSysError(_("Failed to close file handle"));
228 // return true only if the file could be opened successfully
229 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
232 operator HANDLE() const { return m_hFile
; }
240 // ----------------------------------------------------------------------------
242 // ----------------------------------------------------------------------------
244 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
246 // convert between wxDateTime and FILETIME which is a 64-bit value representing
247 // the number of 100-nanosecond intervals since January 1, 1601.
249 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
251 FILETIME ftcopy
= ft
;
253 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
255 wxLogLastError(wxT("FileTimeToLocalFileTime"));
259 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
261 wxLogLastError(wxT("FileTimeToSystemTime"));
264 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
265 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
268 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
271 st
.wDay
= dt
.GetDay();
272 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
273 st
.wYear
= (WORD
)dt
.GetYear();
274 st
.wHour
= dt
.GetHour();
275 st
.wMinute
= dt
.GetMinute();
276 st
.wSecond
= dt
.GetSecond();
277 st
.wMilliseconds
= dt
.GetMillisecond();
280 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
282 wxLogLastError(wxT("SystemTimeToFileTime"));
285 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
287 wxLogLastError(wxT("LocalFileTimeToFileTime"));
291 #endif // wxUSE_DATETIME && __WIN32__
293 // return a string with the volume par
294 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
298 if ( !volume
.empty() )
300 format
= wxFileName::GetFormat(format
);
302 // Special Windows UNC paths hack, part 2: undo what we did in
303 // SplitPath() and make an UNC path if we have a drive which is not a
304 // single letter (hopefully the network shares can't be one letter only
305 // although I didn't find any authoritative docs on this)
306 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
308 // We also have to check for Windows unique volume names here and
309 // return it with '\\?\' prepended to it
310 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume
+ "\\",
313 path
<< "\\\\?\\" << volume
;
317 // it must be a UNC path
318 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
321 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
323 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
331 // return true if the character is a DOS path separator i.e. either a slash or
333 inline bool IsDOSPathSep(wxUniChar ch
)
335 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
338 // return true if the format used is the DOS/Windows one and the string looks
340 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
342 return format
== wxPATH_DOS
&&
343 path
.length() >= 4 && // "\\a" can't be a UNC path
344 IsDOSPathSep(path
[0u]) &&
345 IsDOSPathSep(path
[1u]) &&
346 !IsDOSPathSep(path
[2u]);
349 // ----------------------------------------------------------------------------
351 // ----------------------------------------------------------------------------
353 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
354 static const size_t wxMSWUniqueVolumePrefixLength
= 49;
356 } // anonymous namespace
358 // ============================================================================
360 // ============================================================================
362 // ----------------------------------------------------------------------------
363 // wxFileName construction
364 // ----------------------------------------------------------------------------
366 void wxFileName::Assign( const wxFileName
&filepath
)
368 m_volume
= filepath
.GetVolume();
369 m_dirs
= filepath
.GetDirs();
370 m_name
= filepath
.GetName();
371 m_ext
= filepath
.GetExt();
372 m_relative
= filepath
.m_relative
;
373 m_hasExt
= filepath
.m_hasExt
;
376 void wxFileName::Assign(const wxString
& volume
,
377 const wxString
& path
,
378 const wxString
& name
,
383 // we should ignore paths which look like UNC shares because we already
384 // have the volume here and the UNC notation (\\server\path) is only valid
385 // for paths which don't start with a volume, so prevent SetPath() from
386 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
388 // note also that this is a rather ugly way to do what we want (passing
389 // some kind of flag telling to ignore UNC paths to SetPath() would be
390 // better) but this is the safest thing to do to avoid breaking backwards
391 // compatibility in 2.8
392 if ( IsUNCPath(path
, format
) )
394 // remove one of the 2 leading backslashes to ensure that it's not
395 // recognized as an UNC path by SetPath()
396 wxString
pathNonUNC(path
, 1, wxString::npos
);
397 SetPath(pathNonUNC
, format
);
399 else // no UNC complications
401 SetPath(path
, format
);
411 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
415 if ( pathOrig
.empty() )
423 format
= GetFormat( format
);
425 // 0) deal with possible volume part first
428 SplitVolume(pathOrig
, &volume
, &path
, format
);
429 if ( !volume
.empty() )
436 // 1) Determine if the path is relative or absolute.
440 // we had only the volume
444 wxChar leadingChar
= path
[0u];
449 m_relative
= leadingChar
== wxT(':');
451 // We then remove a leading ":". The reason is in our
452 // storage form for relative paths:
453 // ":dir:file.txt" actually means "./dir/file.txt" in
454 // DOS notation and should get stored as
455 // (relative) (dir) (file.txt)
456 // "::dir:file.txt" actually means "../dir/file.txt"
457 // stored as (relative) (..) (dir) (file.txt)
458 // This is important only for the Mac as an empty dir
459 // actually means <UP>, whereas under DOS, double
460 // slashes can be ignored: "\\\\" is the same as "\\".
466 // TODO: what is the relative path format here?
471 wxFAIL_MSG( wxT("Unknown path format") );
472 // !! Fall through !!
475 m_relative
= leadingChar
!= wxT('/');
479 m_relative
= !IsPathSeparator(leadingChar
, format
);
484 // 2) Break up the path into its members. If the original path
485 // was just "/" or "\\", m_dirs will be empty. We know from
486 // the m_relative field, if this means "nothing" or "root dir".
488 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
490 while ( tn
.HasMoreTokens() )
492 wxString token
= tn
.GetNextToken();
494 // Remove empty token under DOS and Unix, interpret them
498 if (format
== wxPATH_MAC
)
499 m_dirs
.Add( wxT("..") );
509 void wxFileName::Assign(const wxString
& fullpath
,
512 wxString volume
, path
, name
, ext
;
514 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
516 Assign(volume
, path
, name
, ext
, hasExt
, format
);
519 void wxFileName::Assign(const wxString
& fullpathOrig
,
520 const wxString
& fullname
,
523 // always recognize fullpath as directory, even if it doesn't end with a
525 wxString fullpath
= fullpathOrig
;
526 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
528 fullpath
+= GetPathSeparator(format
);
531 wxString volume
, path
, name
, ext
;
534 // do some consistency checks: the name should be really just the filename
535 // and the path should be really just a path
536 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
538 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
540 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
541 wxT("the file name shouldn't contain the path") );
543 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
546 // This test makes no sense on an OpenVMS system.
547 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
548 wxT("the path shouldn't contain file name nor extension") );
550 Assign(volume
, path
, name
, ext
, hasExt
, format
);
553 void wxFileName::Assign(const wxString
& pathOrig
,
554 const wxString
& name
,
560 SplitVolume(pathOrig
, &volume
, &path
, format
);
562 Assign(volume
, path
, name
, ext
, format
);
565 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
567 Assign(dir
, wxEmptyString
, format
);
570 void wxFileName::Clear()
576 m_ext
= wxEmptyString
;
578 // we don't have any absolute path for now
586 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
588 return wxFileName(file
, format
);
592 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
595 fn
.AssignDir(dir
, format
);
599 // ----------------------------------------------------------------------------
601 // ----------------------------------------------------------------------------
603 bool wxFileName::FileExists() const
605 return wxFileName::FileExists( GetFullPath() );
609 bool wxFileName::FileExists( const wxString
&filePath
)
611 #if defined(__WXPALMOS__)
613 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
614 // we must use GetFileAttributes() instead of the ANSI C functions because
615 // it can cope with network (UNC) paths unlike them
616 DWORD ret
= ::GetFileAttributes(filePath
.t_str());
618 return (ret
!= INVALID_FILE_ATTRIBUTES
) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
621 #define S_ISREG(mode) ((mode) & S_IFREG)
625 return (wxStat( filePath
, &st
) == 0 && S_ISREG(st
.st_mode
))
627 || (errno
== EACCES
) // if access is denied something with that name
628 // exists and is opened in exclusive mode.
631 #endif // __WIN32__/!__WIN32__
634 bool wxFileName::DirExists() const
636 return wxFileName::DirExists( GetPath() );
640 bool wxFileName::DirExists( const wxString
&dirPath
)
642 wxString
strPath(dirPath
);
644 #if defined(__WINDOWS__) || defined(__OS2__)
645 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
646 // so remove all trailing backslashes from the path - but don't do this for
647 // the paths "d:\" (which are different from "d:"), for just "\" or for
648 // windows unique volume names ("\\?\Volume{GUID}\")
649 while ( wxEndsWithPathSeparator(strPath
) )
651 size_t len
= strPath
.length();
652 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) ||
653 (len
== wxMSWUniqueVolumePrefixLength
&&
654 wxFileName::IsMSWUniqueVolumeNamePath(strPath
)))
659 strPath
.Truncate(len
- 1);
661 #endif // __WINDOWS__
664 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
665 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
669 #if defined(__WXPALMOS__)
671 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
672 // stat() can't cope with network paths
673 DWORD ret
= ::GetFileAttributes(strPath
.t_str());
675 return (ret
!= INVALID_FILE_ATTRIBUTES
) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
676 #elif defined(__OS2__)
677 FILESTATUS3 Info
= {{0}};
678 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
679 (void*) &Info
, sizeof(FILESTATUS3
));
681 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
682 (rc
== ERROR_SHARING_VIOLATION
);
683 // If we got a sharing violation, there must be something with this name.
687 #ifndef __VISAGECPP__
688 return wxStat(strPath
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
690 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
691 return wxStat(strPath
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
694 #endif // __WIN32__/!__WIN32__
697 // ----------------------------------------------------------------------------
698 // CWD and HOME stuff
699 // ----------------------------------------------------------------------------
701 void wxFileName::AssignCwd(const wxString
& volume
)
703 AssignDir(wxFileName::GetCwd(volume
));
707 wxString
wxFileName::GetCwd(const wxString
& volume
)
709 // if we have the volume, we must get the current directory on this drive
710 // and to do this we have to chdir to this volume - at least under Windows,
711 // I don't know how to get the current drive on another volume elsewhere
714 if ( !volume
.empty() )
717 SetCwd(volume
+ GetVolumeSeparator());
720 wxString cwd
= ::wxGetCwd();
722 if ( !volume
.empty() )
730 bool wxFileName::SetCwd() const
732 return wxFileName::SetCwd( GetPath() );
735 bool wxFileName::SetCwd( const wxString
&cwd
)
737 return ::wxSetWorkingDirectory( cwd
);
740 void wxFileName::AssignHomeDir()
742 AssignDir(wxFileName::GetHomeDir());
745 wxString
wxFileName::GetHomeDir()
747 return ::wxGetHomeDir();
751 // ----------------------------------------------------------------------------
752 // CreateTempFileName
753 // ----------------------------------------------------------------------------
755 #if wxUSE_FILE || wxUSE_FFILE
758 #if !defined wx_fdopen && defined HAVE_FDOPEN
759 #define wx_fdopen fdopen
762 // NB: GetTempFileName() under Windows creates the file, so using
763 // O_EXCL there would fail
765 #define wxOPEN_EXCL 0
767 #define wxOPEN_EXCL O_EXCL
771 #ifdef wxOpenOSFHandle
772 #define WX_HAVE_DELETE_ON_CLOSE
773 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
775 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
777 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
779 DWORD disposition
= OPEN_ALWAYS
;
781 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
782 FILE_FLAG_DELETE_ON_CLOSE
;
784 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
785 disposition
, attributes
, NULL
);
787 return wxOpenOSFHandle(h
, wxO_BINARY
);
789 #endif // wxOpenOSFHandle
792 // Helper to open the file
794 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
796 #ifdef WX_HAVE_DELETE_ON_CLOSE
798 return wxOpenWithDeleteOnClose(path
);
801 *deleteOnClose
= false;
803 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
808 // Helper to open the file and attach it to the wxFFile
810 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
813 *deleteOnClose
= false;
814 return file
->Open(path
, wxT("w+b"));
816 int fd
= wxTempOpen(path
, deleteOnClose
);
819 file
->Attach(wx_fdopen(fd
, "w+b"));
820 return file
->IsOpened();
823 #endif // wxUSE_FFILE
827 #define WXFILEARGS(x, y) y
829 #define WXFILEARGS(x, y) x
831 #define WXFILEARGS(x, y) x, y
835 // Implementation of wxFileName::CreateTempFileName().
837 static wxString
wxCreateTempImpl(
838 const wxString
& prefix
,
839 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
840 bool *deleteOnClose
= NULL
)
842 #if wxUSE_FILE && wxUSE_FFILE
843 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
845 wxString path
, dir
, name
;
846 bool wantDeleteOnClose
= false;
850 // set the result to false initially
851 wantDeleteOnClose
= *deleteOnClose
;
852 *deleteOnClose
= false;
856 // easier if it alwasys points to something
857 deleteOnClose
= &wantDeleteOnClose
;
860 // use the directory specified by the prefix
861 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
865 dir
= wxFileName::GetTempDir();
868 #if defined(__WXWINCE__)
869 path
= dir
+ wxT("\\") + name
;
871 while (wxFileName::FileExists(path
))
873 path
= dir
+ wxT("\\") + name
;
878 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
879 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
880 wxStringBuffer(path
, MAX_PATH
+ 1)))
882 wxLogLastError(wxT("GetTempFileName"));
890 if ( !wxEndsWithPathSeparator(dir
) &&
891 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
893 path
+= wxFILE_SEP_PATH
;
898 #if defined(HAVE_MKSTEMP)
899 // scratch space for mkstemp()
900 path
+= wxT("XXXXXX");
902 // we need to copy the path to the buffer in which mkstemp() can modify it
903 wxCharBuffer
buf(path
.fn_str());
905 // cast is safe because the string length doesn't change
906 int fdTemp
= mkstemp( (char*)(const char*) buf
);
909 // this might be not necessary as mkstemp() on most systems should have
910 // already done it but it doesn't hurt neither...
913 else // mkstemp() succeeded
915 path
= wxConvFile
.cMB2WX( (const char*) buf
);
918 // avoid leaking the fd
921 fileTemp
->Attach(fdTemp
);
930 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
932 ffileTemp
->Open(path
, wxT("r+b"));
943 #else // !HAVE_MKSTEMP
947 path
+= wxT("XXXXXX");
949 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
950 if ( !mktemp( (char*)(const char*) buf
) )
956 path
= wxConvFile
.cMB2WX( (const char*) buf
);
958 #else // !HAVE_MKTEMP (includes __DOS__)
959 // generate the unique file name ourselves
960 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
961 path
<< (unsigned int)getpid();
966 static const size_t numTries
= 1000;
967 for ( size_t n
= 0; n
< numTries
; n
++ )
969 // 3 hex digits is enough for numTries == 1000 < 4096
970 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
971 if ( !wxFileName::FileExists(pathTry
) )
980 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
982 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
984 #endif // Windows/!Windows
988 wxLogSysError(_("Failed to create a temporary file name"));
994 // open the file - of course, there is a race condition here, this is
995 // why we always prefer using mkstemp()...
997 if ( fileTemp
&& !fileTemp
->IsOpened() )
999 *deleteOnClose
= wantDeleteOnClose
;
1000 int fd
= wxTempOpen(path
, deleteOnClose
);
1002 fileTemp
->Attach(fd
);
1009 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1011 *deleteOnClose
= wantDeleteOnClose
;
1012 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1018 // FIXME: If !ok here should we loop and try again with another
1019 // file name? That is the standard recourse if open(O_EXCL)
1020 // fails, though of course it should be protected against
1021 // possible infinite looping too.
1023 wxLogError(_("Failed to open temporary file."));
1033 static bool wxCreateTempImpl(
1034 const wxString
& prefix
,
1035 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1038 bool deleteOnClose
= true;
1040 *name
= wxCreateTempImpl(prefix
,
1041 WXFILEARGS(fileTemp
, ffileTemp
),
1044 bool ok
= !name
->empty();
1049 else if (ok
&& wxRemoveFile(*name
))
1057 static void wxAssignTempImpl(
1059 const wxString
& prefix
,
1060 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1063 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1065 if ( tempname
.empty() )
1067 // error, failed to get temp file name
1072 fn
->Assign(tempname
);
1077 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1079 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1083 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1085 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1088 #endif // wxUSE_FILE || wxUSE_FFILE
1093 wxString
wxCreateTempFileName(const wxString
& prefix
,
1095 bool *deleteOnClose
)
1097 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1100 bool wxCreateTempFile(const wxString
& prefix
,
1104 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1107 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1109 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1114 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1116 return wxCreateTempFileName(prefix
, fileTemp
);
1119 #endif // wxUSE_FILE
1124 wxString
wxCreateTempFileName(const wxString
& prefix
,
1126 bool *deleteOnClose
)
1128 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1131 bool wxCreateTempFile(const wxString
& prefix
,
1135 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1139 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1141 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1146 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1148 return wxCreateTempFileName(prefix
, fileTemp
);
1151 #endif // wxUSE_FFILE
1154 // ----------------------------------------------------------------------------
1155 // directory operations
1156 // ----------------------------------------------------------------------------
1158 // helper of GetTempDir(): check if the given directory exists and return it if
1159 // it does or an empty string otherwise
1163 wxString
CheckIfDirExists(const wxString
& dir
)
1165 return wxFileName::DirExists(dir
) ? dir
: wxString();
1168 } // anonymous namespace
1170 wxString
wxFileName::GetTempDir()
1172 // first try getting it from environment: this allows overriding the values
1173 // used by default if the user wants to create temporary files in another
1175 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1178 dir
= CheckIfDirExists(wxGetenv("TMP"));
1180 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1183 // if no environment variables are set, use the system default
1186 #if defined(__WXWINCE__)
1187 dir
= CheckIfDirExists(wxT("\\temp"));
1188 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1189 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1191 wxLogLastError(wxT("GetTempPath"));
1193 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1194 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1195 #endif // systems with native way
1197 else // we got directory from an environment variable
1199 // remove any trailing path separators, we don't want to ever return
1200 // them from this function for consistency
1201 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1202 if ( lastNonSep
== wxString::npos
)
1204 // the string consists entirely of separators, leave only one
1205 dir
= GetPathSeparator();
1209 dir
.erase(lastNonSep
+ 1);
1213 // fall back to hard coded value
1216 #ifdef __UNIX_LIKE__
1217 dir
= CheckIfDirExists("/tmp");
1219 #endif // __UNIX_LIKE__
1226 bool wxFileName::Mkdir( int perm
, int flags
) const
1228 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1231 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1233 if ( flags
& wxPATH_MKDIR_FULL
)
1235 // split the path in components
1236 wxFileName filename
;
1237 filename
.AssignDir(dir
);
1240 if ( filename
.HasVolume())
1242 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1245 wxArrayString dirs
= filename
.GetDirs();
1246 size_t count
= dirs
.GetCount();
1247 for ( size_t i
= 0; i
< count
; i
++ )
1249 if ( i
> 0 || filename
.IsAbsolute() )
1250 currPath
+= wxFILE_SEP_PATH
;
1251 currPath
+= dirs
[i
];
1253 if (!DirExists(currPath
))
1255 if (!wxMkdir(currPath
, perm
))
1257 // no need to try creating further directories
1267 return ::wxMkdir( dir
, perm
);
1270 bool wxFileName::Rmdir(int flags
) const
1272 return wxFileName::Rmdir( GetPath(), flags
);
1275 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1278 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1280 // SHFileOperation needs double null termination string
1281 // but without separator at the end of the path
1283 if ( path
.Last() == wxFILE_SEP_PATH
)
1287 SHFILEOPSTRUCT fileop
;
1288 wxZeroMemory(fileop
);
1289 fileop
.wFunc
= FO_DELETE
;
1290 #if defined(__CYGWIN__) && defined(wxUSE_UNICODE)
1291 fileop
.pFrom
= path
.wc_str();
1293 fileop
.pFrom
= path
.fn_str();
1295 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1297 // FOF_NOERRORUI is not defined in WinCE
1298 fileop
.fFlags
|= FOF_NOERRORUI
;
1301 int ret
= SHFileOperation(&fileop
);
1304 // SHFileOperation may return non-Win32 error codes, so the error
1305 // message can be incorrect
1306 wxLogApiError(wxT("SHFileOperation"), ret
);
1312 else if ( flags
& wxPATH_RMDIR_FULL
)
1314 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1315 #endif // !__WXMSW__
1318 if ( path
.Last() != wxFILE_SEP_PATH
)
1319 path
+= wxFILE_SEP_PATH
;
1323 if ( !d
.IsOpened() )
1328 // first delete all subdirectories
1329 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1332 wxFileName::Rmdir(path
+ filename
, flags
);
1333 cont
= d
.GetNext(&filename
);
1337 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1339 // delete all files too
1340 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1343 ::wxRemoveFile(path
+ filename
);
1344 cont
= d
.GetNext(&filename
);
1347 #endif // !__WXMSW__
1350 return ::wxRmdir(dir
);
1353 // ----------------------------------------------------------------------------
1354 // path normalization
1355 // ----------------------------------------------------------------------------
1357 bool wxFileName::Normalize(int flags
,
1358 const wxString
& cwd
,
1359 wxPathFormat format
)
1361 // deal with env vars renaming first as this may seriously change the path
1362 if ( flags
& wxPATH_NORM_ENV_VARS
)
1364 wxString pathOrig
= GetFullPath(format
);
1365 wxString path
= wxExpandEnvVars(pathOrig
);
1366 if ( path
!= pathOrig
)
1372 // the existing path components
1373 wxArrayString dirs
= GetDirs();
1375 // the path to prepend in front to make the path absolute
1378 format
= GetFormat(format
);
1380 // set up the directory to use for making the path absolute later
1381 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1385 curDir
.AssignCwd(GetVolume());
1387 else // cwd provided
1389 curDir
.AssignDir(cwd
);
1393 // handle ~ stuff under Unix only
1394 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1396 if ( !dirs
.IsEmpty() )
1398 wxString dir
= dirs
[0u];
1399 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1401 // to make the path absolute use the home directory
1402 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1408 // transform relative path into abs one
1409 if ( curDir
.IsOk() )
1411 // this path may be relative because it doesn't have the volume name
1412 // and still have m_relative=true; in this case we shouldn't modify
1413 // our directory components but just set the current volume
1414 if ( !HasVolume() && curDir
.HasVolume() )
1416 SetVolume(curDir
.GetVolume());
1420 // yes, it was the case - we don't need curDir then
1425 // finally, prepend curDir to the dirs array
1426 wxArrayString dirsNew
= curDir
.GetDirs();
1427 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1429 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1430 // return for some reason an absolute path, then curDir maybe not be absolute!
1431 if ( !curDir
.m_relative
)
1433 // we have prepended an absolute path and thus we are now an absolute
1437 // else if (flags & wxPATH_NORM_ABSOLUTE):
1438 // should we warn the user that we didn't manage to make the path absolute?
1441 // now deal with ".", ".." and the rest
1443 size_t count
= dirs
.GetCount();
1444 for ( size_t n
= 0; n
< count
; n
++ )
1446 wxString dir
= dirs
[n
];
1448 if ( flags
& wxPATH_NORM_DOTS
)
1450 if ( dir
== wxT(".") )
1456 if ( dir
== wxT("..") )
1458 if ( m_dirs
.empty() )
1460 // We have more ".." than directory components so far.
1461 // Don't treat this as an error as the path could have been
1462 // entered by user so try to handle it reasonably: if the
1463 // path is absolute, just ignore the extra ".." because
1464 // "/.." is the same as "/". Otherwise, i.e. for relative
1465 // paths, keep ".." unchanged because removing it would
1466 // modify the file a relative path refers to.
1471 else // Normal case, go one step up.
1482 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1483 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1486 if (GetShortcutTarget(GetFullPath(format
), filename
))
1494 #if defined(__WIN32__)
1495 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1497 Assign(GetLongPath());
1501 // Change case (this should be kept at the end of the function, to ensure
1502 // that the path doesn't change any more after we normalize its case)
1503 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1505 m_volume
.MakeLower();
1509 // directory entries must be made lower case as well
1510 count
= m_dirs
.GetCount();
1511 for ( size_t i
= 0; i
< count
; i
++ )
1513 m_dirs
[i
].MakeLower();
1521 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1522 const wxString
& replacementFmtString
,
1523 wxPathFormat format
)
1525 // look into stringForm for the contents of the given environment variable
1527 if (envname
.empty() ||
1528 !wxGetEnv(envname
, &val
))
1533 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1534 // do not touch the file name and the extension
1536 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1537 stringForm
.Replace(val
, replacement
);
1539 // Now assign ourselves the modified path:
1540 Assign(stringForm
, GetFullName(), format
);
1546 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1548 wxString homedir
= wxGetHomeDir();
1549 if (homedir
.empty())
1552 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1553 // do not touch the file name and the extension
1555 stringForm
.Replace(homedir
, "~");
1557 // Now assign ourselves the modified path:
1558 Assign(stringForm
, GetFullName(), format
);
1563 // ----------------------------------------------------------------------------
1564 // get the shortcut target
1565 // ----------------------------------------------------------------------------
1567 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1568 // The .lnk file is a plain text file so it should be easy to
1569 // make it work. Hint from Google Groups:
1570 // "If you open up a lnk file, you'll see a
1571 // number, followed by a pound sign (#), followed by more text. The
1572 // number is the number of characters that follows the pound sign. The
1573 // characters after the pound sign are the command line (which _can_
1574 // include arguments) to be executed. Any path (e.g. \windows\program
1575 // files\myapp.exe) that includes spaces needs to be enclosed in
1576 // quotation marks."
1578 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1579 // The following lines are necessary under WinCE
1580 // #include "wx/msw/private.h"
1581 // #include <ole2.h>
1583 #if defined(__WXWINCE__)
1584 #include <shlguid.h>
1587 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1588 wxString
& targetFilename
,
1589 wxString
* arguments
) const
1591 wxString path
, file
, ext
;
1592 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1596 bool success
= false;
1598 // Assume it's not a shortcut if it doesn't end with lnk
1599 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1602 // create a ShellLink object
1603 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1604 IID_IShellLink
, (LPVOID
*) &psl
);
1606 if (SUCCEEDED(hres
))
1609 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1610 if (SUCCEEDED(hres
))
1612 WCHAR wsz
[MAX_PATH
];
1614 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1617 hres
= ppf
->Load(wsz
, 0);
1620 if (SUCCEEDED(hres
))
1623 // Wrong prototype in early versions
1624 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1625 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1627 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1629 targetFilename
= wxString(buf
);
1630 success
= (shortcutPath
!= targetFilename
);
1632 psl
->GetArguments(buf
, 2048);
1634 if (!args
.empty() && arguments
)
1646 #endif // __WIN32__ && !__WXWINCE__
1649 // ----------------------------------------------------------------------------
1650 // absolute/relative paths
1651 // ----------------------------------------------------------------------------
1653 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1655 // unix paths beginning with ~ are reported as being absolute
1656 if ( format
== wxPATH_UNIX
)
1658 if ( !m_dirs
.IsEmpty() )
1660 wxString dir
= m_dirs
[0u];
1662 if (!dir
.empty() && dir
[0u] == wxT('~'))
1667 // if our path doesn't start with a path separator, it's not an absolute
1672 if ( !GetVolumeSeparator(format
).empty() )
1674 // this format has volumes and an absolute path must have one, it's not
1675 // enough to have the full path to be an absolute file under Windows
1676 if ( GetVolume().empty() )
1683 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1685 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1687 // get cwd only once - small time saving
1688 wxString cwd
= wxGetCwd();
1689 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1690 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1692 bool withCase
= IsCaseSensitive(format
);
1694 // we can't do anything if the files live on different volumes
1695 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1701 // same drive, so we don't need our volume
1704 // remove common directories starting at the top
1705 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1706 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1709 fnBase
.m_dirs
.RemoveAt(0);
1712 // add as many ".." as needed
1713 size_t count
= fnBase
.m_dirs
.GetCount();
1714 for ( size_t i
= 0; i
< count
; i
++ )
1716 m_dirs
.Insert(wxT(".."), 0u);
1719 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1721 // a directory made relative with respect to itself is '.' under Unix
1722 // and DOS, by definition (but we don't have to insert "./" for the
1724 if ( m_dirs
.IsEmpty() && IsDir() )
1726 m_dirs
.Add(wxT('.'));
1736 // ----------------------------------------------------------------------------
1737 // filename kind tests
1738 // ----------------------------------------------------------------------------
1740 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1742 wxFileName fn1
= *this,
1745 // get cwd only once - small time saving
1746 wxString cwd
= wxGetCwd();
1747 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1748 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1750 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1753 // TODO: compare inodes for Unix, this works even when filenames are
1754 // different but files are the same (symlinks) (VZ)
1760 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1762 // only Unix filenames are truely case-sensitive
1763 return GetFormat(format
) == wxPATH_UNIX
;
1767 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1769 // Inits to forbidden characters that are common to (almost) all platforms.
1770 wxString strForbiddenChars
= wxT("*?");
1772 // If asserts, wxPathFormat has been changed. In case of a new path format
1773 // addition, the following code might have to be updated.
1774 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1775 switch ( GetFormat(format
) )
1778 wxFAIL_MSG( wxT("Unknown path format") );
1779 // !! Fall through !!
1785 // On a Mac even names with * and ? are allowed (Tested with OS
1786 // 9.2.1 and OS X 10.2.5)
1787 strForbiddenChars
= wxEmptyString
;
1791 strForbiddenChars
+= wxT("\\/:\"<>|");
1798 return strForbiddenChars
;
1802 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1805 return wxEmptyString
;
1809 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1810 (GetFormat(format
) == wxPATH_VMS
) )
1812 sepVol
= wxFILE_SEP_DSK
;
1821 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1824 switch ( GetFormat(format
) )
1827 // accept both as native APIs do but put the native one first as
1828 // this is the one we use in GetFullPath()
1829 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1833 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1837 seps
= wxFILE_SEP_PATH_UNIX
;
1841 seps
= wxFILE_SEP_PATH_MAC
;
1845 seps
= wxFILE_SEP_PATH_VMS
;
1853 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1855 format
= GetFormat(format
);
1857 // under VMS the end of the path is ']', not the path separator used to
1858 // separate the components
1859 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1863 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1865 // wxString::Find() doesn't work as expected with NUL - it will always find
1866 // it, so test for it separately
1867 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1872 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
1874 // return true if the format used is the DOS/Windows one and the string begins
1875 // with a Windows unique volume name ("\\?\Volume{guid}\")
1876 return format
== wxPATH_DOS
&&
1877 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
1878 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
1879 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
1882 // ----------------------------------------------------------------------------
1883 // path components manipulation
1884 // ----------------------------------------------------------------------------
1886 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1890 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1895 const size_t len
= dir
.length();
1896 for ( size_t n
= 0; n
< len
; n
++ )
1898 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1900 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1909 void wxFileName::AppendDir( const wxString
& dir
)
1911 if ( IsValidDirComponent(dir
) )
1915 void wxFileName::PrependDir( const wxString
& dir
)
1920 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1922 if ( IsValidDirComponent(dir
) )
1923 m_dirs
.Insert(dir
, before
);
1926 void wxFileName::RemoveDir(size_t pos
)
1928 m_dirs
.RemoveAt(pos
);
1931 // ----------------------------------------------------------------------------
1933 // ----------------------------------------------------------------------------
1935 void wxFileName::SetFullName(const wxString
& fullname
)
1937 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1938 &m_name
, &m_ext
, &m_hasExt
);
1941 wxString
wxFileName::GetFullName() const
1943 wxString fullname
= m_name
;
1946 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1952 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1954 format
= GetFormat( format
);
1958 // return the volume with the path as well if requested
1959 if ( flags
& wxPATH_GET_VOLUME
)
1961 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1964 // the leading character
1969 fullpath
+= wxFILE_SEP_PATH_MAC
;
1974 fullpath
+= wxFILE_SEP_PATH_DOS
;
1978 wxFAIL_MSG( wxT("Unknown path format") );
1984 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1989 // no leading character here but use this place to unset
1990 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1991 // as, if I understand correctly, there should never be a dot
1992 // before the closing bracket
1993 flags
&= ~wxPATH_GET_SEPARATOR
;
1996 if ( m_dirs
.empty() )
1998 // there is nothing more
2002 // then concatenate all the path components using the path separator
2003 if ( format
== wxPATH_VMS
)
2005 fullpath
+= wxT('[');
2008 const size_t dirCount
= m_dirs
.GetCount();
2009 for ( size_t i
= 0; i
< dirCount
; i
++ )
2014 if ( m_dirs
[i
] == wxT(".") )
2016 // skip appending ':', this shouldn't be done in this
2017 // case as "::" is interpreted as ".." under Unix
2021 // convert back from ".." to nothing
2022 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2023 fullpath
+= m_dirs
[i
];
2027 wxFAIL_MSG( wxT("Unexpected path format") );
2028 // still fall through
2032 fullpath
+= m_dirs
[i
];
2036 // TODO: What to do with ".." under VMS
2038 // convert back from ".." to nothing
2039 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2040 fullpath
+= m_dirs
[i
];
2044 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2045 fullpath
+= GetPathSeparator(format
);
2048 if ( format
== wxPATH_VMS
)
2050 fullpath
+= wxT(']');
2056 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2058 // we already have a function to get the path
2059 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2062 // now just add the file name and extension to it
2063 fullpath
+= GetFullName();
2068 // Return the short form of the path (returns identity on non-Windows platforms)
2069 wxString
wxFileName::GetShortPath() const
2071 wxString
path(GetFullPath());
2073 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2074 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2078 if ( ::GetShortPathName
2081 wxStringBuffer(pathOut
, sz
),
2093 // Return the long form of the path (returns identity on non-Windows platforms)
2094 wxString
wxFileName::GetLongPath() const
2097 path
= GetFullPath();
2099 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2101 #if wxUSE_DYNLIB_CLASS
2102 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2104 // this is MT-safe as in the worst case we're going to resolve the function
2105 // twice -- but as the result is the same in both threads, it's ok
2106 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2107 if ( !s_pfnGetLongPathName
)
2109 static bool s_triedToLoad
= false;
2111 if ( !s_triedToLoad
)
2113 s_triedToLoad
= true;
2115 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2117 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2122 #endif // Unicode/ANSI
2124 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2126 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2127 dllKernel
.GetSymbol(GetLongPathName
);
2130 // note that kernel32.dll can be unloaded, it stays in memory
2131 // anyhow as all Win32 programs link to it and so it's safe to call
2132 // GetLongPathName() even after unloading it
2136 if ( s_pfnGetLongPathName
)
2138 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2141 if ( (*s_pfnGetLongPathName
)
2144 wxStringBuffer(pathOut
, dwSize
),
2152 #endif // wxUSE_DYNLIB_CLASS
2154 // The OS didn't support GetLongPathName, or some other error.
2155 // We need to call FindFirstFile on each component in turn.
2157 WIN32_FIND_DATA findFileData
;
2161 pathOut
= GetVolume() +
2162 GetVolumeSeparator(wxPATH_DOS
) +
2163 GetPathSeparator(wxPATH_DOS
);
2165 pathOut
= wxEmptyString
;
2167 wxArrayString dirs
= GetDirs();
2168 dirs
.Add(GetFullName());
2172 size_t count
= dirs
.GetCount();
2173 for ( size_t i
= 0; i
< count
; i
++ )
2175 const wxString
& dir
= dirs
[i
];
2177 // We're using pathOut to collect the long-name path, but using a
2178 // temporary for appending the last path component which may be
2180 tmpPath
= pathOut
+ dir
;
2182 // We must not process "." or ".." here as they would be (unexpectedly)
2183 // replaced by the corresponding directory names so just leave them
2186 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2187 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2188 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2190 tmpPath
+= wxFILE_SEP_PATH
;
2195 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2196 if (hFind
== INVALID_HANDLE_VALUE
)
2198 // Error: most likely reason is that path doesn't exist, so
2199 // append any unprocessed parts and return
2200 for ( i
+= 1; i
< count
; i
++ )
2201 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2206 pathOut
+= findFileData
.cFileName
;
2207 if ( (i
< (count
-1)) )
2208 pathOut
+= wxFILE_SEP_PATH
;
2214 #endif // Win32/!Win32
2219 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2221 if (format
== wxPATH_NATIVE
)
2223 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2224 format
= wxPATH_DOS
;
2225 #elif defined(__VMS)
2226 format
= wxPATH_VMS
;
2228 format
= wxPATH_UNIX
;
2234 #ifdef wxHAS_FILESYSTEM_VOLUMES
2237 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2239 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2241 wxString
vol(drive
);
2242 vol
+= wxFILE_SEP_DSK
;
2243 if ( flags
& wxPATH_GET_SEPARATOR
)
2244 vol
+= wxFILE_SEP_PATH
;
2249 #endif // wxHAS_FILESYSTEM_VOLUMES
2251 // ----------------------------------------------------------------------------
2252 // path splitting function
2253 // ----------------------------------------------------------------------------
2257 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2258 wxString
*pstrVolume
,
2260 wxPathFormat format
)
2262 format
= GetFormat(format
);
2264 wxString fullpath
= fullpathWithVolume
;
2266 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2268 // special Windows unique volume names hack: transform
2269 // \\?\Volume{guid}\path into Volume{guid}:path
2270 // note: this check must be done before the check for UNC path
2272 // we know the last backslash from the unique volume name is located
2273 // there from IsMSWUniqueVolumeNamePath
2274 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2276 // paths starting with a unique volume name should always be absolute
2277 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2279 // remove the leading "\\?\" part
2280 fullpath
.erase(0, 4);
2282 else if ( IsUNCPath(fullpath
, format
) )
2284 // special Windows UNC paths hack: transform \\share\path into share:path
2286 fullpath
.erase(0, 2);
2288 size_t posFirstSlash
=
2289 fullpath
.find_first_of(GetPathTerminators(format
));
2290 if ( posFirstSlash
!= wxString::npos
)
2292 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2294 // UNC paths are always absolute, right? (FIXME)
2295 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2299 // We separate the volume here
2300 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2302 wxString sepVol
= GetVolumeSeparator(format
);
2304 // we have to exclude the case of a colon in the very beginning of the
2305 // string as it can't be a volume separator (nor can this be a valid
2306 // DOS file name at all but we'll leave dealing with this to our caller)
2307 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2308 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2312 *pstrVolume
= fullpath
.Left(posFirstColon
);
2315 // remove the volume name and the separator from the full path
2316 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2321 *pstrPath
= fullpath
;
2325 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2326 wxString
*pstrVolume
,
2331 wxPathFormat format
)
2333 format
= GetFormat(format
);
2336 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2338 // find the positions of the last dot and last path separator in the path
2339 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2340 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2342 // check whether this dot occurs at the very beginning of a path component
2343 if ( (posLastDot
!= wxString::npos
) &&
2345 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2346 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2348 // dot may be (and commonly -- at least under Unix -- is) the first
2349 // character of the filename, don't treat the entire filename as
2350 // extension in this case
2351 posLastDot
= wxString::npos
;
2354 // if we do have a dot and a slash, check that the dot is in the name part
2355 if ( (posLastDot
!= wxString::npos
) &&
2356 (posLastSlash
!= wxString::npos
) &&
2357 (posLastDot
< posLastSlash
) )
2359 // the dot is part of the path, not the start of the extension
2360 posLastDot
= wxString::npos
;
2363 // now fill in the variables provided by user
2366 if ( posLastSlash
== wxString::npos
)
2373 // take everything up to the path separator but take care to make
2374 // the path equal to something like '/', not empty, for the files
2375 // immediately under root directory
2376 size_t len
= posLastSlash
;
2378 // this rule does not apply to mac since we do not start with colons (sep)
2379 // except for relative paths
2380 if ( !len
&& format
!= wxPATH_MAC
)
2383 *pstrPath
= fullpath
.Left(len
);
2385 // special VMS hack: remove the initial bracket
2386 if ( format
== wxPATH_VMS
)
2388 if ( (*pstrPath
)[0u] == wxT('[') )
2389 pstrPath
->erase(0, 1);
2396 // take all characters starting from the one after the last slash and
2397 // up to, but excluding, the last dot
2398 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2400 if ( posLastDot
== wxString::npos
)
2402 // take all until the end
2403 count
= wxString::npos
;
2405 else if ( posLastSlash
== wxString::npos
)
2409 else // have both dot and slash
2411 count
= posLastDot
- posLastSlash
- 1;
2414 *pstrName
= fullpath
.Mid(nStart
, count
);
2417 // finally deal with the extension here: we have an added complication that
2418 // extension may be empty (but present) as in "foo." where trailing dot
2419 // indicates the empty extension at the end -- and hence we must remember
2420 // that we have it independently of pstrExt
2421 if ( posLastDot
== wxString::npos
)
2431 // take everything after the dot
2433 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2440 void wxFileName::SplitPath(const wxString
& fullpath
,
2444 wxPathFormat format
)
2447 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2451 path
->Prepend(wxGetVolumeString(volume
, format
));
2456 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2458 wxFileName
fn(fullpath
);
2460 return fn
.GetFullPath();
2463 // ----------------------------------------------------------------------------
2465 // ----------------------------------------------------------------------------
2469 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2470 const wxDateTime
*dtMod
,
2471 const wxDateTime
*dtCreate
) const
2473 #if defined(__WIN32__)
2474 FILETIME ftAccess
, ftCreate
, ftWrite
;
2477 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2479 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2481 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2487 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2489 wxLogError(_("Setting directory access times is not supported "
2490 "under this OS version"));
2495 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2499 path
= GetFullPath();
2503 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2506 if ( ::SetFileTime(fh
,
2507 dtCreate
? &ftCreate
: NULL
,
2508 dtAccess
? &ftAccess
: NULL
,
2509 dtMod
? &ftWrite
: NULL
) )
2514 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2515 wxUnusedVar(dtCreate
);
2517 if ( !dtAccess
&& !dtMod
)
2519 // can't modify the creation time anyhow, don't try
2523 // if dtAccess or dtMod is not specified, use the other one (which must be
2524 // non NULL because of the test above) for both times
2526 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2527 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2528 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2532 #else // other platform
2533 wxUnusedVar(dtAccess
);
2535 wxUnusedVar(dtCreate
);
2538 wxLogSysError(_("Failed to modify file times for '%s'"),
2539 GetFullPath().c_str());
2544 bool wxFileName::Touch() const
2546 #if defined(__UNIX_LIKE__)
2547 // under Unix touching file is simple: just pass NULL to utime()
2548 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2553 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2556 #else // other platform
2557 wxDateTime dtNow
= wxDateTime::Now();
2559 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2563 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2565 wxDateTime
*dtCreate
) const
2567 #if defined(__WIN32__)
2568 // we must use different methods for the files and directories under
2569 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2570 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2573 FILETIME ftAccess
, ftCreate
, ftWrite
;
2576 // implemented in msw/dir.cpp
2577 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2578 FILETIME
*, FILETIME
*, FILETIME
*);
2580 // we should pass the path without the trailing separator to
2581 // wxGetDirectoryTimes()
2582 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2583 &ftAccess
, &ftCreate
, &ftWrite
);
2587 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2590 ok
= ::GetFileTime(fh
,
2591 dtCreate
? &ftCreate
: NULL
,
2592 dtAccess
? &ftAccess
: NULL
,
2593 dtMod
? &ftWrite
: NULL
) != 0;
2604 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2606 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2608 ConvertFileTimeToWx(dtMod
, ftWrite
);
2612 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2613 // no need to test for IsDir() here
2615 if ( wxStat( GetFullPath(), &stBuf
) == 0 )
2618 dtAccess
->Set(stBuf
.st_atime
);
2620 dtMod
->Set(stBuf
.st_mtime
);
2622 dtCreate
->Set(stBuf
.st_ctime
);
2626 #else // other platform
2627 wxUnusedVar(dtAccess
);
2629 wxUnusedVar(dtCreate
);
2632 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2633 GetFullPath().c_str());
2638 #endif // wxUSE_DATETIME
2641 // ----------------------------------------------------------------------------
2642 // file size functions
2643 // ----------------------------------------------------------------------------
2648 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2650 if (!wxFileExists(filename
))
2651 return wxInvalidSize
;
2653 #if defined(__WXPALMOS__)
2655 return wxInvalidSize
;
2656 #elif defined(__WIN32__)
2657 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2659 return wxInvalidSize
;
2661 DWORD lpFileSizeHigh
;
2662 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2663 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2664 return wxInvalidSize
;
2666 return wxULongLong(lpFileSizeHigh
, ret
);
2667 #else // ! __WIN32__
2669 if (wxStat( filename
, &st
) != 0)
2670 return wxInvalidSize
;
2671 return wxULongLong(st
.st_size
);
2676 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2677 const wxString
&nullsize
,
2679 wxSizeConvention conv
)
2681 // deal with trivial case first
2682 if ( bs
== 0 || bs
== wxInvalidSize
)
2685 // depending on the convention used the multiplier may be either 1000 or
2686 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2687 double multiplier
= 1024.;
2692 case wxSIZE_CONV_TRADITIONAL
:
2693 // nothing to do, this corresponds to the default values of both
2694 // the multiplier and infix string
2697 case wxSIZE_CONV_IEC
:
2701 case wxSIZE_CONV_SI
:
2706 const double kiloByteSize
= multiplier
;
2707 const double megaByteSize
= multiplier
* kiloByteSize
;
2708 const double gigaByteSize
= multiplier
* megaByteSize
;
2709 const double teraByteSize
= multiplier
* gigaByteSize
;
2711 const double bytesize
= bs
.ToDouble();
2714 if ( bytesize
< kiloByteSize
)
2715 result
.Printf("%s B", bs
.ToString());
2716 else if ( bytesize
< megaByteSize
)
2717 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2718 else if (bytesize
< gigaByteSize
)
2719 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2720 else if (bytesize
< teraByteSize
)
2721 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2723 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2728 wxULongLong
wxFileName::GetSize() const
2730 return GetSize(GetFullPath());
2733 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2735 wxSizeConvention conv
) const
2737 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2740 #endif // wxUSE_LONGLONG
2742 // ----------------------------------------------------------------------------
2743 // Mac-specific functions
2744 // ----------------------------------------------------------------------------
2746 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2751 class MacDefaultExtensionRecord
2754 MacDefaultExtensionRecord()
2760 // default copy ctor, assignment operator and dtor are ok
2762 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2766 m_creator
= creator
;
2774 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2776 bool gMacDefaultExtensionsInited
= false;
2778 #include "wx/arrimpl.cpp"
2780 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2782 MacDefaultExtensionArray gMacDefaultExtensions
;
2784 // load the default extensions
2785 const MacDefaultExtensionRecord gDefaults
[] =
2787 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2788 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2789 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2792 void MacEnsureDefaultExtensionsLoaded()
2794 if ( !gMacDefaultExtensionsInited
)
2796 // we could load the pc exchange prefs here too
2797 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2799 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2801 gMacDefaultExtensionsInited
= true;
2805 } // anonymous namespace
2807 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2810 FSCatalogInfo catInfo
;
2813 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2815 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2817 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2818 finfo
->fileType
= type
;
2819 finfo
->fileCreator
= creator
;
2820 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2827 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2830 FSCatalogInfo catInfo
;
2833 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2835 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2837 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2838 *type
= finfo
->fileType
;
2839 *creator
= finfo
->fileCreator
;
2846 bool wxFileName::MacSetDefaultTypeAndCreator()
2848 wxUint32 type
, creator
;
2849 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2852 return MacSetTypeAndCreator( type
, creator
) ;
2857 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2859 MacEnsureDefaultExtensionsLoaded() ;
2860 wxString extl
= ext
.Lower() ;
2861 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2863 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2865 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2866 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2873 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2875 MacEnsureDefaultExtensionsLoaded();
2876 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2877 gMacDefaultExtensions
.Add( rec
);
2880 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON