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 license
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
27 wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
29 volume:dir1:...:dirN:filename
30 and the relative file names are either
31 :dir1:...:dirN:filename
34 (although :filename works as well).
35 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
39 wxPATH_VMS: VMS native format, absolute file names have the form
40 <device>:[dir1.dir2.dir3]file.txt
42 <device>:[000000.dir1.dir2.dir3]file.txt
44 the <device> is the physical device (i.e. disk). 000000 is the
45 root directory on the device which can be omitted.
47 Note that VMS uses different separators unlike Unix:
48 : always after the device. If the path does not contain : than
49 the default (the device of the current directory) is assumed.
50 [ start of directory specyfication
51 . separator between directory and subdirectory
52 ] between directory and file
55 // ============================================================================
57 // ============================================================================
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
64 #pragma implementation "filename.h"
67 // For compilers that support precompilation, includes "wx.h".
68 #include "wx/wxprec.h"
80 #include "wx/filename.h"
81 #include "wx/tokenzr.h"
82 #include "wx/config.h" // for wxExpandEnvVars
85 //#include "wx/dynlib.h" // see GetLongPath below, code disabled.
87 // For GetShort/LongPathName
90 #include "wx/msw/winundef.h"
93 #if defined(__WXMAC__)
94 #include "wx/mac/private.h" // includes mac headers
97 // utime() is POSIX so should normally be available on all Unices
99 #include <sys/types.h>
101 #include <sys/stat.h>
117 #include <sys/utime.h>
118 #include <sys/stat.h>
127 // ----------------------------------------------------------------------------
129 // ----------------------------------------------------------------------------
131 // small helper class which opens and closes the file - we use it just to get
132 // a file handle for the given file name to pass it to some Win32 API function
133 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
144 wxFileHandle(const wxString
& filename
, OpenMode mode
)
146 m_hFile
= ::CreateFile
149 mode
== Read
? GENERIC_READ
// access mask
152 NULL
, // no secutity attr
153 OPEN_EXISTING
, // creation disposition
155 NULL
// no template file
158 if ( m_hFile
== INVALID_HANDLE_VALUE
)
160 wxLogSysError(_("Failed to open '%s' for %s"),
162 mode
== Read
? _("reading") : _("writing"));
168 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
170 if ( !::CloseHandle(m_hFile
) )
172 wxLogSysError(_("Failed to close file handle"));
177 // return TRUE only if the file could be opened successfully
178 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
181 operator HANDLE() const { return m_hFile
; }
189 // ----------------------------------------------------------------------------
191 // ----------------------------------------------------------------------------
193 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
195 // convert between wxDateTime and FILETIME which is a 64-bit value representing
196 // the number of 100-nanosecond intervals since January 1, 1601.
198 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
200 FILETIME ftcopy
= ft
;
202 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
204 wxLogLastError(_T("FileTimeToLocalFileTime"));
208 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
210 wxLogLastError(_T("FileTimeToSystemTime"));
213 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
214 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
217 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
220 st
.wDay
= dt
.GetDay();
221 st
.wMonth
= dt
.GetMonth() + 1;
222 st
.wYear
= dt
.GetYear();
223 st
.wHour
= dt
.GetHour();
224 st
.wMinute
= dt
.GetMinute();
225 st
.wSecond
= dt
.GetSecond();
226 st
.wMilliseconds
= dt
.GetMillisecond();
229 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
231 wxLogLastError(_T("SystemTimeToFileTime"));
234 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
236 wxLogLastError(_T("LocalFileTimeToFileTime"));
242 // ============================================================================
244 // ============================================================================
246 // ----------------------------------------------------------------------------
247 // wxFileName construction
248 // ----------------------------------------------------------------------------
250 void wxFileName::Assign( const wxFileName
&filepath
)
252 m_volume
= filepath
.GetVolume();
253 m_dirs
= filepath
.GetDirs();
254 m_name
= filepath
.GetName();
255 m_ext
= filepath
.GetExt();
256 m_relative
= filepath
.m_relative
;
259 void wxFileName::Assign(const wxString
& volume
,
260 const wxString
& path
,
261 const wxString
& name
,
263 wxPathFormat format
)
265 SetPath( path
, format
);
272 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
278 wxPathFormat my_format
= GetFormat( format
);
279 wxString my_path
= path
;
281 // 1) Determine if the path is relative or absolute.
282 wxChar leadingChar
= my_path
[0u];
287 m_relative
= leadingChar
== wxT(':');
289 // We then remove a leading ":". The reason is in our
290 // storage form for relative paths:
291 // ":dir:file.txt" actually means "./dir/file.txt" in
292 // DOS notation and should get stored as
293 // (relative) (dir) (file.txt)
294 // "::dir:file.txt" actually means "../dir/file.txt"
295 // stored as (relative) (..) (dir) (file.txt)
296 // This is important only for the Mac as an empty dir
297 // actually means <UP>, whereas under DOS, double
298 // slashes can be ignored: "\\\\" is the same as "\\".
300 my_path
.erase( 0, 1 );
304 // TODO: what is the relative path format here?
309 // the paths of the form "~" or "~username" are absolute
310 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
314 m_relative
= !IsPathSeparator(leadingChar
, my_format
);
318 wxFAIL_MSG( wxT("error") );
322 // 2) Break up the path into its members. If the original path
323 // was just "/" or "\\", m_dirs will be empty. We know from
324 // the m_relative field, if this means "nothing" or "root dir".
326 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
328 while ( tn
.HasMoreTokens() )
330 wxString token
= tn
.GetNextToken();
332 // Remove empty token under DOS and Unix, interpret them
336 if (my_format
== wxPATH_MAC
)
337 m_dirs
.Add( wxT("..") );
346 else // no path at all
352 void wxFileName::Assign(const wxString
& fullpath
,
355 wxString volume
, path
, name
, ext
;
356 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
358 Assign(volume
, path
, name
, ext
, format
);
361 void wxFileName::Assign(const wxString
& fullpathOrig
,
362 const wxString
& fullname
,
365 // always recognize fullpath as directory, even if it doesn't end with a
367 wxString fullpath
= fullpathOrig
;
368 if ( !wxEndsWithPathSeparator(fullpath
) )
370 fullpath
+= GetPathSeparators(format
)[0u];
373 wxString volume
, path
, name
, ext
;
375 // do some consistency checks in debug mode: the name should be really just
376 // the filename and the path should be really just a path
378 wxString pathDummy
, nameDummy
, extDummy
;
380 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
382 wxASSERT_MSG( pathDummy
.empty(),
383 _T("the file name shouldn't contain the path") );
385 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
387 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
388 _T("the path shouldn't contain file name nor extension") );
390 #else // !__WXDEBUG__
391 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
392 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
393 #endif // __WXDEBUG__/!__WXDEBUG__
395 Assign(volume
, path
, name
, ext
, format
);
398 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
400 Assign(dir
, _T(""), format
);
403 void wxFileName::Clear()
409 m_ext
= wxEmptyString
;
413 wxFileName
wxFileName::FileName(const wxString
& file
)
415 return wxFileName(file
);
419 wxFileName
wxFileName::DirName(const wxString
& dir
)
426 // ----------------------------------------------------------------------------
428 // ----------------------------------------------------------------------------
430 bool wxFileName::FileExists()
432 return wxFileName::FileExists( GetFullPath() );
435 bool wxFileName::FileExists( const wxString
&file
)
437 return ::wxFileExists( file
);
440 bool wxFileName::DirExists()
442 return wxFileName::DirExists( GetFullPath() );
445 bool wxFileName::DirExists( const wxString
&dir
)
447 return ::wxDirExists( dir
);
450 // ----------------------------------------------------------------------------
451 // CWD and HOME stuff
452 // ----------------------------------------------------------------------------
454 void wxFileName::AssignCwd(const wxString
& volume
)
456 AssignDir(wxFileName::GetCwd(volume
));
460 wxString
wxFileName::GetCwd(const wxString
& volume
)
462 // if we have the volume, we must get the current directory on this drive
463 // and to do this we have to chdir to this volume - at least under Windows,
464 // I don't know how to get the current drive on another volume elsewhere
467 if ( !volume
.empty() )
470 SetCwd(volume
+ GetVolumeSeparator());
473 wxString cwd
= ::wxGetCwd();
475 if ( !volume
.empty() )
483 bool wxFileName::SetCwd()
485 return wxFileName::SetCwd( GetFullPath() );
488 bool wxFileName::SetCwd( const wxString
&cwd
)
490 return ::wxSetWorkingDirectory( cwd
);
493 void wxFileName::AssignHomeDir()
495 AssignDir(wxFileName::GetHomeDir());
498 wxString
wxFileName::GetHomeDir()
500 return ::wxGetHomeDir();
503 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
505 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
506 if ( tempname
.empty() )
508 // error, failed to get temp file name
519 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
521 wxString path
, dir
, name
;
523 // use the directory specified by the prefix
524 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
526 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
531 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
533 wxLogLastError(_T("GetTempPath"));
538 // GetTempFileName() fails if we pass it an empty string
542 else // we have a dir to create the file in
544 // ensure we use only the back slashes as GetTempFileName(), unlike all
545 // the other APIs, is picky and doesn't accept the forward ones
546 dir
.Replace(_T("/"), _T("\\"));
549 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
551 wxLogLastError(_T("GetTempFileName"));
556 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
562 #elif defined(__WXPM__)
563 // for now just create a file
565 // future enhancements can be to set some extended attributes for file
566 // systems OS/2 supports that have them (HPFS, FAT32) and security
568 static const wxChar
*szMktempSuffix
= wxT("XXX");
569 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
571 // Temporarily remove - MN
573 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
576 #else // !Windows, !OS/2
579 #if defined(__WXMAC__) && !defined(__DARWIN__)
580 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
582 dir
= wxGetenv(_T("TMP"));
585 dir
= wxGetenv(_T("TEMP"));
602 if ( !wxEndsWithPathSeparator(dir
) &&
603 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
605 path
+= wxFILE_SEP_PATH
;
610 #if defined(HAVE_MKSTEMP)
611 // scratch space for mkstemp()
612 path
+= _T("XXXXXX");
614 // can use the cast here because the length doesn't change and the string
616 int fdTemp
= mkstemp((char *)path
.mb_str());
619 // this might be not necessary as mkstemp() on most systems should have
620 // already done it but it doesn't hurt neither...
623 else // mkstemp() succeeded
625 // avoid leaking the fd
628 fileTemp
->Attach(fdTemp
);
635 #else // !HAVE_MKSTEMP
639 path
+= _T("XXXXXX");
641 if ( !mktemp((char *)path
.mb_str()) )
645 #else // !HAVE_MKTEMP (includes __DOS__)
646 // generate the unique file name ourselves
648 path
<< (unsigned int)getpid();
653 static const size_t numTries
= 1000;
654 for ( size_t n
= 0; n
< numTries
; n
++ )
656 // 3 hex digits is enough for numTries == 1000 < 4096
657 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
658 if ( !wxFile::Exists(pathTry
) )
667 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
672 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
674 #endif // Windows/!Windows
678 wxLogSysError(_("Failed to create a temporary file name"));
680 else if ( fileTemp
&& !fileTemp
->IsOpened() )
682 // open the file - of course, there is a race condition here, this is
683 // why we always prefer using mkstemp()...
685 // NB: GetTempFileName() under Windows creates the file, so using
686 // write_excl there would fail
687 if ( !fileTemp
->Open(path
,
688 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
693 wxS_IRUSR
| wxS_IWUSR
) )
695 // FIXME: If !ok here should we loop and try again with another
696 // file name? That is the standard recourse if open(O_EXCL)
697 // fails, though of course it should be protected against
698 // possible infinite looping too.
700 wxLogError(_("Failed to open temporary file."));
709 // ----------------------------------------------------------------------------
710 // directory operations
711 // ----------------------------------------------------------------------------
713 bool wxFileName::Mkdir( int perm
, bool full
)
715 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
718 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
722 wxFileName
filename(dir
);
723 wxArrayString dirs
= filename
.GetDirs();
724 dirs
.Add(filename
.GetName());
726 size_t count
= dirs
.GetCount();
730 for ( i
= 0; i
< count
; i
++ )
734 if (currPath
.Last() == wxT(':'))
736 // Can't create a root directory so continue to next dir
737 currPath
+= wxFILE_SEP_PATH
;
741 if (!DirExists(currPath
))
742 if (!wxMkdir(currPath
, perm
))
745 if ( (i
< (count
-1)) )
746 currPath
+= wxFILE_SEP_PATH
;
749 return (noErrors
== 0);
753 return ::wxMkdir( dir
, perm
);
756 bool wxFileName::Rmdir()
758 return wxFileName::Rmdir( GetFullPath() );
761 bool wxFileName::Rmdir( const wxString
&dir
)
763 return ::wxRmdir( dir
);
766 // ----------------------------------------------------------------------------
767 // path normalization
768 // ----------------------------------------------------------------------------
770 bool wxFileName::Normalize(int flags
,
774 // the existing path components
775 wxArrayString dirs
= GetDirs();
777 // the path to prepend in front to make the path absolute
780 format
= GetFormat(format
);
782 // make the path absolute
783 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
787 curDir
.AssignCwd(GetVolume());
791 curDir
.AssignDir(cwd
);
794 // the path may be not absolute because it doesn't have the volume name
795 // but in this case we shouldn't modify the directory components of it
796 // but just set the current volume
797 if ( !HasVolume() && curDir
.HasVolume() )
799 SetVolume(curDir
.GetVolume());
803 // yes, it was the case - we don't need curDir then
809 // handle ~ stuff under Unix only
810 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
812 if ( !dirs
.IsEmpty() )
814 wxString dir
= dirs
[0u];
815 if ( !dir
.empty() && dir
[0u] == _T('~') )
817 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
824 // transform relative path into abs one
827 wxArrayString dirsNew
= curDir
.GetDirs();
828 size_t count
= dirs
.GetCount();
829 for ( size_t n
= 0; n
< count
; n
++ )
831 dirsNew
.Add(dirs
[n
]);
837 // now deal with ".", ".." and the rest
839 size_t count
= dirs
.GetCount();
840 for ( size_t n
= 0; n
< count
; n
++ )
842 wxString dir
= dirs
[n
];
844 if ( flags
& wxPATH_NORM_DOTS
)
846 if ( dir
== wxT(".") )
852 if ( dir
== wxT("..") )
854 if ( m_dirs
.IsEmpty() )
856 wxLogError(_("The path '%s' contains too many \"..\"!"),
857 GetFullPath().c_str());
861 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
866 if ( flags
& wxPATH_NORM_ENV_VARS
)
868 dir
= wxExpandEnvVars(dir
);
871 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
879 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
881 // VZ: expand env vars here too?
887 #if defined(__WIN32__)
888 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
890 Assign(GetLongPath());
894 // we do have the path now
900 // ----------------------------------------------------------------------------
901 // absolute/relative paths
902 // ----------------------------------------------------------------------------
904 bool wxFileName::IsAbsolute(wxPathFormat format
) const
906 // if our path doesn't start with a path separator, it's not an absolute
911 if ( !GetVolumeSeparator(format
).empty() )
913 // this format has volumes and an absolute path must have one, it's not
914 // enough to have the full path to bean absolute file under Windows
915 if ( GetVolume().empty() )
922 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
924 wxFileName
fnBase(pathBase
, format
);
926 // get cwd only once - small time saving
927 wxString cwd
= wxGetCwd();
928 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
929 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
931 bool withCase
= IsCaseSensitive(format
);
933 // we can't do anything if the files live on different volumes
934 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
940 // same drive, so we don't need our volume
943 // remove common directories starting at the top
944 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
945 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
948 fnBase
.m_dirs
.RemoveAt(0);
951 // add as many ".." as needed
952 size_t count
= fnBase
.m_dirs
.GetCount();
953 for ( size_t i
= 0; i
< count
; i
++ )
955 m_dirs
.Insert(wxT(".."), 0u);
964 // ----------------------------------------------------------------------------
965 // filename kind tests
966 // ----------------------------------------------------------------------------
968 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
970 wxFileName fn1
= *this,
973 // get cwd only once - small time saving
974 wxString cwd
= wxGetCwd();
975 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
976 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
978 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
981 // TODO: compare inodes for Unix, this works even when filenames are
982 // different but files are the same (symlinks) (VZ)
988 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
990 // only Unix filenames are truely case-sensitive
991 return GetFormat(format
) == wxPATH_UNIX
;
995 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
999 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1000 (GetFormat(format
) == wxPATH_VMS
) )
1002 sepVol
= wxFILE_SEP_DSK
;
1010 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1013 switch ( GetFormat(format
) )
1016 // accept both as native APIs do but put the native one first as
1017 // this is the one we use in GetFullPath()
1018 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1022 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
1026 seps
= wxFILE_SEP_PATH_UNIX
;
1030 seps
= wxFILE_SEP_PATH_MAC
;
1034 seps
= wxFILE_SEP_PATH_VMS
;
1042 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1044 // wxString::Find() doesn't work as expected with NUL - it will always find
1045 // it, so it is almost surely a bug if this function is called with NUL arg
1046 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1048 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1051 bool wxFileName::IsWild( wxPathFormat
WXUNUSED(format
) )
1053 // FIXME: this is probably false for Mac and this is surely wrong for most
1054 // of Unix shells (think about "[...]")
1055 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
1058 // ----------------------------------------------------------------------------
1059 // path components manipulation
1060 // ----------------------------------------------------------------------------
1062 void wxFileName::AppendDir( const wxString
&dir
)
1067 void wxFileName::PrependDir( const wxString
&dir
)
1069 m_dirs
.Insert( dir
, 0 );
1072 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1074 m_dirs
.Insert( dir
, before
);
1077 void wxFileName::RemoveDir( int pos
)
1079 m_dirs
.Remove( (size_t)pos
);
1082 // ----------------------------------------------------------------------------
1084 // ----------------------------------------------------------------------------
1086 void wxFileName::SetFullName(const wxString
& fullname
)
1088 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1091 wxString
wxFileName::GetFullName() const
1093 wxString fullname
= m_name
;
1094 if ( !m_ext
.empty() )
1096 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1102 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1104 format
= GetFormat( format
);
1108 // the leading character
1109 if ( format
== wxPATH_MAC
&& m_relative
)
1111 fullpath
+= wxFILE_SEP_PATH_MAC
;
1113 else if ( format
== wxPATH_DOS
)
1116 fullpath
+= wxFILE_SEP_PATH_DOS
;
1118 else if ( format
== wxPATH_UNIX
)
1121 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1124 // then concatenate all the path components using the path separator
1125 size_t dirCount
= m_dirs
.GetCount();
1128 if ( format
== wxPATH_VMS
)
1130 fullpath
+= wxT('[');
1134 for ( size_t i
= 0; i
< dirCount
; i
++ )
1136 // TODO: What to do with ".." under VMS
1142 if (m_dirs
[i
] == wxT("."))
1144 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1145 fullpath
+= m_dirs
[i
];
1146 fullpath
+= wxT(':');
1151 fullpath
+= m_dirs
[i
];
1152 fullpath
+= wxT('\\');
1157 fullpath
+= m_dirs
[i
];
1158 fullpath
+= wxT('/');
1163 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1164 fullpath
+= m_dirs
[i
];
1165 if (i
== dirCount
-1)
1166 fullpath
+= wxT(']');
1168 fullpath
+= wxT('.');
1173 wxFAIL_MSG( wxT("error") );
1179 if ( add_separator
&& !fullpath
.empty() )
1181 fullpath
+= GetPathSeparators(format
)[0u];
1187 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1189 format
= GetFormat(format
);
1193 // first put the volume
1194 if ( !m_volume
.empty() )
1197 // Special Windows UNC paths hack, part 2: undo what we did in
1198 // SplitPath() and make an UNC path if we have a drive which is not a
1199 // single letter (hopefully the network shares can't be one letter only
1200 // although I didn't find any authoritative docs on this)
1201 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1203 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1205 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1207 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1213 // the leading character
1214 if ( format
== wxPATH_MAC
)
1217 fullpath
+= wxFILE_SEP_PATH_MAC
;
1219 else if ( format
== wxPATH_DOS
)
1222 fullpath
+= wxFILE_SEP_PATH_DOS
;
1224 else if ( format
== wxPATH_UNIX
)
1228 // normally the absolute file names starts with a slash with one
1229 // exception: file names like "~/foo.bar" don't have it
1230 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1232 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1237 // then concatenate all the path components using the path separator
1238 size_t dirCount
= m_dirs
.GetCount();
1241 if ( format
== wxPATH_VMS
)
1243 fullpath
+= wxT('[');
1247 for ( size_t i
= 0; i
< dirCount
; i
++ )
1249 // TODO: What to do with ".." under VMS
1255 if (m_dirs
[i
] == wxT("."))
1257 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1258 fullpath
+= m_dirs
[i
];
1259 fullpath
+= wxT(':');
1264 fullpath
+= m_dirs
[i
];
1265 fullpath
+= wxT('\\');
1270 fullpath
+= m_dirs
[i
];
1271 fullpath
+= wxT('/');
1276 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1277 fullpath
+= m_dirs
[i
];
1278 if (i
== dirCount
-1)
1279 fullpath
+= wxT(']');
1281 fullpath
+= wxT('.');
1286 wxFAIL_MSG( wxT("error") );
1292 // finally add the file name and extension
1293 fullpath
+= GetFullName();
1298 // Return the short form of the path (returns identity on non-Windows platforms)
1299 wxString
wxFileName::GetShortPath() const
1301 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1302 wxString
path(GetFullPath());
1304 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1308 ok
= ::GetShortPathName
1311 pathOut
.GetWriteBuf(sz
),
1314 pathOut
.UngetWriteBuf();
1321 return GetFullPath();
1325 // Return the long form of the path (returns identity on non-Windows platforms)
1326 wxString
wxFileName::GetLongPath() const
1329 path
= GetFullPath();
1331 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1332 bool success
= FALSE
;
1334 // VZ: why was this code disabled?
1335 #if 0 // wxUSE_DYNAMIC_LOADER
1336 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1338 static bool s_triedToLoad
= FALSE
;
1340 if ( !s_triedToLoad
)
1342 s_triedToLoad
= TRUE
;
1343 wxDynamicLibrary
dllKernel(_T("kernel32"));
1344 if ( dllKernel
.IsLoaded() )
1346 // may succeed or fail depending on the Windows version
1347 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1349 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1351 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1354 if ( s_pfnGetLongPathName
)
1356 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1357 bool ok
= dwSize
> 0;
1361 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1365 ok
= (*s_pfnGetLongPathName
)
1368 pathOut
.GetWriteBuf(sz
),
1371 pathOut
.UngetWriteBuf();
1381 #endif // wxUSE_DYNAMIC_LOADER
1385 // The OS didn't support GetLongPathName, or some other error.
1386 // We need to call FindFirstFile on each component in turn.
1388 WIN32_FIND_DATA findFileData
;
1390 pathOut
= wxEmptyString
;
1392 wxArrayString dirs
= GetDirs();
1393 dirs
.Add(GetFullName());
1397 size_t count
= dirs
.GetCount();
1398 for ( size_t i
= 0; i
< count
; i
++ )
1400 // We're using pathOut to collect the long-name path, but using a
1401 // temporary for appending the last path component which may be
1403 tmpPath
= pathOut
+ dirs
[i
];
1405 if ( tmpPath
.empty() )
1408 if ( tmpPath
.Last() == wxT(':') )
1410 // Can't pass a drive and root dir to FindFirstFile,
1411 // so continue to next dir
1412 tmpPath
+= wxFILE_SEP_PATH
;
1417 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1418 if (hFind
== INVALID_HANDLE_VALUE
)
1420 // Error: return immediately with the original path
1424 pathOut
+= findFileData
.cFileName
;
1425 if ( (i
< (count
-1)) )
1426 pathOut
+= wxFILE_SEP_PATH
;
1433 #endif // Win32/!Win32
1438 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1440 if (format
== wxPATH_NATIVE
)
1442 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1443 format
= wxPATH_DOS
;
1444 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1445 format
= wxPATH_MAC
;
1446 #elif defined(__VMS)
1447 format
= wxPATH_VMS
;
1449 format
= wxPATH_UNIX
;
1455 // ----------------------------------------------------------------------------
1456 // path splitting function
1457 // ----------------------------------------------------------------------------
1460 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1461 wxString
*pstrVolume
,
1465 wxPathFormat format
)
1467 format
= GetFormat(format
);
1469 wxString fullpath
= fullpathWithVolume
;
1471 // under VMS the end of the path is ']', not the path separator used to
1472 // separate the components
1473 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1474 : GetPathSeparators(format
);
1476 // special Windows UNC paths hack: transform \\share\path into share:path
1477 if ( format
== wxPATH_DOS
)
1479 if ( fullpath
.length() >= 4 &&
1480 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1481 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1483 fullpath
.erase(0, 2);
1485 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1486 if ( posFirstSlash
!= wxString::npos
)
1488 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1490 // UNC paths are always absolute, right? (FIXME)
1491 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1496 // We separate the volume here
1497 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1499 wxString sepVol
= GetVolumeSeparator(format
);
1501 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1502 if ( posFirstColon
!= wxString::npos
)
1506 *pstrVolume
= fullpath
.Left(posFirstColon
);
1509 // remove the volume name and the separator from the full path
1510 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1514 // find the positions of the last dot and last path separator in the path
1515 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1516 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1518 if ( (posLastDot
!= wxString::npos
) &&
1519 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1521 if ( (posLastDot
== 0) ||
1522 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1524 // under Unix and VMS, dot may be (and commonly is) the first
1525 // character of the filename, don't treat the entire filename as
1526 // extension in this case
1527 posLastDot
= wxString::npos
;
1531 // if we do have a dot and a slash, check that the dot is in the name part
1532 if ( (posLastDot
!= wxString::npos
) &&
1533 (posLastSlash
!= wxString::npos
) &&
1534 (posLastDot
< posLastSlash
) )
1536 // the dot is part of the path, not the start of the extension
1537 posLastDot
= wxString::npos
;
1540 // now fill in the variables provided by user
1543 if ( posLastSlash
== wxString::npos
)
1550 // take everything up to the path separator but take care to make
1551 // the path equal to something like '/', not empty, for the files
1552 // immediately under root directory
1553 size_t len
= posLastSlash
;
1555 // this rule does not apply to mac since we do not start with colons (sep)
1556 // except for relative paths
1557 if ( !len
&& format
!= wxPATH_MAC
)
1560 *pstrPath
= fullpath
.Left(len
);
1562 // special VMS hack: remove the initial bracket
1563 if ( format
== wxPATH_VMS
)
1565 if ( (*pstrPath
)[0u] == _T('[') )
1566 pstrPath
->erase(0, 1);
1573 // take all characters starting from the one after the last slash and
1574 // up to, but excluding, the last dot
1575 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1577 if ( posLastDot
== wxString::npos
)
1579 // take all until the end
1580 count
= wxString::npos
;
1582 else if ( posLastSlash
== wxString::npos
)
1586 else // have both dot and slash
1588 count
= posLastDot
- posLastSlash
- 1;
1591 *pstrName
= fullpath
.Mid(nStart
, count
);
1596 if ( posLastDot
== wxString::npos
)
1603 // take everything after the dot
1604 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1610 void wxFileName::SplitPath(const wxString
& fullpath
,
1614 wxPathFormat format
)
1617 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1619 if ( path
&& !volume
.empty() )
1621 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1625 // ----------------------------------------------------------------------------
1627 // ----------------------------------------------------------------------------
1629 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1630 const wxDateTime
*dtMod
,
1631 const wxDateTime
*dtCreate
)
1633 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1634 if ( !dtAccess
&& !dtMod
)
1636 // can't modify the creation time anyhow, don't try
1640 // if dtAccess or dtMod is not specified, use the other one (which must be
1641 // non NULL because of the test above) for both times
1643 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1644 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1645 if ( utime(GetFullPath(), &utm
) == 0 )
1649 #elif defined(__WIN32__)
1650 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1653 FILETIME ftAccess
, ftCreate
, ftWrite
;
1656 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1658 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1660 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1662 if ( ::SetFileTime(fh
,
1663 dtCreate
? &ftCreate
: NULL
,
1664 dtAccess
? &ftAccess
: NULL
,
1665 dtMod
? &ftWrite
: NULL
) )
1670 #else // other platform
1673 wxLogSysError(_("Failed to modify file times for '%s'"),
1674 GetFullPath().c_str());
1679 bool wxFileName::Touch()
1681 #if defined(__UNIX_LIKE__)
1682 // under Unix touching file is simple: just pass NULL to utime()
1683 if ( utime(GetFullPath(), NULL
) == 0 )
1688 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1691 #else // other platform
1692 wxDateTime dtNow
= wxDateTime::Now();
1694 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1698 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1700 wxDateTime
*dtCreate
) const
1702 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1704 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1707 dtAccess
->Set(stBuf
.st_atime
);
1709 dtMod
->Set(stBuf
.st_mtime
);
1711 dtCreate
->Set(stBuf
.st_ctime
);
1715 #elif defined(__WIN32__)
1716 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1719 FILETIME ftAccess
, ftCreate
, ftWrite
;
1721 if ( ::GetFileTime(fh
,
1722 dtMod
? &ftCreate
: NULL
,
1723 dtAccess
? &ftAccess
: NULL
,
1724 dtCreate
? &ftWrite
: NULL
) )
1727 ConvertFileTimeToWx(dtMod
, ftCreate
);
1729 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1731 ConvertFileTimeToWx(dtCreate
, ftWrite
);
1736 #else // other platform
1739 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1740 GetFullPath().c_str());
1747 const short kMacExtensionMaxLength
= 16 ;
1750 char m_ext
[kMacExtensionMaxLength
] ;
1753 } MacDefaultExtensionRecord
;
1755 #include "wx/dynarray.h"
1756 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1757 #include "wx/arrimpl.cpp"
1758 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray
) ;
1760 MacDefaultExtensionArray gMacDefaultExtensions
;
1761 bool gMacDefaultExtensionsInited
= false ;
1763 static void MacEnsureDefaultExtensionsLoaded()
1765 if ( !gMacDefaultExtensionsInited
)
1767 // load the default extensions
1768 MacDefaultExtensionRecord defaults
[] =
1770 { "txt" , 'TEXT' , 'ttxt' } ,
1773 // we could load the pc exchange prefs here too
1775 for ( int i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1777 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1779 gMacDefaultExtensionsInited
= true ;
1782 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1786 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1787 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1788 wxCHECK( err
== noErr
, false ) ;
1790 fndrInfo
.fdType
= type
;
1791 fndrInfo
.fdCreator
= creator
;
1792 FSpSetFInfo( &spec
, &fndrInfo
) ;
1796 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1800 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1801 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1802 wxCHECK( err
== noErr
, false ) ;
1804 *type
= fndrInfo
.fdType
;
1805 *creator
= fndrInfo
.fdCreator
;
1809 bool wxFileName::MacSetDefaultTypeAndCreator()
1811 wxUint32 type
, creator
;
1812 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1815 return MacSetTypeAndCreator( type
, creator
) ;
1820 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1822 MacEnsureDefaultExtensionsLoaded() ;
1823 wxString extl
= ext
.Lower() ;
1824 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1826 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1828 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1829 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1836 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1838 MacEnsureDefaultExtensionsLoaded() ;
1839 MacDefaultExtensionRecord rec
;
1841 rec
.m_creator
= creator
;
1842 strncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1843 gMacDefaultExtensions
.Add( rec
) ;