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
159 // ----------------------------------------------------------------------------
161 // ----------------------------------------------------------------------------
163 // small helper class which opens and closes the file - we use it just to get
164 // a file handle for the given file name to pass it to some Win32 API function
165 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
176 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
178 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
179 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
180 // be changed when we open it because this class is used for setting
181 // access time (see #10567)
182 m_hFile
= ::CreateFile
184 filename
.t_str(), // name
185 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
186 : FILE_WRITE_ATTRIBUTES
,
187 FILE_SHARE_READ
| // sharing mode
188 FILE_SHARE_WRITE
, // (allow everything)
189 NULL
, // no secutity attr
190 OPEN_EXISTING
, // creation disposition
192 NULL
// no template file
195 if ( m_hFile
== INVALID_HANDLE_VALUE
)
197 if ( mode
== ReadAttr
)
199 wxLogSysError(_("Failed to open '%s' for reading"),
204 wxLogSysError(_("Failed to open '%s' for writing"),
212 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
214 if ( !::CloseHandle(m_hFile
) )
216 wxLogSysError(_("Failed to close file handle"));
221 // return true only if the file could be opened successfully
222 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
225 operator HANDLE() const { return m_hFile
; }
233 // ----------------------------------------------------------------------------
235 // ----------------------------------------------------------------------------
237 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
239 // convert between wxDateTime and FILETIME which is a 64-bit value representing
240 // the number of 100-nanosecond intervals since January 1, 1601.
242 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
244 FILETIME ftcopy
= ft
;
246 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
248 wxLogLastError(wxT("FileTimeToLocalFileTime"));
252 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
254 wxLogLastError(wxT("FileTimeToSystemTime"));
257 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
258 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
261 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
264 st
.wDay
= dt
.GetDay();
265 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
266 st
.wYear
= (WORD
)dt
.GetYear();
267 st
.wHour
= dt
.GetHour();
268 st
.wMinute
= dt
.GetMinute();
269 st
.wSecond
= dt
.GetSecond();
270 st
.wMilliseconds
= dt
.GetMillisecond();
273 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
275 wxLogLastError(wxT("SystemTimeToFileTime"));
278 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
280 wxLogLastError(wxT("LocalFileTimeToFileTime"));
284 #endif // wxUSE_DATETIME && __WIN32__
286 // return a string with the volume par
287 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
291 if ( !volume
.empty() )
293 format
= wxFileName::GetFormat(format
);
295 // Special Windows UNC paths hack, part 2: undo what we did in
296 // SplitPath() and make an UNC path if we have a drive which is not a
297 // single letter (hopefully the network shares can't be one letter only
298 // although I didn't find any authoritative docs on this)
299 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
301 // We also have to check for Windows unique volume names here and
302 // return it with '\\?\' prepended to it
303 if ( wxFileName::IsMSWUniqueVolumeNamePath("\\\\?\\" + volume
+ "\\",
306 path
<< "\\\\?\\" << volume
;
310 // it must be a UNC path
311 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
314 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
316 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
324 // return true if the character is a DOS path separator i.e. either a slash or
326 inline bool IsDOSPathSep(wxUniChar ch
)
328 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
331 // return true if the format used is the DOS/Windows one and the string looks
333 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
335 return format
== wxPATH_DOS
&&
336 path
.length() >= 4 && // "\\a" can't be a UNC path
337 IsDOSPathSep(path
[0u]) &&
338 IsDOSPathSep(path
[1u]) &&
339 !IsDOSPathSep(path
[2u]);
342 // ----------------------------------------------------------------------------
344 // ----------------------------------------------------------------------------
346 // length of \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ string
347 static const size_t wxMSWUniqueVolumePrefixLength
= 49;
349 } // anonymous namespace
351 // ============================================================================
353 // ============================================================================
355 // ----------------------------------------------------------------------------
356 // wxFileName construction
357 // ----------------------------------------------------------------------------
359 void wxFileName::Assign( const wxFileName
&filepath
)
361 m_volume
= filepath
.GetVolume();
362 m_dirs
= filepath
.GetDirs();
363 m_name
= filepath
.GetName();
364 m_ext
= filepath
.GetExt();
365 m_relative
= filepath
.m_relative
;
366 m_hasExt
= filepath
.m_hasExt
;
369 void wxFileName::Assign(const wxString
& volume
,
370 const wxString
& path
,
371 const wxString
& name
,
376 // we should ignore paths which look like UNC shares because we already
377 // have the volume here and the UNC notation (\\server\path) is only valid
378 // for paths which don't start with a volume, so prevent SetPath() from
379 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
381 // note also that this is a rather ugly way to do what we want (passing
382 // some kind of flag telling to ignore UNC paths to SetPath() would be
383 // better) but this is the safest thing to do to avoid breaking backwards
384 // compatibility in 2.8
385 if ( IsUNCPath(path
, format
) )
387 // remove one of the 2 leading backslashes to ensure that it's not
388 // recognized as an UNC path by SetPath()
389 wxString
pathNonUNC(path
, 1, wxString::npos
);
390 SetPath(pathNonUNC
, format
);
392 else // no UNC complications
394 SetPath(path
, format
);
404 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
408 if ( pathOrig
.empty() )
416 format
= GetFormat( format
);
418 // 0) deal with possible volume part first
421 SplitVolume(pathOrig
, &volume
, &path
, format
);
422 if ( !volume
.empty() )
429 // 1) Determine if the path is relative or absolute.
433 // we had only the volume
437 wxChar leadingChar
= path
[0u];
442 m_relative
= leadingChar
== wxT(':');
444 // We then remove a leading ":". The reason is in our
445 // storage form for relative paths:
446 // ":dir:file.txt" actually means "./dir/file.txt" in
447 // DOS notation and should get stored as
448 // (relative) (dir) (file.txt)
449 // "::dir:file.txt" actually means "../dir/file.txt"
450 // stored as (relative) (..) (dir) (file.txt)
451 // This is important only for the Mac as an empty dir
452 // actually means <UP>, whereas under DOS, double
453 // slashes can be ignored: "\\\\" is the same as "\\".
459 // TODO: what is the relative path format here?
464 wxFAIL_MSG( wxT("Unknown path format") );
465 // !! Fall through !!
468 m_relative
= leadingChar
!= wxT('/');
472 m_relative
= !IsPathSeparator(leadingChar
, format
);
477 // 2) Break up the path into its members. If the original path
478 // was just "/" or "\\", m_dirs will be empty. We know from
479 // the m_relative field, if this means "nothing" or "root dir".
481 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
483 while ( tn
.HasMoreTokens() )
485 wxString token
= tn
.GetNextToken();
487 // Remove empty token under DOS and Unix, interpret them
491 if (format
== wxPATH_MAC
)
492 m_dirs
.Add( wxT("..") );
502 void wxFileName::Assign(const wxString
& fullpath
,
505 wxString volume
, path
, name
, ext
;
507 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
509 Assign(volume
, path
, name
, ext
, hasExt
, format
);
512 void wxFileName::Assign(const wxString
& fullpathOrig
,
513 const wxString
& fullname
,
516 // always recognize fullpath as directory, even if it doesn't end with a
518 wxString fullpath
= fullpathOrig
;
519 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
521 fullpath
+= GetPathSeparator(format
);
524 wxString volume
, path
, name
, ext
;
527 // do some consistency checks: the name should be really just the filename
528 // and the path should be really just a path
529 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
531 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
533 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
534 wxT("the file name shouldn't contain the path") );
536 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
539 // This test makes no sense on an OpenVMS system.
540 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
541 wxT("the path shouldn't contain file name nor extension") );
543 Assign(volume
, path
, name
, ext
, hasExt
, format
);
546 void wxFileName::Assign(const wxString
& pathOrig
,
547 const wxString
& name
,
553 SplitVolume(pathOrig
, &volume
, &path
, format
);
555 Assign(volume
, path
, name
, ext
, format
);
558 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
560 Assign(dir
, wxEmptyString
, format
);
563 void wxFileName::Clear()
569 m_ext
= wxEmptyString
;
571 // we don't have any absolute path for now
579 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
581 return wxFileName(file
, format
);
585 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
588 fn
.AssignDir(dir
, format
);
592 // ----------------------------------------------------------------------------
594 // ----------------------------------------------------------------------------
596 bool wxFileName::FileExists() const
598 return wxFileName::FileExists( GetFullPath() );
602 bool wxFileName::FileExists( const wxString
&filePath
)
604 #if defined(__WXPALMOS__)
606 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
607 // we must use GetFileAttributes() instead of the ANSI C functions because
608 // it can cope with network (UNC) paths unlike them
609 DWORD ret
= ::GetFileAttributes(filePath
.t_str());
611 return (ret
!= INVALID_FILE_ATTRIBUTES
) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
614 #define S_ISREG(mode) ((mode) & S_IFREG)
618 return (wxStat( filePath
, &st
) == 0 && S_ISREG(st
.st_mode
))
620 || (errno
== EACCES
) // if access is denied something with that name
621 // exists and is opened in exclusive mode.
624 #endif // __WIN32__/!__WIN32__
627 bool wxFileName::DirExists() const
629 return wxFileName::DirExists( GetPath() );
633 bool wxFileName::DirExists( const wxString
&dirPath
)
635 wxString
strPath(dirPath
);
637 #if defined(__WINDOWS__) || defined(__OS2__)
638 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
639 // so remove all trailing backslashes from the path - but don't do this for
640 // the paths "d:\" (which are different from "d:"), for just "\" or for
641 // windows unique volume names ("\\?\Volume{GUID}\")
642 while ( wxEndsWithPathSeparator(strPath
) )
644 size_t len
= strPath
.length();
645 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) ||
646 (len
== wxMSWUniqueVolumePrefixLength
&&
647 wxFileName::IsMSWUniqueVolumeNamePath(strPath
)))
652 strPath
.Truncate(len
- 1);
654 #endif // __WINDOWS__
657 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
658 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
662 #if defined(__WXPALMOS__)
664 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
665 // stat() can't cope with network paths
666 DWORD ret
= ::GetFileAttributes(strPath
.t_str());
668 return (ret
!= INVALID_FILE_ATTRIBUTES
) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
669 #elif defined(__OS2__)
670 FILESTATUS3 Info
= {{0}};
671 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
672 (void*) &Info
, sizeof(FILESTATUS3
));
674 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
675 (rc
== ERROR_SHARING_VIOLATION
);
676 // If we got a sharing violation, there must be something with this name.
680 #ifndef __VISAGECPP__
681 return wxStat(strPath
, &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
683 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
684 return wxStat(strPath
, &st
) == 0 && (st
.st_mode
== S_IFDIR
);
687 #endif // __WIN32__/!__WIN32__
690 // ----------------------------------------------------------------------------
691 // CWD and HOME stuff
692 // ----------------------------------------------------------------------------
694 void wxFileName::AssignCwd(const wxString
& volume
)
696 AssignDir(wxFileName::GetCwd(volume
));
700 wxString
wxFileName::GetCwd(const wxString
& volume
)
702 // if we have the volume, we must get the current directory on this drive
703 // and to do this we have to chdir to this volume - at least under Windows,
704 // I don't know how to get the current drive on another volume elsewhere
707 if ( !volume
.empty() )
710 SetCwd(volume
+ GetVolumeSeparator());
713 wxString cwd
= ::wxGetCwd();
715 if ( !volume
.empty() )
723 bool wxFileName::SetCwd() const
725 return wxFileName::SetCwd( GetPath() );
728 bool wxFileName::SetCwd( const wxString
&cwd
)
730 return ::wxSetWorkingDirectory( cwd
);
733 void wxFileName::AssignHomeDir()
735 AssignDir(wxFileName::GetHomeDir());
738 wxString
wxFileName::GetHomeDir()
740 return ::wxGetHomeDir();
744 // ----------------------------------------------------------------------------
745 // CreateTempFileName
746 // ----------------------------------------------------------------------------
748 #if wxUSE_FILE || wxUSE_FFILE
751 #if !defined wx_fdopen && defined HAVE_FDOPEN
752 #define wx_fdopen fdopen
755 // NB: GetTempFileName() under Windows creates the file, so using
756 // O_EXCL there would fail
758 #define wxOPEN_EXCL 0
760 #define wxOPEN_EXCL O_EXCL
764 #ifdef wxOpenOSFHandle
765 #define WX_HAVE_DELETE_ON_CLOSE
766 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
768 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
770 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
772 DWORD disposition
= OPEN_ALWAYS
;
774 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
775 FILE_FLAG_DELETE_ON_CLOSE
;
777 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
778 disposition
, attributes
, NULL
);
780 return wxOpenOSFHandle(h
, wxO_BINARY
);
782 #endif // wxOpenOSFHandle
785 // Helper to open the file
787 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
789 #ifdef WX_HAVE_DELETE_ON_CLOSE
791 return wxOpenWithDeleteOnClose(path
);
794 *deleteOnClose
= false;
796 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
801 // Helper to open the file and attach it to the wxFFile
803 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
806 *deleteOnClose
= false;
807 return file
->Open(path
, wxT("w+b"));
809 int fd
= wxTempOpen(path
, deleteOnClose
);
812 file
->Attach(wx_fdopen(fd
, "w+b"));
813 return file
->IsOpened();
816 #endif // wxUSE_FFILE
820 #define WXFILEARGS(x, y) y
822 #define WXFILEARGS(x, y) x
824 #define WXFILEARGS(x, y) x, y
828 // Implementation of wxFileName::CreateTempFileName().
830 static wxString
wxCreateTempImpl(
831 const wxString
& prefix
,
832 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
833 bool *deleteOnClose
= NULL
)
835 #if wxUSE_FILE && wxUSE_FFILE
836 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
838 wxString path
, dir
, name
;
839 bool wantDeleteOnClose
= false;
843 // set the result to false initially
844 wantDeleteOnClose
= *deleteOnClose
;
845 *deleteOnClose
= false;
849 // easier if it alwasys points to something
850 deleteOnClose
= &wantDeleteOnClose
;
853 // use the directory specified by the prefix
854 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
858 dir
= wxFileName::GetTempDir();
861 #if defined(__WXWINCE__)
862 path
= dir
+ wxT("\\") + name
;
864 while (wxFileName::FileExists(path
))
866 path
= dir
+ wxT("\\") + name
;
871 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
872 if (!::GetTempFileName(dir
.t_str(), name
.t_str(), 0,
873 wxStringBuffer(path
, MAX_PATH
+ 1)))
875 wxLogLastError(wxT("GetTempFileName"));
883 if ( !wxEndsWithPathSeparator(dir
) &&
884 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
886 path
+= wxFILE_SEP_PATH
;
891 #if defined(HAVE_MKSTEMP)
892 // scratch space for mkstemp()
893 path
+= wxT("XXXXXX");
895 // we need to copy the path to the buffer in which mkstemp() can modify it
896 wxCharBuffer
buf(path
.fn_str());
898 // cast is safe because the string length doesn't change
899 int fdTemp
= mkstemp( (char*)(const char*) buf
);
902 // this might be not necessary as mkstemp() on most systems should have
903 // already done it but it doesn't hurt neither...
906 else // mkstemp() succeeded
908 path
= wxConvFile
.cMB2WX( (const char*) buf
);
911 // avoid leaking the fd
914 fileTemp
->Attach(fdTemp
);
923 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
925 ffileTemp
->Open(path
, wxT("r+b"));
936 #else // !HAVE_MKSTEMP
940 path
+= wxT("XXXXXX");
942 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
943 if ( !mktemp( (char*)(const char*) buf
) )
949 path
= wxConvFile
.cMB2WX( (const char*) buf
);
951 #else // !HAVE_MKTEMP (includes __DOS__)
952 // generate the unique file name ourselves
953 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
954 path
<< (unsigned int)getpid();
959 static const size_t numTries
= 1000;
960 for ( size_t n
= 0; n
< numTries
; n
++ )
962 // 3 hex digits is enough for numTries == 1000 < 4096
963 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
964 if ( !wxFileName::FileExists(pathTry
) )
973 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
975 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
977 #endif // Windows/!Windows
981 wxLogSysError(_("Failed to create a temporary file name"));
987 // open the file - of course, there is a race condition here, this is
988 // why we always prefer using mkstemp()...
990 if ( fileTemp
&& !fileTemp
->IsOpened() )
992 *deleteOnClose
= wantDeleteOnClose
;
993 int fd
= wxTempOpen(path
, deleteOnClose
);
995 fileTemp
->Attach(fd
);
1002 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
1004 *deleteOnClose
= wantDeleteOnClose
;
1005 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
1011 // FIXME: If !ok here should we loop and try again with another
1012 // file name? That is the standard recourse if open(O_EXCL)
1013 // fails, though of course it should be protected against
1014 // possible infinite looping too.
1016 wxLogError(_("Failed to open temporary file."));
1026 static bool wxCreateTempImpl(
1027 const wxString
& prefix
,
1028 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1031 bool deleteOnClose
= true;
1033 *name
= wxCreateTempImpl(prefix
,
1034 WXFILEARGS(fileTemp
, ffileTemp
),
1037 bool ok
= !name
->empty();
1042 else if (ok
&& wxRemoveFile(*name
))
1050 static void wxAssignTempImpl(
1052 const wxString
& prefix
,
1053 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1056 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1058 if ( tempname
.empty() )
1060 // error, failed to get temp file name
1065 fn
->Assign(tempname
);
1070 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1072 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1076 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1078 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1081 #endif // wxUSE_FILE || wxUSE_FFILE
1086 wxString
wxCreateTempFileName(const wxString
& prefix
,
1088 bool *deleteOnClose
)
1090 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1093 bool wxCreateTempFile(const wxString
& prefix
,
1097 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1100 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1102 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1107 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1109 return wxCreateTempFileName(prefix
, fileTemp
);
1112 #endif // wxUSE_FILE
1117 wxString
wxCreateTempFileName(const wxString
& prefix
,
1119 bool *deleteOnClose
)
1121 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1124 bool wxCreateTempFile(const wxString
& prefix
,
1128 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1132 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1134 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1139 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1141 return wxCreateTempFileName(prefix
, fileTemp
);
1144 #endif // wxUSE_FFILE
1147 // ----------------------------------------------------------------------------
1148 // directory operations
1149 // ----------------------------------------------------------------------------
1151 // helper of GetTempDir(): check if the given directory exists and return it if
1152 // it does or an empty string otherwise
1156 wxString
CheckIfDirExists(const wxString
& dir
)
1158 return wxFileName::DirExists(dir
) ? dir
: wxString();
1161 } // anonymous namespace
1163 wxString
wxFileName::GetTempDir()
1165 // first try getting it from environment: this allows overriding the values
1166 // used by default if the user wants to create temporary files in another
1168 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1171 dir
= CheckIfDirExists(wxGetenv("TMP"));
1173 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1176 // if no environment variables are set, use the system default
1179 #if defined(__WXWINCE__)
1180 dir
= CheckIfDirExists(wxT("\\temp"));
1181 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1182 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1184 wxLogLastError(wxT("GetTempPath"));
1186 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1187 dir
= wxMacFindFolderNoSeparator(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1188 #endif // systems with native way
1190 else // we got directory from an environment variable
1192 // remove any trailing path separators, we don't want to ever return
1193 // them from this function for consistency
1194 const size_t lastNonSep
= dir
.find_last_not_of(GetPathSeparators());
1195 if ( lastNonSep
== wxString::npos
)
1197 // the string consists entirely of separators, leave only one
1198 dir
= GetPathSeparator();
1202 dir
.erase(lastNonSep
+ 1);
1206 // fall back to hard coded value
1209 #ifdef __UNIX_LIKE__
1210 dir
= CheckIfDirExists("/tmp");
1212 #endif // __UNIX_LIKE__
1219 bool wxFileName::Mkdir( int perm
, int flags
) const
1221 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1224 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1226 if ( flags
& wxPATH_MKDIR_FULL
)
1228 // split the path in components
1229 wxFileName filename
;
1230 filename
.AssignDir(dir
);
1233 if ( filename
.HasVolume())
1235 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1238 wxArrayString dirs
= filename
.GetDirs();
1239 size_t count
= dirs
.GetCount();
1240 for ( size_t i
= 0; i
< count
; i
++ )
1242 if ( i
> 0 || filename
.IsAbsolute() )
1243 currPath
+= wxFILE_SEP_PATH
;
1244 currPath
+= dirs
[i
];
1246 if (!DirExists(currPath
))
1248 if (!wxMkdir(currPath
, perm
))
1250 // no need to try creating further directories
1260 return ::wxMkdir( dir
, perm
);
1263 bool wxFileName::Rmdir(int flags
) const
1265 return wxFileName::Rmdir( GetPath(), flags
);
1268 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1271 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1273 // SHFileOperation needs double null termination string
1274 // but without separator at the end of the path
1276 if ( path
.Last() == wxFILE_SEP_PATH
)
1280 SHFILEOPSTRUCT fileop
;
1281 wxZeroMemory(fileop
);
1282 fileop
.wFunc
= FO_DELETE
;
1283 #if defined(__CYGWIN__) && defined(wxUSE_UNICODE)
1284 fileop
.pFrom
= path
.wc_str();
1286 fileop
.pFrom
= path
.fn_str();
1288 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1290 // FOF_NOERRORUI is not defined in WinCE
1291 fileop
.fFlags
|= FOF_NOERRORUI
;
1294 int ret
= SHFileOperation(&fileop
);
1297 // SHFileOperation may return non-Win32 error codes, so the error
1298 // message can be incorrect
1299 wxLogApiError(wxT("SHFileOperation"), ret
);
1305 else if ( flags
& wxPATH_RMDIR_FULL
)
1307 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1308 #endif // !__WXMSW__
1311 if ( path
.Last() != wxFILE_SEP_PATH
)
1312 path
+= wxFILE_SEP_PATH
;
1316 if ( !d
.IsOpened() )
1321 // first delete all subdirectories
1322 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1325 wxFileName::Rmdir(path
+ filename
, flags
);
1326 cont
= d
.GetNext(&filename
);
1330 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1332 // delete all files too
1333 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1336 ::wxRemoveFile(path
+ filename
);
1337 cont
= d
.GetNext(&filename
);
1340 #endif // !__WXMSW__
1343 return ::wxRmdir(dir
);
1346 // ----------------------------------------------------------------------------
1347 // path normalization
1348 // ----------------------------------------------------------------------------
1350 bool wxFileName::Normalize(int flags
,
1351 const wxString
& cwd
,
1352 wxPathFormat format
)
1354 // deal with env vars renaming first as this may seriously change the path
1355 if ( flags
& wxPATH_NORM_ENV_VARS
)
1357 wxString pathOrig
= GetFullPath(format
);
1358 wxString path
= wxExpandEnvVars(pathOrig
);
1359 if ( path
!= pathOrig
)
1365 // the existing path components
1366 wxArrayString dirs
= GetDirs();
1368 // the path to prepend in front to make the path absolute
1371 format
= GetFormat(format
);
1373 // set up the directory to use for making the path absolute later
1374 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1378 curDir
.AssignCwd(GetVolume());
1380 else // cwd provided
1382 curDir
.AssignDir(cwd
);
1386 // handle ~ stuff under Unix only
1387 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1389 if ( !dirs
.IsEmpty() )
1391 wxString dir
= dirs
[0u];
1392 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1394 // to make the path absolute use the home directory
1395 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1401 // transform relative path into abs one
1402 if ( curDir
.IsOk() )
1404 // this path may be relative because it doesn't have the volume name
1405 // and still have m_relative=true; in this case we shouldn't modify
1406 // our directory components but just set the current volume
1407 if ( !HasVolume() && curDir
.HasVolume() )
1409 SetVolume(curDir
.GetVolume());
1413 // yes, it was the case - we don't need curDir then
1418 // finally, prepend curDir to the dirs array
1419 wxArrayString dirsNew
= curDir
.GetDirs();
1420 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1422 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1423 // return for some reason an absolute path, then curDir maybe not be absolute!
1424 if ( !curDir
.m_relative
)
1426 // we have prepended an absolute path and thus we are now an absolute
1430 // else if (flags & wxPATH_NORM_ABSOLUTE):
1431 // should we warn the user that we didn't manage to make the path absolute?
1434 // now deal with ".", ".." and the rest
1436 size_t count
= dirs
.GetCount();
1437 for ( size_t n
= 0; n
< count
; n
++ )
1439 wxString dir
= dirs
[n
];
1441 if ( flags
& wxPATH_NORM_DOTS
)
1443 if ( dir
== wxT(".") )
1449 if ( dir
== wxT("..") )
1451 if ( m_dirs
.empty() )
1453 // We have more ".." than directory components so far.
1454 // Don't treat this as an error as the path could have been
1455 // entered by user so try to handle it reasonably: if the
1456 // path is absolute, just ignore the extra ".." because
1457 // "/.." is the same as "/". Otherwise, i.e. for relative
1458 // paths, keep ".." unchanged because removing it would
1459 // modify the file a relative path refers to.
1464 else // Normal case, go one step up.
1475 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1476 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1479 if (GetShortcutTarget(GetFullPath(format
), filename
))
1487 #if defined(__WIN32__)
1488 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1490 Assign(GetLongPath());
1494 // Change case (this should be kept at the end of the function, to ensure
1495 // that the path doesn't change any more after we normalize its case)
1496 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1498 m_volume
.MakeLower();
1502 // directory entries must be made lower case as well
1503 count
= m_dirs
.GetCount();
1504 for ( size_t i
= 0; i
< count
; i
++ )
1506 m_dirs
[i
].MakeLower();
1514 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1515 const wxString
& replacementFmtString
,
1516 wxPathFormat format
)
1518 // look into stringForm for the contents of the given environment variable
1520 if (envname
.empty() ||
1521 !wxGetEnv(envname
, &val
))
1526 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1527 // do not touch the file name and the extension
1529 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1530 stringForm
.Replace(val
, replacement
);
1532 // Now assign ourselves the modified path:
1533 Assign(stringForm
, GetFullName(), format
);
1539 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1541 wxString homedir
= wxGetHomeDir();
1542 if (homedir
.empty())
1545 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1546 // do not touch the file name and the extension
1548 stringForm
.Replace(homedir
, "~");
1550 // Now assign ourselves the modified path:
1551 Assign(stringForm
, GetFullName(), format
);
1556 // ----------------------------------------------------------------------------
1557 // get the shortcut target
1558 // ----------------------------------------------------------------------------
1560 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1561 // The .lnk file is a plain text file so it should be easy to
1562 // make it work. Hint from Google Groups:
1563 // "If you open up a lnk file, you'll see a
1564 // number, followed by a pound sign (#), followed by more text. The
1565 // number is the number of characters that follows the pound sign. The
1566 // characters after the pound sign are the command line (which _can_
1567 // include arguments) to be executed. Any path (e.g. \windows\program
1568 // files\myapp.exe) that includes spaces needs to be enclosed in
1569 // quotation marks."
1571 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1572 // The following lines are necessary under WinCE
1573 // #include "wx/msw/private.h"
1574 // #include <ole2.h>
1576 #if defined(__WXWINCE__)
1577 #include <shlguid.h>
1580 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1581 wxString
& targetFilename
,
1582 wxString
* arguments
) const
1584 wxString path
, file
, ext
;
1585 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1589 bool success
= false;
1591 // Assume it's not a shortcut if it doesn't end with lnk
1592 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1595 // create a ShellLink object
1596 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1597 IID_IShellLink
, (LPVOID
*) &psl
);
1599 if (SUCCEEDED(hres
))
1602 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1603 if (SUCCEEDED(hres
))
1605 WCHAR wsz
[MAX_PATH
];
1607 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1610 hres
= ppf
->Load(wsz
, 0);
1613 if (SUCCEEDED(hres
))
1616 // Wrong prototype in early versions
1617 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1618 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1620 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1622 targetFilename
= wxString(buf
);
1623 success
= (shortcutPath
!= targetFilename
);
1625 psl
->GetArguments(buf
, 2048);
1627 if (!args
.empty() && arguments
)
1639 #endif // __WIN32__ && !__WXWINCE__
1642 // ----------------------------------------------------------------------------
1643 // absolute/relative paths
1644 // ----------------------------------------------------------------------------
1646 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1648 // unix paths beginning with ~ are reported as being absolute
1649 if ( format
== wxPATH_UNIX
)
1651 if ( !m_dirs
.IsEmpty() )
1653 wxString dir
= m_dirs
[0u];
1655 if (!dir
.empty() && dir
[0u] == wxT('~'))
1660 // if our path doesn't start with a path separator, it's not an absolute
1665 if ( !GetVolumeSeparator(format
).empty() )
1667 // this format has volumes and an absolute path must have one, it's not
1668 // enough to have the full path to be an absolute file under Windows
1669 if ( GetVolume().empty() )
1676 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1678 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1680 // get cwd only once - small time saving
1681 wxString cwd
= wxGetCwd();
1682 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1683 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1685 bool withCase
= IsCaseSensitive(format
);
1687 // we can't do anything if the files live on different volumes
1688 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1694 // same drive, so we don't need our volume
1697 // remove common directories starting at the top
1698 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1699 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1702 fnBase
.m_dirs
.RemoveAt(0);
1705 // add as many ".." as needed
1706 size_t count
= fnBase
.m_dirs
.GetCount();
1707 for ( size_t i
= 0; i
< count
; i
++ )
1709 m_dirs
.Insert(wxT(".."), 0u);
1712 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1714 // a directory made relative with respect to itself is '.' under Unix
1715 // and DOS, by definition (but we don't have to insert "./" for the
1717 if ( m_dirs
.IsEmpty() && IsDir() )
1719 m_dirs
.Add(wxT('.'));
1729 // ----------------------------------------------------------------------------
1730 // filename kind tests
1731 // ----------------------------------------------------------------------------
1733 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1735 wxFileName fn1
= *this,
1738 // get cwd only once - small time saving
1739 wxString cwd
= wxGetCwd();
1740 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1741 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1743 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1746 // TODO: compare inodes for Unix, this works even when filenames are
1747 // different but files are the same (symlinks) (VZ)
1753 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1755 // only Unix filenames are truely case-sensitive
1756 return GetFormat(format
) == wxPATH_UNIX
;
1760 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1762 // Inits to forbidden characters that are common to (almost) all platforms.
1763 wxString strForbiddenChars
= wxT("*?");
1765 // If asserts, wxPathFormat has been changed. In case of a new path format
1766 // addition, the following code might have to be updated.
1767 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1768 switch ( GetFormat(format
) )
1771 wxFAIL_MSG( wxT("Unknown path format") );
1772 // !! Fall through !!
1778 // On a Mac even names with * and ? are allowed (Tested with OS
1779 // 9.2.1 and OS X 10.2.5)
1780 strForbiddenChars
= wxEmptyString
;
1784 strForbiddenChars
+= wxT("\\/:\"<>|");
1791 return strForbiddenChars
;
1795 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1798 return wxEmptyString
;
1802 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1803 (GetFormat(format
) == wxPATH_VMS
) )
1805 sepVol
= wxFILE_SEP_DSK
;
1814 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1817 switch ( GetFormat(format
) )
1820 // accept both as native APIs do but put the native one first as
1821 // this is the one we use in GetFullPath()
1822 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1826 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1830 seps
= wxFILE_SEP_PATH_UNIX
;
1834 seps
= wxFILE_SEP_PATH_MAC
;
1838 seps
= wxFILE_SEP_PATH_VMS
;
1846 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1848 format
= GetFormat(format
);
1850 // under VMS the end of the path is ']', not the path separator used to
1851 // separate the components
1852 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1856 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1858 // wxString::Find() doesn't work as expected with NUL - it will always find
1859 // it, so test for it separately
1860 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1865 wxFileName::IsMSWUniqueVolumeNamePath(const wxString
& path
, wxPathFormat format
)
1867 // return true if the format used is the DOS/Windows one and the string begins
1868 // with a Windows unique volume name ("\\?\Volume{guid}\")
1869 return format
== wxPATH_DOS
&&
1870 path
.length() >= wxMSWUniqueVolumePrefixLength
&&
1871 path
.StartsWith(wxS("\\\\?\\Volume{")) &&
1872 path
[wxMSWUniqueVolumePrefixLength
- 1] == wxFILE_SEP_PATH_DOS
;
1875 // ----------------------------------------------------------------------------
1876 // path components manipulation
1877 // ----------------------------------------------------------------------------
1879 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1883 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1888 const size_t len
= dir
.length();
1889 for ( size_t n
= 0; n
< len
; n
++ )
1891 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1893 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1902 void wxFileName::AppendDir( const wxString
& dir
)
1904 if ( IsValidDirComponent(dir
) )
1908 void wxFileName::PrependDir( const wxString
& dir
)
1913 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1915 if ( IsValidDirComponent(dir
) )
1916 m_dirs
.Insert(dir
, before
);
1919 void wxFileName::RemoveDir(size_t pos
)
1921 m_dirs
.RemoveAt(pos
);
1924 // ----------------------------------------------------------------------------
1926 // ----------------------------------------------------------------------------
1928 void wxFileName::SetFullName(const wxString
& fullname
)
1930 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1931 &m_name
, &m_ext
, &m_hasExt
);
1934 wxString
wxFileName::GetFullName() const
1936 wxString fullname
= m_name
;
1939 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1945 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1947 format
= GetFormat( format
);
1951 // return the volume with the path as well if requested
1952 if ( flags
& wxPATH_GET_VOLUME
)
1954 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1957 // the leading character
1962 fullpath
+= wxFILE_SEP_PATH_MAC
;
1967 fullpath
+= wxFILE_SEP_PATH_DOS
;
1971 wxFAIL_MSG( wxT("Unknown path format") );
1977 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1982 // no leading character here but use this place to unset
1983 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1984 // as, if I understand correctly, there should never be a dot
1985 // before the closing bracket
1986 flags
&= ~wxPATH_GET_SEPARATOR
;
1989 if ( m_dirs
.empty() )
1991 // there is nothing more
1995 // then concatenate all the path components using the path separator
1996 if ( format
== wxPATH_VMS
)
1998 fullpath
+= wxT('[');
2001 const size_t dirCount
= m_dirs
.GetCount();
2002 for ( size_t i
= 0; i
< dirCount
; i
++ )
2007 if ( m_dirs
[i
] == wxT(".") )
2009 // skip appending ':', this shouldn't be done in this
2010 // case as "::" is interpreted as ".." under Unix
2014 // convert back from ".." to nothing
2015 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2016 fullpath
+= m_dirs
[i
];
2020 wxFAIL_MSG( wxT("Unexpected path format") );
2021 // still fall through
2025 fullpath
+= m_dirs
[i
];
2029 // TODO: What to do with ".." under VMS
2031 // convert back from ".." to nothing
2032 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
2033 fullpath
+= m_dirs
[i
];
2037 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
2038 fullpath
+= GetPathSeparator(format
);
2041 if ( format
== wxPATH_VMS
)
2043 fullpath
+= wxT(']');
2049 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
2051 // we already have a function to get the path
2052 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
2055 // now just add the file name and extension to it
2056 fullpath
+= GetFullName();
2061 // Return the short form of the path (returns identity on non-Windows platforms)
2062 wxString
wxFileName::GetShortPath() const
2064 wxString
path(GetFullPath());
2066 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2067 DWORD sz
= ::GetShortPathName(path
.t_str(), NULL
, 0);
2071 if ( ::GetShortPathName
2074 wxStringBuffer(pathOut
, sz
),
2086 // Return the long form of the path (returns identity on non-Windows platforms)
2087 wxString
wxFileName::GetLongPath() const
2090 path
= GetFullPath();
2092 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2094 #if wxUSE_DYNLIB_CLASS
2095 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2097 // this is MT-safe as in the worst case we're going to resolve the function
2098 // twice -- but as the result is the same in both threads, it's ok
2099 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2100 if ( !s_pfnGetLongPathName
)
2102 static bool s_triedToLoad
= false;
2104 if ( !s_triedToLoad
)
2106 s_triedToLoad
= true;
2108 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2110 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2115 #endif // Unicode/ANSI
2117 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2119 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2120 dllKernel
.GetSymbol(GetLongPathName
);
2123 // note that kernel32.dll can be unloaded, it stays in memory
2124 // anyhow as all Win32 programs link to it and so it's safe to call
2125 // GetLongPathName() even after unloading it
2129 if ( s_pfnGetLongPathName
)
2131 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.t_str(), NULL
, 0);
2134 if ( (*s_pfnGetLongPathName
)
2137 wxStringBuffer(pathOut
, dwSize
),
2145 #endif // wxUSE_DYNLIB_CLASS
2147 // The OS didn't support GetLongPathName, or some other error.
2148 // We need to call FindFirstFile on each component in turn.
2150 WIN32_FIND_DATA findFileData
;
2154 pathOut
= GetVolume() +
2155 GetVolumeSeparator(wxPATH_DOS
) +
2156 GetPathSeparator(wxPATH_DOS
);
2158 pathOut
= wxEmptyString
;
2160 wxArrayString dirs
= GetDirs();
2161 dirs
.Add(GetFullName());
2165 size_t count
= dirs
.GetCount();
2166 for ( size_t i
= 0; i
< count
; i
++ )
2168 const wxString
& dir
= dirs
[i
];
2170 // We're using pathOut to collect the long-name path, but using a
2171 // temporary for appending the last path component which may be
2173 tmpPath
= pathOut
+ dir
;
2175 // We must not process "." or ".." here as they would be (unexpectedly)
2176 // replaced by the corresponding directory names so just leave them
2179 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2180 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2181 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2183 tmpPath
+= wxFILE_SEP_PATH
;
2188 hFind
= ::FindFirstFile(tmpPath
.t_str(), &findFileData
);
2189 if (hFind
== INVALID_HANDLE_VALUE
)
2191 // Error: most likely reason is that path doesn't exist, so
2192 // append any unprocessed parts and return
2193 for ( i
+= 1; i
< count
; i
++ )
2194 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2199 pathOut
+= findFileData
.cFileName
;
2200 if ( (i
< (count
-1)) )
2201 pathOut
+= wxFILE_SEP_PATH
;
2207 #endif // Win32/!Win32
2212 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2214 if (format
== wxPATH_NATIVE
)
2216 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2217 format
= wxPATH_DOS
;
2218 #elif defined(__VMS)
2219 format
= wxPATH_VMS
;
2221 format
= wxPATH_UNIX
;
2227 #ifdef wxHAS_FILESYSTEM_VOLUMES
2230 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2232 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2234 wxString
vol(drive
);
2235 vol
+= wxFILE_SEP_DSK
;
2236 if ( flags
& wxPATH_GET_SEPARATOR
)
2237 vol
+= wxFILE_SEP_PATH
;
2242 #endif // wxHAS_FILESYSTEM_VOLUMES
2244 // ----------------------------------------------------------------------------
2245 // path splitting function
2246 // ----------------------------------------------------------------------------
2250 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2251 wxString
*pstrVolume
,
2253 wxPathFormat format
)
2255 format
= GetFormat(format
);
2257 wxString fullpath
= fullpathWithVolume
;
2259 if ( IsMSWUniqueVolumeNamePath(fullpath
, format
) )
2261 // special Windows unique volume names hack: transform
2262 // \\?\Volume{guid}\path into Volume{guid}:path
2263 // note: this check must be done before the check for UNC path
2265 // we know the last backslash from the unique volume name is located
2266 // there from IsMSWUniqueVolumeNamePath
2267 fullpath
[wxMSWUniqueVolumePrefixLength
- 1] = wxFILE_SEP_DSK
;
2269 // paths starting with a unique volume name should always be absolute
2270 fullpath
.insert(wxMSWUniqueVolumePrefixLength
, 1, wxFILE_SEP_PATH_DOS
);
2272 // remove the leading "\\?\" part
2273 fullpath
.erase(0, 4);
2275 else if ( IsUNCPath(fullpath
, format
) )
2277 // special Windows UNC paths hack: transform \\share\path into share:path
2279 fullpath
.erase(0, 2);
2281 size_t posFirstSlash
=
2282 fullpath
.find_first_of(GetPathTerminators(format
));
2283 if ( posFirstSlash
!= wxString::npos
)
2285 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2287 // UNC paths are always absolute, right? (FIXME)
2288 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2292 // We separate the volume here
2293 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2295 wxString sepVol
= GetVolumeSeparator(format
);
2297 // we have to exclude the case of a colon in the very beginning of the
2298 // string as it can't be a volume separator (nor can this be a valid
2299 // DOS file name at all but we'll leave dealing with this to our caller)
2300 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2301 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2305 *pstrVolume
= fullpath
.Left(posFirstColon
);
2308 // remove the volume name and the separator from the full path
2309 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2314 *pstrPath
= fullpath
;
2318 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2319 wxString
*pstrVolume
,
2324 wxPathFormat format
)
2326 format
= GetFormat(format
);
2329 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2331 // find the positions of the last dot and last path separator in the path
2332 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2333 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2335 // check whether this dot occurs at the very beginning of a path component
2336 if ( (posLastDot
!= wxString::npos
) &&
2338 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2339 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2341 // dot may be (and commonly -- at least under Unix -- is) the first
2342 // character of the filename, don't treat the entire filename as
2343 // extension in this case
2344 posLastDot
= wxString::npos
;
2347 // if we do have a dot and a slash, check that the dot is in the name part
2348 if ( (posLastDot
!= wxString::npos
) &&
2349 (posLastSlash
!= wxString::npos
) &&
2350 (posLastDot
< posLastSlash
) )
2352 // the dot is part of the path, not the start of the extension
2353 posLastDot
= wxString::npos
;
2356 // now fill in the variables provided by user
2359 if ( posLastSlash
== wxString::npos
)
2366 // take everything up to the path separator but take care to make
2367 // the path equal to something like '/', not empty, for the files
2368 // immediately under root directory
2369 size_t len
= posLastSlash
;
2371 // this rule does not apply to mac since we do not start with colons (sep)
2372 // except for relative paths
2373 if ( !len
&& format
!= wxPATH_MAC
)
2376 *pstrPath
= fullpath
.Left(len
);
2378 // special VMS hack: remove the initial bracket
2379 if ( format
== wxPATH_VMS
)
2381 if ( (*pstrPath
)[0u] == wxT('[') )
2382 pstrPath
->erase(0, 1);
2389 // take all characters starting from the one after the last slash and
2390 // up to, but excluding, the last dot
2391 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2393 if ( posLastDot
== wxString::npos
)
2395 // take all until the end
2396 count
= wxString::npos
;
2398 else if ( posLastSlash
== wxString::npos
)
2402 else // have both dot and slash
2404 count
= posLastDot
- posLastSlash
- 1;
2407 *pstrName
= fullpath
.Mid(nStart
, count
);
2410 // finally deal with the extension here: we have an added complication that
2411 // extension may be empty (but present) as in "foo." where trailing dot
2412 // indicates the empty extension at the end -- and hence we must remember
2413 // that we have it independently of pstrExt
2414 if ( posLastDot
== wxString::npos
)
2424 // take everything after the dot
2426 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2433 void wxFileName::SplitPath(const wxString
& fullpath
,
2437 wxPathFormat format
)
2440 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2444 path
->Prepend(wxGetVolumeString(volume
, format
));
2449 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2451 wxFileName
fn(fullpath
);
2453 return fn
.GetFullPath();
2456 // ----------------------------------------------------------------------------
2458 // ----------------------------------------------------------------------------
2462 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2463 const wxDateTime
*dtMod
,
2464 const wxDateTime
*dtCreate
) const
2466 #if defined(__WIN32__)
2467 FILETIME ftAccess
, ftCreate
, ftWrite
;
2470 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2472 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2474 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2480 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2482 wxLogError(_("Setting directory access times is not supported "
2483 "under this OS version"));
2488 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2492 path
= GetFullPath();
2496 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2499 if ( ::SetFileTime(fh
,
2500 dtCreate
? &ftCreate
: NULL
,
2501 dtAccess
? &ftAccess
: NULL
,
2502 dtMod
? &ftWrite
: NULL
) )
2507 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2508 wxUnusedVar(dtCreate
);
2510 if ( !dtAccess
&& !dtMod
)
2512 // can't modify the creation time anyhow, don't try
2516 // if dtAccess or dtMod is not specified, use the other one (which must be
2517 // non NULL because of the test above) for both times
2519 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2520 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2521 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2525 #else // other platform
2526 wxUnusedVar(dtAccess
);
2528 wxUnusedVar(dtCreate
);
2531 wxLogSysError(_("Failed to modify file times for '%s'"),
2532 GetFullPath().c_str());
2537 bool wxFileName::Touch() const
2539 #if defined(__UNIX_LIKE__)
2540 // under Unix touching file is simple: just pass NULL to utime()
2541 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2546 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2549 #else // other platform
2550 wxDateTime dtNow
= wxDateTime::Now();
2552 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2556 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2558 wxDateTime
*dtCreate
) const
2560 #if defined(__WIN32__)
2561 // we must use different methods for the files and directories under
2562 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2563 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2566 FILETIME ftAccess
, ftCreate
, ftWrite
;
2569 // implemented in msw/dir.cpp
2570 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2571 FILETIME
*, FILETIME
*, FILETIME
*);
2573 // we should pass the path without the trailing separator to
2574 // wxGetDirectoryTimes()
2575 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2576 &ftAccess
, &ftCreate
, &ftWrite
);
2580 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2583 ok
= ::GetFileTime(fh
,
2584 dtCreate
? &ftCreate
: NULL
,
2585 dtAccess
? &ftAccess
: NULL
,
2586 dtMod
? &ftWrite
: NULL
) != 0;
2597 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2599 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2601 ConvertFileTimeToWx(dtMod
, ftWrite
);
2605 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2606 // no need to test for IsDir() here
2608 if ( wxStat( GetFullPath(), &stBuf
) == 0 )
2611 dtAccess
->Set(stBuf
.st_atime
);
2613 dtMod
->Set(stBuf
.st_mtime
);
2615 dtCreate
->Set(stBuf
.st_ctime
);
2619 #else // other platform
2620 wxUnusedVar(dtAccess
);
2622 wxUnusedVar(dtCreate
);
2625 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2626 GetFullPath().c_str());
2631 #endif // wxUSE_DATETIME
2634 // ----------------------------------------------------------------------------
2635 // file size functions
2636 // ----------------------------------------------------------------------------
2641 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2643 if (!wxFileExists(filename
))
2644 return wxInvalidSize
;
2646 #if defined(__WXPALMOS__)
2648 return wxInvalidSize
;
2649 #elif defined(__WIN32__)
2650 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2652 return wxInvalidSize
;
2654 DWORD lpFileSizeHigh
;
2655 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2656 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2657 return wxInvalidSize
;
2659 return wxULongLong(lpFileSizeHigh
, ret
);
2660 #else // ! __WIN32__
2662 if (wxStat( filename
, &st
) != 0)
2663 return wxInvalidSize
;
2664 return wxULongLong(st
.st_size
);
2669 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2670 const wxString
&nullsize
,
2672 wxSizeConvention conv
)
2674 // deal with trivial case first
2675 if ( bs
== 0 || bs
== wxInvalidSize
)
2678 // depending on the convention used the multiplier may be either 1000 or
2679 // 1024 and the binary infix may be empty (for "KB") or "i" (for "KiB")
2680 double multiplier
= 1024.;
2685 case wxSIZE_CONV_TRADITIONAL
:
2686 // nothing to do, this corresponds to the default values of both
2687 // the multiplier and infix string
2690 case wxSIZE_CONV_IEC
:
2694 case wxSIZE_CONV_SI
:
2699 const double kiloByteSize
= multiplier
;
2700 const double megaByteSize
= multiplier
* kiloByteSize
;
2701 const double gigaByteSize
= multiplier
* megaByteSize
;
2702 const double teraByteSize
= multiplier
* gigaByteSize
;
2704 const double bytesize
= bs
.ToDouble();
2707 if ( bytesize
< kiloByteSize
)
2708 result
.Printf("%s B", bs
.ToString());
2709 else if ( bytesize
< megaByteSize
)
2710 result
.Printf("%.*f K%sB", precision
, bytesize
/kiloByteSize
, biInfix
);
2711 else if (bytesize
< gigaByteSize
)
2712 result
.Printf("%.*f M%sB", precision
, bytesize
/megaByteSize
, biInfix
);
2713 else if (bytesize
< teraByteSize
)
2714 result
.Printf("%.*f G%sB", precision
, bytesize
/gigaByteSize
, biInfix
);
2716 result
.Printf("%.*f T%sB", precision
, bytesize
/teraByteSize
, biInfix
);
2721 wxULongLong
wxFileName::GetSize() const
2723 return GetSize(GetFullPath());
2726 wxString
wxFileName::GetHumanReadableSize(const wxString
& failmsg
,
2728 wxSizeConvention conv
) const
2730 return GetHumanReadableSize(GetSize(), failmsg
, precision
, conv
);
2733 #endif // wxUSE_LONGLONG
2735 // ----------------------------------------------------------------------------
2736 // Mac-specific functions
2737 // ----------------------------------------------------------------------------
2739 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2744 class MacDefaultExtensionRecord
2747 MacDefaultExtensionRecord()
2753 // default copy ctor, assignment operator and dtor are ok
2755 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2759 m_creator
= creator
;
2767 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2769 bool gMacDefaultExtensionsInited
= false;
2771 #include "wx/arrimpl.cpp"
2773 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2775 MacDefaultExtensionArray gMacDefaultExtensions
;
2777 // load the default extensions
2778 const MacDefaultExtensionRecord gDefaults
[] =
2780 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2781 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2782 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2785 void MacEnsureDefaultExtensionsLoaded()
2787 if ( !gMacDefaultExtensionsInited
)
2789 // we could load the pc exchange prefs here too
2790 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2792 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2794 gMacDefaultExtensionsInited
= true;
2798 } // anonymous namespace
2800 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2803 FSCatalogInfo catInfo
;
2806 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2808 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2810 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2811 finfo
->fileType
= type
;
2812 finfo
->fileCreator
= creator
;
2813 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2820 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2823 FSCatalogInfo catInfo
;
2826 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2828 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2830 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2831 *type
= finfo
->fileType
;
2832 *creator
= finfo
->fileCreator
;
2839 bool wxFileName::MacSetDefaultTypeAndCreator()
2841 wxUint32 type
, creator
;
2842 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2845 return MacSetTypeAndCreator( type
, creator
) ;
2850 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2852 MacEnsureDefaultExtensionsLoaded() ;
2853 wxString extl
= ext
.Lower() ;
2854 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2856 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2858 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2859 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2866 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2868 MacEnsureDefaultExtensionsLoaded();
2869 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2870 gMacDefaultExtensions
.Add( rec
);
2873 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON