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
152 #define S_ISREG(mode) ((mode) & S_IFREG)
155 #define S_ISDIR(mode) ((mode) & S_IFDIR)
159 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
160 #endif // wxUSE_LONGLONG
165 // ----------------------------------------------------------------------------
167 // ----------------------------------------------------------------------------
169 // small helper class which opens and closes the file - we use it just to get
170 // a file handle for the given file name to pass it to some Win32 API function
171 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
182 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
184 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
185 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
186 // be changed when we open it because this class is used for setting
187 // access time (see #10567)
188 m_hFile
= ::CreateFile
190 filename
.t_str(), // name
191 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
192 : FILE_WRITE_ATTRIBUTES
,
193 FILE_SHARE_READ
| // sharing mode
194 FILE_SHARE_WRITE
, // (allow everything)
195 NULL
, // no secutity attr
196 OPEN_EXISTING
, // creation disposition
198 NULL
// no template file
201 if ( m_hFile
== INVALID_HANDLE_VALUE
)
203 if ( mode
== ReadAttr
)
205 wxLogSysError(_("Failed to open '%s' for reading"),
210 wxLogSysError(_("Failed to open '%s' for writing"),
218 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
220 if ( !::CloseHandle(m_hFile
) )
222 wxLogSysError(_("Failed to close file handle"));
227 // return true only if the file could be opened successfully
228 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
231 operator HANDLE() const { return m_hFile
; }
239 // ----------------------------------------------------------------------------
241 // ----------------------------------------------------------------------------
243 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
245 // convert between wxDateTime and FILETIME which is a 64-bit value representing
246 // the number of 100-nanosecond intervals since January 1, 1601.
248 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
250 FILETIME ftcopy
= ft
;
252 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
254 wxLogLastError(wxT("FileTimeToLocalFileTime"));
258 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
260 wxLogLastError(wxT("FileTimeToSystemTime"));
263 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
264 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
267 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
270 st
.wDay
= dt
.GetDay();
271 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
272 st
.wYear
= (WORD
)dt
.GetYear();
273 st
.wHour
= dt
.GetHour();
274 st
.wMinute
= dt
.GetMinute();
275 st
.wSecond
= dt
.GetSecond();
276 st
.wMilliseconds
= dt
.GetMillisecond();
279 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
281 wxLogLastError(wxT("SystemTimeToFileTime"));
284 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
286 wxLogLastError(wxT("LocalFileTimeToFileTime"));
290 #endif // wxUSE_DATETIME && __WIN32__
292 // return a string with the volume par
293 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
297 if ( !volume
.empty() )
299 format
= wxFileName::GetFormat(format
);
301 // Special Windows UNC paths hack, part 2: undo what we did in
302 // SplitPath() and make an UNC path if we have a drive which is not a
303 // single letter (hopefully the network shares can't be one letter only
304 // although I didn't find any authoritative docs on this)
305 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
307 // We also have to check for Windows unique volume names here and
308 // return it with '\\?\' prepended to it
309 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume
+ "\\",
312 path
<< "\\\\?\\" << volume
;
316 // it must be a UNC path
317 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
320 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
322 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
330 // return true if the character is a DOS path separator i.e. either a slash or
332 inline bool IsDOSPathSep(wxUniChar ch
)
334 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
337 // return true if the format used is the DOS/Windows one and the string looks
339 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
341 return format
== wxPATH_DOS
&&
342 path
.length() >= 4 && // "\\a" can't be a UNC path
343 IsDOSPathSep(path
[0u]) &&
344 IsDOSPathSep(path
[1u]) &&
345 !IsDOSPathSep(path
[2u]);
348 // ----------------------------------------------------------------------------
350 // ----------------------------------------------------------------------------
352 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
353 static const size_t wxMSWUniqueVolumePrefixLength
= 49;
355 } // anonymous namespace
357 // ============================================================================
359 // ============================================================================
361 // ----------------------------------------------------------------------------
362 // wxFileName construction
363 // ----------------------------------------------------------------------------
365 void wxFileName::Assign( const wxFileName
&filepath
)
367 m_volume
= filepath
.GetVolume();
368 m_dirs
= filepath
.GetDirs();
369 m_name
= filepath
.GetName();
370 m_ext
= filepath
.GetExt();
371 m_relative
= filepath
.m_relative
;
372 m_hasExt
= filepath
.m_hasExt
;
375 void wxFileName::Assign(const wxString
& volume
,
376 const wxString
& path
,
377 const wxString
& name
,
382 // we should ignore paths which look like UNC shares because we already
383 // have the volume here and the UNC notation (\\server\path) is only valid
384 // for paths which don't start with a volume, so prevent SetPath() from
385 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
387 // note also that this is a rather ugly way to do what we want (passing
388 // some kind of flag telling to ignore UNC paths to SetPath() would be
389 // better) but this is the safest thing to do to avoid breaking backwards
390 // compatibility in 2.8
391 if ( IsUNCPath(path
, format
) )
393 // remove one of the 2 leading backslashes to ensure that it's not
394 // recognized as an UNC path by SetPath()
395 wxString
pathNonUNC(path
, 1, wxString::npos
);
396 SetPath(pathNonUNC
, format
);
398 else // no UNC complications
400 SetPath(path
, format
);
410 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
414 if ( pathOrig
.empty() )
422 format
= GetFormat( format
);
424 // 0) deal with possible volume part first
427 SplitVolume(pathOrig
, &volume
, &path
, format
);
428 if ( !volume
.empty() )
435 // 1) Determine if the path is relative or absolute.
439 // we had only the volume
443 wxChar leadingChar
= path
[0u];
448 m_relative
= leadingChar
== wxT(':');
450 // We then remove a leading ":". The reason is in our
451 // storage form for relative paths:
452 // ":dir:file.txt" actually means "./dir/file.txt" in
453 // DOS notation and should get stored as
454 // (relative) (dir) (file.txt)
455 // "::dir:file.txt" actually means "../dir/file.txt"
456 // stored as (relative) (..) (dir) (file.txt)
457 // This is important only for the Mac as an empty dir
458 // actually means <UP>, whereas under DOS, double
459 // slashes can be ignored: "\\\\" is the same as "\\".
465 // TODO: what is the relative path format here?
470 wxFAIL_MSG( wxT("Unknown path format") );
471 // !! Fall through !!
474 m_relative
= leadingChar
!= wxT('/');
478 m_relative
= !IsPathSeparator(leadingChar
, format
);
483 // 2) Break up the path into its members. If the original path
484 // was just "/" or "\\", m_dirs will be empty. We know from
485 // the m_relative field, if this means "nothing" or "root dir".
487 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
489 while ( tn
.HasMoreTokens() )
491 wxString token
= tn
.GetNextToken();
493 // Remove empty token under DOS and Unix, interpret them
497 if (format
== wxPATH_MAC
)
498 m_dirs
.Add( wxT("..") );
508 void wxFileName::Assign(const wxString
& fullpath
,
511 wxString volume
, path
, name
, ext
;
513 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
515 Assign(volume
, path
, name
, ext
, hasExt
, format
);
518 void wxFileName::Assign(const wxString
& fullpathOrig
,
519 const wxString
& fullname
,
522 // always recognize fullpath as directory, even if it doesn't end with a
524 wxString fullpath
= fullpathOrig
;
525 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
527 fullpath
+= GetPathSeparator(format
);
530 wxString volume
, path
, name
, ext
;
533 // do some consistency checks: the name should be really just the filename
534 // and the path should be really just a path
535 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
537 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
539 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
540 wxT("the file name shouldn't contain the path") );
542 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
545 // This test makes no sense on an OpenVMS system.
546 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
547 wxT("the path shouldn't contain file name nor extension") );
549 Assign(volume
, path
, name
, ext
, hasExt
, format
);
552 void wxFileName::Assign(const wxString
& pathOrig
,
553 const wxString
& name
,
559 SplitVolume(pathOrig
, &volume
, &path
, format
);
561 Assign(volume
, path
, name
, ext
, format
);
564 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
566 Assign(dir
, wxEmptyString
, format
);
569 void wxFileName::Clear()
575 m_ext
= wxEmptyString
;
577 // we don't have any absolute path for now
585 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
587 return wxFileName(file
, format
);
591 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
594 fn
.AssignDir(dir
, format
);
598 // ----------------------------------------------------------------------------
600 // ----------------------------------------------------------------------------
605 // Flags for wxFileSystemObjectExists() asking it to check for:
608 wxFileSystemObject_File
= 1, // file existence
609 wxFileSystemObject_Dir
= 2, // directory existence
610 wxFileSystemObject_Other
= 4, // existence of something else, e.g.
611 // device, socket, FIFO under Unix
612 wxFileSystemObject_Any
= 7 // existence of anything at all
615 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
617 void RemoveTrailingSeparatorsFromPath(wxString
& strPath
)
619 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
620 // so remove all trailing backslashes from the path - but don't do this for
621 // the paths "d:\" (which are different from "d:"), for just "\" or for
622 // windows unique volume names ("\\?\Volume{GUID}\")
623 while ( wxEndsWithPathSeparator( strPath
) )
625 size_t len
= strPath
.length();
626 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) ||
627 (len
== wxMSWUniqueVolumePrefixLength
&&
628 wxFileName::IsMSWUniqueVolumeNamePath(strPath
)))
633 strPath
.Truncate(len
- 1);
637 #endif // __WINDOWS__ || __OS2__
639 bool wxFileSystemObjectExists(const wxString
& path
, int flags
)
641 // Should the existence of file/directory with this name be accepted, i.e.
642 // result in the true return value from this function?
643 const bool acceptFile
= flags
& wxFileSystemObject_File
;
644 const bool acceptDir
= flags
& wxFileSystemObject_Dir
;
646 wxString
strPath(path
);
648 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
651 // Ensure that the path doesn't have any trailing separators when
652 // checking for directories.
653 RemoveTrailingSeparatorsFromPath(strPath
);
656 // we must use GetFileAttributes() instead of the ANSI C functions because
657 // it can cope with network (UNC) paths unlike them
658 DWORD ret
= ::GetFileAttributes(path
.t_str());
660 if ( ret
== INVALID_FILE_ATTRIBUTES
)
663 if ( ret
& FILE_ATTRIBUTE_DIRECTORY
)
666 // Anything else must be a file (perhaps we should check for
667 // FILE_ATTRIBUTE_REPARSE_POINT?)
669 #elif defined(__OS2__)
672 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
673 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
677 FILESTATUS3 Info
= {{0}};
678 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
679 (void*) &Info
, sizeof(FILESTATUS3
));
681 if ( rc
== NO_ERROR
)
683 if ( Info
.attrFile
& FILE_DIRECTORY
)
689 // We consider that the path must exist if we get a sharing violation for
690 // it but we don't know what is it in this case.
691 if ( rc
== ERROR_SHARING_VIOLATION
)
692 return flags
& wxFileSystemObject_Other
;
694 // Any other error (usually ERROR_PATH_NOT_FOUND), means there is nothing
697 #else // Non-MSW, non-OS/2
699 if ( wxStat(strPath
, &st
) != 0 )
702 if ( S_ISREG(st
.st_mode
) )
704 if ( S_ISDIR(st
.st_mode
) )
707 return flags
& wxFileSystemObject_Other
;
711 } // anonymous namespace
713 bool wxFileName::FileExists() const
715 return wxFileName::FileExists( GetFullPath() );
719 bool wxFileName::FileExists( const wxString
&filePath
)
721 return wxFileSystemObjectExists(filePath
, wxFileSystemObject_File
);
724 bool wxFileName::DirExists() const
726 return wxFileName::DirExists( GetPath() );
730 bool wxFileName::DirExists( const wxString
&dirPath
)
732 return wxFileSystemObjectExists(dirPath
, wxFileSystemObject_Dir
);
735 // ----------------------------------------------------------------------------
736 // CWD and HOME stuff
737 // ----------------------------------------------------------------------------
739 void wxFileName::AssignCwd(const wxString
& volume
)
741 AssignDir(wxFileName::GetCwd(volume
));
745 wxString
wxFileName::GetCwd(const wxString
& volume
)
747 // if we have the volume, we must get the current directory on this drive
748 // and to do this we have to chdir to this volume - at least under Windows,
749 // I don't know how to get the current drive on another volume elsewhere
752 if ( !volume
.empty() )
755 SetCwd(volume
+ GetVolumeSeparator());
758 wxString cwd
= ::wxGetCwd();
760 if ( !volume
.empty() )
768 bool wxFileName::SetCwd() const
770 return wxFileName::SetCwd( GetPath() );
773 bool wxFileName::SetCwd( const wxString
&cwd
)
775 return ::wxSetWorkingDirectory( cwd
);
778 void wxFileName::AssignHomeDir()
780 AssignDir(wxFileName::GetHomeDir());
783 wxString
wxFileName::GetHomeDir()
785 return ::wxGetHomeDir();
789 // ----------------------------------------------------------------------------
790 // CreateTempFileName
791 // ----------------------------------------------------------------------------
793 #if wxUSE_FILE || wxUSE_FFILE
796 #if !defined wx_fdopen && defined HAVE_FDOPEN
797 #define wx_fdopen fdopen
800 // NB: GetTempFileName() under Windows creates the file, so using
801 // O_EXCL there would fail
803 #define wxOPEN_EXCL 0
805 #define wxOPEN_EXCL O_EXCL
809 #ifdef wxOpenOSFHandle
810 #define WX_HAVE_DELETE_ON_CLOSE
811 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
813 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
815 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
817 DWORD disposition
= OPEN_ALWAYS
;
819 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
820 FILE_FLAG_DELETE_ON_CLOSE
;
822 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
823 disposition
, attributes
, NULL
);
825 return wxOpenOSFHandle(h
, wxO_BINARY
);
827 #endif // wxOpenOSFHandle
830 // Helper to open the file
832 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
834 #ifdef WX_HAVE_DELETE_ON_CLOSE
836 return wxOpenWithDeleteOnClose(path
);
839 *deleteOnClose
= false;
841 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
846 // Helper to open the file and attach it to the wxFFile
848 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
851 *deleteOnClose
= false;
852 return file
->Open(path
, wxT("w+b"));
854 int fd
= wxTempOpen(path
, deleteOnClose
);
857 file
->Attach(wx_fdopen(fd
, "w+b"), path
);
858 return file
->IsOpened();
861 #endif // wxUSE_FFILE
865 #define WXFILEARGS(x, y) y
867 #define WXFILEARGS(x, y) x
869 #define WXFILEARGS(x, y) x, y
873 // Implementation of wxFileName::CreateTempFileName().
875 static wxString
wxCreateTempImpl(
876 const wxString
& prefix
,
877 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
878 bool *deleteOnClose
= NULL
)
880 #if wxUSE_FILE && wxUSE_FFILE
881 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
883 wxString path
, dir
, name
;
884 bool wantDeleteOnClose
= false;
888 // set the result to false initially
889 wantDeleteOnClose
= *deleteOnClose
;
890 *deleteOnClose
= false;
894 // easier if it alwasys points to something
895 deleteOnClose
= &wantDeleteOnClose
;
898 // use the directory specified by the prefix
899 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
903 dir
= wxFileName::GetTempDir();
906 #if defined(__WXWINCE__)
907 path
= dir
+ wxT("\\") + name
;
909 while (wxFileName::FileExists(path
))
911 path
= dir
+ wxT("\\") + name
;
916 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
917 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
918 wxStringBuffer(path
, MAX_PATH
+ 1)))
920 wxLogLastError(wxT("GetTempFileName"));
928 if ( !wxEndsWithPathSeparator(dir
) &&
929 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
931 path
+= wxFILE_SEP_PATH
;
936 #if defined(HAVE_MKSTEMP)
937 // scratch space for mkstemp()
938 path
+= wxT("XXXXXX");
940 // we need to copy the path to the buffer in which mkstemp() can modify it
941 wxCharBuffer
buf(path
.fn_str());
943 // cast is safe because the string length doesn't change
944 int fdTemp
= mkstemp( (char*)(const char*) buf
);
947 // this might be not necessary as mkstemp() on most systems should have
948 // already done it but it doesn't hurt neither...
951 else // mkstemp() succeeded
953 path
= wxConvFile
.cMB2WX( (const char*) buf
);
956 // avoid leaking the fd
959 fileTemp
->Attach(fdTemp
);
968 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"), path
);
970 ffileTemp
->Open(path
, wxT("r+b"));
981 #else // !HAVE_MKSTEMP
985 path
+= wxT("XXXXXX");
987 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
988 if ( !mktemp( (char*)(const char*) buf
) )
994 path
= wxConvFile
.cMB2WX( (const char*) buf
);
996 #else // !HAVE_MKTEMP (includes __DOS__)
997 // generate the unique file name ourselves
998 #if !defined(__DOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
999 path
<< (unsigned int)getpid();
1004 static const size_t numTries
= 1000;
1005 for ( size_t n
= 0; n
< numTries
; n
++ )
1007 // 3 hex digits is enough for numTries == 1000 < 4096
1008 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
1009 if ( !wxFileName::FileExists(pathTry
) )
1018 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
1020 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
1022 #endif // Windows/!Windows
1026 wxLogSysError(_("Failed to create a temporary file name"));
1032 // open the file - of course, there is a race condition here, this is
1033 // why we always prefer using mkstemp()...
1035 if ( fileTemp
&& !fileTemp
->IsOpened() )
1037 *deleteOnClose
= wantDeleteOnClose
;
1038 int fd
= wxTempOpen(path
, deleteOnClose
);
1040 fileTemp
->Attach(fd
);
1047 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1049 *deleteOnClose
= wantDeleteOnClose
;
1050 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1056 // FIXME: If !ok here should we loop and try again with another
1057 // file name? That is the standard recourse if open(O_EXCL)
1058 // fails, though of course it should be protected against
1059 // possible infinite looping too.
1061 wxLogError(_("Failed to open temporary file."));
1071 static bool wxCreateTempImpl(
1072 const wxString
& prefix
,
1073 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1076 bool deleteOnClose
= true;
1078 *name
= wxCreateTempImpl(prefix
,
1079 WXFILEARGS(fileTemp
, ffileTemp
),
1082 bool ok
= !name
->empty();
1087 else if (ok
&& wxRemoveFile(*name
))
1095 static void wxAssignTempImpl(
1097 const wxString
& prefix
,
1098 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1101 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1103 if ( tempname
.empty() )
1105 // error, failed to get temp file name
1110 fn
->Assign(tempname
);
1115 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1117 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1121 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1123 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1126 #endif // wxUSE_FILE || wxUSE_FFILE
1131 wxString
wxCreateTempFileName(const wxString
& prefix
,
1133 bool *deleteOnClose
)
1135 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1138 bool wxCreateTempFile(const wxString
& prefix
,
1142 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1145 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1147 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1152 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1154 return wxCreateTempFileName(prefix
, fileTemp
);
1157 #endif // wxUSE_FILE
1162 wxString
wxCreateTempFileName(const wxString
& prefix
,
1164 bool *deleteOnClose
)
1166 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1169 bool wxCreateTempFile(const wxString
& prefix
,
1173 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1177 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1179 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1184 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1186 return wxCreateTempFileName(prefix
, fileTemp
);
1189 #endif // wxUSE_FFILE
1192 // ----------------------------------------------------------------------------
1193 // directory operations
1194 // ----------------------------------------------------------------------------
1196 // helper of GetTempDir(): check if the given directory exists and return it if
1197 // it does or an empty string otherwise
1201 wxString
CheckIfDirExists(const wxString
& dir
)
1203 return wxFileName::DirExists(dir
) ? dir
: wxString();
1206 } // anonymous namespace
1208 wxString
wxFileName::GetTempDir()
1210 // first try getting it from environment: this allows overriding the values
1211 // used by default if the user wants to create temporary files in another
1213 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1216 dir
= CheckIfDirExists(wxGetenv("TMP"));
1218 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1221 // if no environment variables are set, use the system default
1224 #if defined(__WXWINCE__)
1225 dir
= CheckIfDirExists(wxT("\\temp"));
1226 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1227 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1229 wxLogLastError(wxT("GetTempPath"));
1231 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1232 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1233 #endif // systems with native way
1235 else // we got directory from an environment variable
1237 // remove any trailing path separators, we don't want to ever return
1238 // them from this function for consistency
1239 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1240 if ( lastNonSep
== wxString::npos
)
1242 // the string consists entirely of separators, leave only one
1243 dir
= GetPathSeparator();
1247 dir
.erase(lastNonSep
+ 1);
1251 // fall back to hard coded value
1254 #ifdef __UNIX_LIKE__
1255 dir
= CheckIfDirExists("/tmp");
1257 #endif // __UNIX_LIKE__
1264 bool wxFileName::Mkdir( int perm
, int flags
) const
1266 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1269 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1271 if ( flags
& wxPATH_MKDIR_FULL
)
1273 // split the path in components
1274 wxFileName filename
;
1275 filename
.AssignDir(dir
);
1278 if ( filename
.HasVolume())
1280 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1283 wxArrayString dirs
= filename
.GetDirs();
1284 size_t count
= dirs
.GetCount();
1285 for ( size_t i
= 0; i
< count
; i
++ )
1287 if ( i
> 0 || filename
.IsAbsolute() )
1288 currPath
+= wxFILE_SEP_PATH
;
1289 currPath
+= dirs
[i
];
1291 if (!DirExists(currPath
))
1293 if (!wxMkdir(currPath
, perm
))
1295 // no need to try creating further directories
1305 return ::wxMkdir( dir
, perm
);
1308 bool wxFileName::Rmdir(int flags
) const
1310 return wxFileName::Rmdir( GetPath(), flags
);
1313 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1316 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1318 // SHFileOperation needs double null termination string
1319 // but without separator at the end of the path
1321 if ( path
.Last() == wxFILE_SEP_PATH
)
1325 SHFILEOPSTRUCT fileop
;
1326 wxZeroMemory(fileop
);
1327 fileop
.wFunc
= FO_DELETE
;
1328 #if defined(__CYGWIN__) && defined(wxUSE_UNICODE)
1329 fileop
.pFrom
= path
.wc_str();
1331 fileop
.pFrom
= path
.fn_str();
1333 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1335 // FOF_NOERRORUI is not defined in WinCE
1336 fileop
.fFlags
|= FOF_NOERRORUI
;
1339 int ret
= SHFileOperation(&fileop
);
1342 // SHFileOperation may return non-Win32 error codes, so the error
1343 // message can be incorrect
1344 wxLogApiError(wxT("SHFileOperation"), ret
);
1350 else if ( flags
& wxPATH_RMDIR_FULL
)
1352 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1353 #endif // !__WXMSW__
1356 if ( path
.Last() != wxFILE_SEP_PATH
)
1357 path
+= wxFILE_SEP_PATH
;
1361 if ( !d
.IsOpened() )
1366 // first delete all subdirectories
1367 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1370 wxFileName::Rmdir(path
+ filename
, flags
);
1371 cont
= d
.GetNext(&filename
);
1375 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1377 // delete all files too
1378 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1381 ::wxRemoveFile(path
+ filename
);
1382 cont
= d
.GetNext(&filename
);
1385 #endif // !__WXMSW__
1388 return ::wxRmdir(dir
);
1391 // ----------------------------------------------------------------------------
1392 // path normalization
1393 // ----------------------------------------------------------------------------
1395 bool wxFileName::Normalize(int flags
,
1396 const wxString
& cwd
,
1397 wxPathFormat format
)
1399 // deal with env vars renaming first as this may seriously change the path
1400 if ( flags
& wxPATH_NORM_ENV_VARS
)
1402 wxString pathOrig
= GetFullPath(format
);
1403 wxString path
= wxExpandEnvVars(pathOrig
);
1404 if ( path
!= pathOrig
)
1410 // the existing path components
1411 wxArrayString dirs
= GetDirs();
1413 // the path to prepend in front to make the path absolute
1416 format
= GetFormat(format
);
1418 // set up the directory to use for making the path absolute later
1419 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1423 curDir
.AssignCwd(GetVolume());
1425 else // cwd provided
1427 curDir
.AssignDir(cwd
);
1431 // handle ~ stuff under Unix only
1432 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1434 if ( !dirs
.IsEmpty() )
1436 wxString dir
= dirs
[0u];
1437 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1439 // to make the path absolute use the home directory
1440 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1446 // transform relative path into abs one
1447 if ( curDir
.IsOk() )
1449 // this path may be relative because it doesn't have the volume name
1450 // and still have m_relative=true; in this case we shouldn't modify
1451 // our directory components but just set the current volume
1452 if ( !HasVolume() && curDir
.HasVolume() )
1454 SetVolume(curDir
.GetVolume());
1458 // yes, it was the case - we don't need curDir then
1463 // finally, prepend curDir to the dirs array
1464 wxArrayString dirsNew
= curDir
.GetDirs();
1465 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1467 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1468 // return for some reason an absolute path, then curDir maybe not be absolute!
1469 if ( !curDir
.m_relative
)
1471 // we have prepended an absolute path and thus we are now an absolute
1475 // else if (flags & wxPATH_NORM_ABSOLUTE):
1476 // should we warn the user that we didn't manage to make the path absolute?
1479 // now deal with ".", ".." and the rest
1481 size_t count
= dirs
.GetCount();
1482 for ( size_t n
= 0; n
< count
; n
++ )
1484 wxString dir
= dirs
[n
];
1486 if ( flags
& wxPATH_NORM_DOTS
)
1488 if ( dir
== wxT(".") )
1494 if ( dir
== wxT("..") )
1496 if ( m_dirs
.empty() )
1498 // We have more ".." than directory components so far.
1499 // Don't treat this as an error as the path could have been
1500 // entered by user so try to handle it reasonably: if the
1501 // path is absolute, just ignore the extra ".." because
1502 // "/.." is the same as "/". Otherwise, i.e. for relative
1503 // paths, keep ".." unchanged because removing it would
1504 // modify the file a relative path refers to.
1509 else // Normal case, go one step up.
1520 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1521 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1524 if (GetShortcutTarget(GetFullPath(format
), filename
))
1532 #if defined(__WIN32__)
1533 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1535 Assign(GetLongPath());
1539 // Change case (this should be kept at the end of the function, to ensure
1540 // that the path doesn't change any more after we normalize its case)
1541 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1543 m_volume
.MakeLower();
1547 // directory entries must be made lower case as well
1548 count
= m_dirs
.GetCount();
1549 for ( size_t i
= 0; i
< count
; i
++ )
1551 m_dirs
[i
].MakeLower();
1559 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1560 const wxString
& replacementFmtString
,
1561 wxPathFormat format
)
1563 // look into stringForm for the contents of the given environment variable
1565 if (envname
.empty() ||
1566 !wxGetEnv(envname
, &val
))
1571 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1572 // do not touch the file name and the extension
1574 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1575 stringForm
.Replace(val
, replacement
);
1577 // Now assign ourselves the modified path:
1578 Assign(stringForm
, GetFullName(), format
);
1584 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1586 wxString homedir
= wxGetHomeDir();
1587 if (homedir
.empty())
1590 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1591 // do not touch the file name and the extension
1593 stringForm
.Replace(homedir
, "~");
1595 // Now assign ourselves the modified path:
1596 Assign(stringForm
, GetFullName(), format
);
1601 // ----------------------------------------------------------------------------
1602 // get the shortcut target
1603 // ----------------------------------------------------------------------------
1605 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1606 // The .lnk file is a plain text file so it should be easy to
1607 // make it work. Hint from Google Groups:
1608 // "If you open up a lnk file, you'll see a
1609 // number, followed by a pound sign (#), followed by more text. The
1610 // number is the number of characters that follows the pound sign. The
1611 // characters after the pound sign are the command line (which _can_
1612 // include arguments) to be executed. Any path (e.g. \windows\program
1613 // files\myapp.exe) that includes spaces needs to be enclosed in
1614 // quotation marks."
1616 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1617 // The following lines are necessary under WinCE
1618 // #include "wx/msw/private.h"
1619 // #include <ole2.h>
1621 #if defined(__WXWINCE__)
1622 #include <shlguid.h>
1625 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1626 wxString
& targetFilename
,
1627 wxString
* arguments
) const
1629 wxString path
, file
, ext
;
1630 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1634 bool success
= false;
1636 // Assume it's not a shortcut if it doesn't end with lnk
1637 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1640 // create a ShellLink object
1641 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1642 IID_IShellLink
, (LPVOID
*) &psl
);
1644 if (SUCCEEDED(hres
))
1647 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1648 if (SUCCEEDED(hres
))
1650 WCHAR wsz
[MAX_PATH
];
1652 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1655 hres
= ppf
->Load(wsz
, 0);
1658 if (SUCCEEDED(hres
))
1661 // Wrong prototype in early versions
1662 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1663 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1665 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1667 targetFilename
= wxString(buf
);
1668 success
= (shortcutPath
!= targetFilename
);
1670 psl
->GetArguments(buf
, 2048);
1672 if (!args
.empty() && arguments
)
1684 #endif // __WIN32__ && !__WXWINCE__
1687 // ----------------------------------------------------------------------------
1688 // absolute/relative paths
1689 // ----------------------------------------------------------------------------
1691 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1693 // unix paths beginning with ~ are reported as being absolute
1694 if ( format
== wxPATH_UNIX
)
1696 if ( !m_dirs
.IsEmpty() )
1698 wxString dir
= m_dirs
[0u];
1700 if (!dir
.empty() && dir
[0u] == wxT('~'))
1705 // if our path doesn't start with a path separator, it's not an absolute
1710 if ( !GetVolumeSeparator(format
).empty() )
1712 // this format has volumes and an absolute path must have one, it's not
1713 // enough to have the full path to be an absolute file under Windows
1714 if ( GetVolume().empty() )
1721 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1723 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1725 // get cwd only once - small time saving
1726 wxString cwd
= wxGetCwd();
1727 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1728 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1730 bool withCase
= IsCaseSensitive(format
);
1732 // we can't do anything if the files live on different volumes
1733 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1739 // same drive, so we don't need our volume
1742 // remove common directories starting at the top
1743 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1744 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1747 fnBase
.m_dirs
.RemoveAt(0);
1750 // add as many ".." as needed
1751 size_t count
= fnBase
.m_dirs
.GetCount();
1752 for ( size_t i
= 0; i
< count
; i
++ )
1754 m_dirs
.Insert(wxT(".."), 0u);
1757 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1759 // a directory made relative with respect to itself is '.' under Unix
1760 // and DOS, by definition (but we don't have to insert "./" for the
1762 if ( m_dirs
.IsEmpty() && IsDir() )
1764 m_dirs
.Add(wxT('.'));
1774 // ----------------------------------------------------------------------------
1775 // filename kind tests
1776 // ----------------------------------------------------------------------------
1778 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1780 wxFileName fn1
= *this,
1783 // get cwd only once - small time saving
1784 wxString cwd
= wxGetCwd();
1785 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1786 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1788 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1791 // TODO: compare inodes for Unix, this works even when filenames are
1792 // different but files are the same (symlinks) (VZ)
1798 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1800 // only Unix filenames are truely case-sensitive
1801 return GetFormat(format
) == wxPATH_UNIX
;
1805 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1807 // Inits to forbidden characters that are common to (almost) all platforms.
1808 wxString strForbiddenChars
= wxT("*?");
1810 // If asserts, wxPathFormat has been changed. In case of a new path format
1811 // addition, the following code might have to be updated.
1812 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1813 switch ( GetFormat(format
) )
1816 wxFAIL_MSG( wxT("Unknown path format") );
1817 // !! Fall through !!
1823 // On a Mac even names with * and ? are allowed (Tested with OS
1824 // 9.2.1 and OS X 10.2.5)
1825 strForbiddenChars
= wxEmptyString
;
1829 strForbiddenChars
+= wxT("\\/:\"<>|");
1836 return strForbiddenChars
;
1840 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1843 return wxEmptyString
;
1847 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1848 (GetFormat(format
) == wxPATH_VMS
) )
1850 sepVol
= wxFILE_SEP_DSK
;
1859 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1862 switch ( GetFormat(format
) )
1865 // accept both as native APIs do but put the native one first as
1866 // this is the one we use in GetFullPath()
1867 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1871 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1875 seps
= wxFILE_SEP_PATH_UNIX
;
1879 seps
= wxFILE_SEP_PATH_MAC
;
1883 seps
= wxFILE_SEP_PATH_VMS
;
1891 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1893 format
= GetFormat(format
);
1895 // under VMS the end of the path is ']', not the path separator used to
1896 // separate the components
1897 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1901 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1903 // wxString::Find() doesn't work as expected with NUL - it will always find
1904 // it, so test for it separately
1905 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1910 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
1912 // return true if the format used is the DOS/Windows one and the string begins
1913 // with a Windows unique volume name ("\\?\Volume{guid}\")
1914 return format
== wxPATH_DOS
&&
1915 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
1916 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
1917 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
1920 // ----------------------------------------------------------------------------
1921 // path components manipulation
1922 // ----------------------------------------------------------------------------
1924 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1928 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1933 const size_t len
= dir
.length();
1934 for ( size_t n
= 0; n
< len
; n
++ )
1936 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1938 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1947 void wxFileName::AppendDir( const wxString
& dir
)
1949 if ( IsValidDirComponent(dir
) )
1953 void wxFileName::PrependDir( const wxString
& dir
)
1958 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1960 if ( IsValidDirComponent(dir
) )
1961 m_dirs
.Insert(dir
, before
);
1964 void wxFileName::RemoveDir(size_t pos
)
1966 m_dirs
.RemoveAt(pos
);
1969 // ----------------------------------------------------------------------------
1971 // ----------------------------------------------------------------------------
1973 void wxFileName::SetFullName(const wxString
& fullname
)
1975 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1976 &m_name
, &m_ext
, &m_hasExt
);
1979 wxString
wxFileName::GetFullName() const
1981 wxString fullname
= m_name
;
1984 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1990 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1992 format
= GetFormat( format
);
1996 // return the volume with the path as well if requested
1997 if ( flags
& wxPATH_GET_VOLUME
)
1999 fullpath
+= wxGetVolumeString(GetVolume(), format
);
2002 // the leading character
2007 fullpath
+= wxFILE_SEP_PATH_MAC
;
2012 fullpath
+= wxFILE_SEP_PATH_DOS
;
2016 wxFAIL_MSG( wxT("Unknown path format") );
2022 fullpath
+= wxFILE_SEP_PATH_UNIX
;
2027 // no leading character here but use this place to unset
2028 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
2029 // as, if I understand correctly, there should never be a dot
2030 // before the closing bracket
2031 flags
&= ~wxPATH_GET_SEPARATOR
;
2034 if ( m_dirs
.empty() )
2036 // there is nothing more
2040 // then concatenate all the path components using the path separator
2041 if ( format
== wxPATH_VMS
)
2043 fullpath
+= wxT('[');
2046 const size_t dirCount
= m_dirs
.GetCount();
2047 for ( size_t i
= 0; i
< dirCount
; i
++ )
2052 if ( m_dirs
[i
] == wxT(".") )
2054 // skip appending ':', this shouldn't be done in this
2055 // case as "::" is interpreted as ".." under Unix
2059 // convert back from ".." to nothing
2060 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2061 fullpath
+= m_dirs
[i
];
2065 wxFAIL_MSG( wxT("Unexpected path format") );
2066 // still fall through
2070 fullpath
+= m_dirs
[i
];
2074 // TODO: What to do with ".." under VMS
2076 // convert back from ".." to nothing
2077 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2078 fullpath
+= m_dirs
[i
];
2082 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2083 fullpath
+= GetPathSeparator(format
);
2086 if ( format
== wxPATH_VMS
)
2088 fullpath
+= wxT(']');
2094 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2096 // we already have a function to get the path
2097 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2100 // now just add the file name and extension to it
2101 fullpath
+= GetFullName();
2106 // Return the short form of the path (returns identity on non-Windows platforms)
2107 wxString
wxFileName::GetShortPath() const
2109 wxString
path(GetFullPath());
2111 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2112 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2116 if ( ::GetShortPathName
2119 wxStringBuffer(pathOut
, sz
),
2131 // Return the long form of the path (returns identity on non-Windows platforms)
2132 wxString
wxFileName::GetLongPath() const
2135 path
= GetFullPath();
2137 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2139 #if wxUSE_DYNLIB_CLASS
2140 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2142 // this is MT-safe as in the worst case we're going to resolve the function
2143 // twice -- but as the result is the same in both threads, it's ok
2144 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2145 if ( !s_pfnGetLongPathName
)
2147 static bool s_triedToLoad
= false;
2149 if ( !s_triedToLoad
)
2151 s_triedToLoad
= true;
2153 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2155 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2160 #endif // Unicode/ANSI
2162 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2164 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2165 dllKernel
.GetSymbol(GetLongPathName
);
2168 // note that kernel32.dll can be unloaded, it stays in memory
2169 // anyhow as all Win32 programs link to it and so it's safe to call
2170 // GetLongPathName() even after unloading it
2174 if ( s_pfnGetLongPathName
)
2176 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2179 if ( (*s_pfnGetLongPathName
)
2182 wxStringBuffer(pathOut
, dwSize
),
2190 #endif // wxUSE_DYNLIB_CLASS
2192 // The OS didn't support GetLongPathName, or some other error.
2193 // We need to call FindFirstFile on each component in turn.
2195 WIN32_FIND_DATA findFileData
;
2199 pathOut
= GetVolume() +
2200 GetVolumeSeparator(wxPATH_DOS
) +
2201 GetPathSeparator(wxPATH_DOS
);
2203 pathOut
= wxEmptyString
;
2205 wxArrayString dirs
= GetDirs();
2206 dirs
.Add(GetFullName());
2210 size_t count
= dirs
.GetCount();
2211 for ( size_t i
= 0; i
< count
; i
++ )
2213 const wxString
& dir
= dirs
[i
];
2215 // We're using pathOut to collect the long-name path, but using a
2216 // temporary for appending the last path component which may be
2218 tmpPath
= pathOut
+ dir
;
2220 // We must not process "." or ".." here as they would be (unexpectedly)
2221 // replaced by the corresponding directory names so just leave them
2224 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2225 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2226 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2228 tmpPath
+= wxFILE_SEP_PATH
;
2233 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2234 if (hFind
== INVALID_HANDLE_VALUE
)
2236 // Error: most likely reason is that path doesn't exist, so
2237 // append any unprocessed parts and return
2238 for ( i
+= 1; i
< count
; i
++ )
2239 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2244 pathOut
+= findFileData
.cFileName
;
2245 if ( (i
< (count
-1)) )
2246 pathOut
+= wxFILE_SEP_PATH
;
2252 #endif // Win32/!Win32
2257 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2259 if (format
== wxPATH_NATIVE
)
2261 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2262 format
= wxPATH_DOS
;
2263 #elif defined(__VMS)
2264 format
= wxPATH_VMS
;
2266 format
= wxPATH_UNIX
;
2272 #ifdef wxHAS_FILESYSTEM_VOLUMES
2275 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2277 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2279 wxString
vol(drive
);
2280 vol
+= wxFILE_SEP_DSK
;
2281 if ( flags
& wxPATH_GET_SEPARATOR
)
2282 vol
+= wxFILE_SEP_PATH
;
2287 #endif // wxHAS_FILESYSTEM_VOLUMES
2289 // ----------------------------------------------------------------------------
2290 // path splitting function
2291 // ----------------------------------------------------------------------------
2295 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2296 wxString
*pstrVolume
,
2298 wxPathFormat format
)
2300 format
= GetFormat(format
);
2302 wxString fullpath
= fullpathWithVolume
;
2304 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2306 // special Windows unique volume names hack: transform
2307 // \\?\Volume{guid}\path into Volume{guid}:path
2308 // note: this check must be done before the check for UNC path
2310 // we know the last backslash from the unique volume name is located
2311 // there from IsMSWUniqueVolumeNamePath
2312 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2314 // paths starting with a unique volume name should always be absolute
2315 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2317 // remove the leading "\\?\" part
2318 fullpath
.erase(0, 4);
2320 else if ( IsUNCPath(fullpath
, format
) )
2322 // special Windows UNC paths hack: transform \\share\path into share:path
2324 fullpath
.erase(0, 2);
2326 size_t posFirstSlash
=
2327 fullpath
.find_first_of(GetPathTerminators(format
));
2328 if ( posFirstSlash
!= wxString::npos
)
2330 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2332 // UNC paths are always absolute, right? (FIXME)
2333 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2337 // We separate the volume here
2338 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2340 wxString sepVol
= GetVolumeSeparator(format
);
2342 // we have to exclude the case of a colon in the very beginning of the
2343 // string as it can't be a volume separator (nor can this be a valid
2344 // DOS file name at all but we'll leave dealing with this to our caller)
2345 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2346 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2350 *pstrVolume
= fullpath
.Left(posFirstColon
);
2353 // remove the volume name and the separator from the full path
2354 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2359 *pstrPath
= fullpath
;
2363 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2364 wxString
*pstrVolume
,
2369 wxPathFormat format
)
2371 format
= GetFormat(format
);
2374 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2376 // find the positions of the last dot and last path separator in the path
2377 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2378 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2380 // check whether this dot occurs at the very beginning of a path component
2381 if ( (posLastDot
!= wxString::npos
) &&
2383 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2384 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2386 // dot may be (and commonly -- at least under Unix -- is) the first
2387 // character of the filename, don't treat the entire filename as
2388 // extension in this case
2389 posLastDot
= wxString::npos
;
2392 // if we do have a dot and a slash, check that the dot is in the name part
2393 if ( (posLastDot
!= wxString::npos
) &&
2394 (posLastSlash
!= wxString::npos
) &&
2395 (posLastDot
< posLastSlash
) )
2397 // the dot is part of the path, not the start of the extension
2398 posLastDot
= wxString::npos
;
2401 // now fill in the variables provided by user
2404 if ( posLastSlash
== wxString::npos
)
2411 // take everything up to the path separator but take care to make
2412 // the path equal to something like '/', not empty, for the files
2413 // immediately under root directory
2414 size_t len
= posLastSlash
;
2416 // this rule does not apply to mac since we do not start with colons (sep)
2417 // except for relative paths
2418 if ( !len
&& format
!= wxPATH_MAC
)
2421 *pstrPath
= fullpath
.Left(len
);
2423 // special VMS hack: remove the initial bracket
2424 if ( format
== wxPATH_VMS
)
2426 if ( (*pstrPath
)[0u] == wxT('[') )
2427 pstrPath
->erase(0, 1);
2434 // take all characters starting from the one after the last slash and
2435 // up to, but excluding, the last dot
2436 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2438 if ( posLastDot
== wxString::npos
)
2440 // take all until the end
2441 count
= wxString::npos
;
2443 else if ( posLastSlash
== wxString::npos
)
2447 else // have both dot and slash
2449 count
= posLastDot
- posLastSlash
- 1;
2452 *pstrName
= fullpath
.Mid(nStart
, count
);
2455 // finally deal with the extension here: we have an added complication that
2456 // extension may be empty (but present) as in "foo." where trailing dot
2457 // indicates the empty extension at the end -- and hence we must remember
2458 // that we have it independently of pstrExt
2459 if ( posLastDot
== wxString::npos
)
2469 // take everything after the dot
2471 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2478 void wxFileName::SplitPath(const wxString
& fullpath
,
2482 wxPathFormat format
)
2485 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2489 path
->Prepend(wxGetVolumeString(volume
, format
));
2494 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2496 wxFileName
fn(fullpath
);
2498 return fn
.GetFullPath();
2501 // ----------------------------------------------------------------------------
2503 // ----------------------------------------------------------------------------
2507 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2508 const wxDateTime
*dtMod
,
2509 const wxDateTime
*dtCreate
) const
2511 #if defined(__WIN32__)
2512 FILETIME ftAccess
, ftCreate
, ftWrite
;
2515 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2517 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2519 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2525 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2527 wxLogError(_("Setting directory access times is not supported "
2528 "under this OS version"));
2533 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2537 path
= GetFullPath();
2541 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2544 if ( ::SetFileTime(fh
,
2545 dtCreate
? &ftCreate
: NULL
,
2546 dtAccess
? &ftAccess
: NULL
,
2547 dtMod
? &ftWrite
: NULL
) )
2552 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2553 wxUnusedVar(dtCreate
);
2555 if ( !dtAccess
&& !dtMod
)
2557 // can't modify the creation time anyhow, don't try
2561 // if dtAccess or dtMod is not specified, use the other one (which must be
2562 // non NULL because of the test above) for both times
2564 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2565 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2566 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2570 #else // other platform
2571 wxUnusedVar(dtAccess
);
2573 wxUnusedVar(dtCreate
);
2576 wxLogSysError(_("Failed to modify file times for '%s'"),
2577 GetFullPath().c_str());
2582 bool wxFileName::Touch() const
2584 #if defined(__UNIX_LIKE__)
2585 // under Unix touching file is simple: just pass NULL to utime()
2586 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2591 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2594 #else // other platform
2595 wxDateTime dtNow
= wxDateTime::Now();
2597 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2601 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2603 wxDateTime
*dtCreate
) const
2605 #if defined(__WIN32__)
2606 // we must use different methods for the files and directories under
2607 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2608 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2611 FILETIME ftAccess
, ftCreate
, ftWrite
;
2614 // implemented in msw/dir.cpp
2615 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2616 FILETIME
*, FILETIME
*, FILETIME
*);
2618 // we should pass the path without the trailing separator to
2619 // wxGetDirectoryTimes()
2620 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2621 &ftAccess
, &ftCreate
, &ftWrite
);
2625 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2628 ok
= ::GetFileTime(fh
,
2629 dtCreate
? &ftCreate
: NULL
,
2630 dtAccess
? &ftAccess
: NULL
,
2631 dtMod
? &ftWrite
: NULL
) != 0;
2642 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2644 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2646 ConvertFileTimeToWx(dtMod
, ftWrite
);
2650 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2651 // no need to test for IsDir() here
2653 if ( wxStat( GetFullPath(), &stBuf
) == 0 )
2656 dtAccess
->Set(stBuf
.st_atime
);
2658 dtMod
->Set(stBuf
.st_mtime
);
2660 dtCreate
->Set(stBuf
.st_ctime
);
2664 #else // other platform
2665 wxUnusedVar(dtAccess
);
2667 wxUnusedVar(dtCreate
);
2670 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2671 GetFullPath().c_str());
2676 #endif // wxUSE_DATETIME
2679 // ----------------------------------------------------------------------------
2680 // file size functions
2681 // ----------------------------------------------------------------------------
2686 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2688 if (!wxFileExists(filename
))
2689 return wxInvalidSize
;
2691 #if defined(__WIN32__)
2692 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2694 return wxInvalidSize
;
2696 DWORD lpFileSizeHigh
;
2697 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2698 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2699 return wxInvalidSize
;
2701 return wxULongLong(lpFileSizeHigh
, ret
);
2702 #else // ! __WIN32__
2704 if (wxStat( filename
, &st
) != 0)
2705 return wxInvalidSize
;
2706 return wxULongLong(st
.st_size
);
2711 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2712 const wxString
&nullsize
,
2714 wxSizeConvention conv
)
2716 // deal with trivial case first
2717 if ( bs
== 0 || bs
== wxInvalidSize
)
2720 // depending on the convention used the multiplier may be either 1000 or
2721 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2722 double multiplier
= 1024.;
2727 case wxSIZE_CONV_TRADITIONAL
:
2728 // nothing to do, this corresponds to the default values of both
2729 // the multiplier and infix string
2732 case wxSIZE_CONV_IEC
:
2736 case wxSIZE_CONV_SI
:
2741 const double kiloByteSize
= multiplier
;
2742 const double megaByteSize
= multiplier
* kiloByteSize
;
2743 const double gigaByteSize
= multiplier
* megaByteSize
;
2744 const double teraByteSize
= multiplier
* gigaByteSize
;
2746 const double bytesize
= bs
.ToDouble();
2749 if ( bytesize
< kiloByteSize
)
2750 result
.Printf("%s B", bs
.ToString());
2751 else if ( bytesize
< megaByteSize
)
2752 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2753 else if (bytesize
< gigaByteSize
)
2754 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2755 else if (bytesize
< teraByteSize
)
2756 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2758 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2763 wxULongLong
wxFileName::GetSize() const
2765 return GetSize(GetFullPath());
2768 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2770 wxSizeConvention conv
) const
2772 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2775 #endif // wxUSE_LONGLONG
2777 // ----------------------------------------------------------------------------
2778 // Mac-specific functions
2779 // ----------------------------------------------------------------------------
2781 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2786 class MacDefaultExtensionRecord
2789 MacDefaultExtensionRecord()
2795 // default copy ctor, assignment operator and dtor are ok
2797 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2801 m_creator
= creator
;
2809 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2811 bool gMacDefaultExtensionsInited
= false;
2813 #include "wx/arrimpl.cpp"
2815 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2817 MacDefaultExtensionArray gMacDefaultExtensions
;
2819 // load the default extensions
2820 const MacDefaultExtensionRecord gDefaults
[] =
2822 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2823 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2824 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2827 void MacEnsureDefaultExtensionsLoaded()
2829 if ( !gMacDefaultExtensionsInited
)
2831 // we could load the pc exchange prefs here too
2832 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2834 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2836 gMacDefaultExtensionsInited
= true;
2840 } // anonymous namespace
2842 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2845 FSCatalogInfo catInfo
;
2848 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2850 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2852 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2853 finfo
->fileType
= type
;
2854 finfo
->fileCreator
= creator
;
2855 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2862 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2865 FSCatalogInfo catInfo
;
2868 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2870 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2872 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2873 *type
= finfo
->fileType
;
2874 *creator
= finfo
->fileCreator
;
2881 bool wxFileName::MacSetDefaultTypeAndCreator()
2883 wxUint32 type
, creator
;
2884 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2887 return MacSetTypeAndCreator( type
, creator
) ;
2892 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2894 MacEnsureDefaultExtensionsLoaded() ;
2895 wxString extl
= ext
.Lower() ;
2896 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2898 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2900 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2901 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2908 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2910 MacEnsureDefaultExtensionsLoaded();
2911 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2912 gMacDefaultExtensions
.Add( rec
);
2915 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON