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 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "filename.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
36 #include "wx/filename.h"
37 #include "wx/tokenzr.h"
38 #include "wx/config.h" // for wxExpandEnvVars
41 #if wxUSE_DYNLIB_CLASS
42 #include "wx/dynlib.h"
45 // For GetShort/LongPathName
49 #include "wx/msw/winundef.h"
52 // utime() is POSIX so should normally be available on all Unices
54 #include <sys/types.h>
60 // ----------------------------------------------------------------------------
62 // ----------------------------------------------------------------------------
64 // small helper class which opens and closes the file - we use it just to get
65 // a file handle for the given file name to pass it to some Win32 API function
71 wxFileHandle(const wxString
& filename
)
73 m_hFile
= ::CreateFile
76 GENERIC_READ
, // access mask
78 NULL
, // no secutity attr
79 OPEN_EXISTING
, // creation disposition
81 NULL
// no template file
84 if ( m_hFile
== INVALID_HANDLE_VALUE
)
86 wxLogSysError(_("Failed to open '%s' for reading"),
93 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
95 if ( !::CloseHandle(m_hFile
) )
97 wxLogSysError(_("Failed to close file handle"));
102 // return TRUE only if the file could be opened successfully
103 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
106 operator HANDLE() const { return m_hFile
; }
114 // ----------------------------------------------------------------------------
116 // ----------------------------------------------------------------------------
120 // convert between wxDateTime and FILETIME which is a 64-bit value representing
121 // the number of 100-nanosecond intervals since January 1, 1601.
123 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
124 // FILETIME reference point (January 1, 1601)
125 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
127 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
129 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
131 // convert 100ns to ms
134 // move it to our Epoch
135 ll
-= FILETIME_EPOCH_OFFSET
;
137 *dt
= wxDateTime(ll
);
140 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
142 // do the reverse of ConvertFileTimeToWx()
143 wxLongLong ll
= dt
.GetValue();
145 ll
+= FILETIME_EPOCH_OFFSET
;
147 ft
->dwHighDateTime
= ll
.GetHi();
148 ft
->dwLowDateTime
= ll
.GetLo();
153 // ============================================================================
155 // ============================================================================
157 // ----------------------------------------------------------------------------
158 // wxFileName construction
159 // ----------------------------------------------------------------------------
161 void wxFileName::Assign( const wxFileName
&filepath
)
163 m_ext
= filepath
.GetExt();
164 m_name
= filepath
.GetName();
165 m_dirs
= filepath
.GetDirs();
168 void wxFileName::Assign( const wxString
& path
,
169 const wxString
& name
,
171 wxPathFormat format
)
173 wxStringTokenizer
tn(path
, GetPathSeparators(format
),
174 wxTOKEN_RET_EMPTY_ALL
);
177 while ( tn
.HasMoreTokens() )
179 wxString token
= tn
.GetNextToken();
181 // If the path starts with a slash (or two for a network path),
182 // we need the first dir entry to be an empty for later reassembly.
183 if ((i
< 2) || !token
.IsEmpty())
193 void wxFileName::Assign(const wxString
& fullpath
,
196 wxString path
, name
, ext
;
197 SplitPath(fullpath
, &path
, &name
, &ext
, format
);
199 Assign(path
, name
, ext
, format
);
202 void wxFileName::Assign(const wxString
& path
,
203 const wxString
& fullname
,
207 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
209 Assign(path
, name
, ext
, format
);
212 void wxFileName::Clear()
216 m_ext
= wxEmptyString
;
220 wxFileName
wxFileName::FileName(const wxString
& file
)
222 return wxFileName(file
);
226 wxFileName
wxFileName::DirName(const wxString
& dir
)
233 // ----------------------------------------------------------------------------
235 // ----------------------------------------------------------------------------
237 bool wxFileName::FileExists()
239 return wxFileName::FileExists( GetFullPath() );
242 bool wxFileName::FileExists( const wxString
&file
)
244 return ::wxFileExists( file
);
247 bool wxFileName::DirExists()
249 return wxFileName::DirExists( GetFullPath() );
252 bool wxFileName::DirExists( const wxString
&dir
)
254 return ::wxDirExists( dir
);
257 // ----------------------------------------------------------------------------
258 // CWD and HOME stuff
259 // ----------------------------------------------------------------------------
261 void wxFileName::AssignCwd()
263 AssignDir(wxFileName::GetCwd());
267 wxString
wxFileName::GetCwd()
272 bool wxFileName::SetCwd()
274 return wxFileName::SetCwd( GetFullPath() );
277 bool wxFileName::SetCwd( const wxString
&cwd
)
279 return ::wxSetWorkingDirectory( cwd
);
282 void wxFileName::AssignHomeDir()
284 AssignDir(wxFileName::GetHomeDir());
287 wxString
wxFileName::GetHomeDir()
289 return ::wxGetHomeDir();
292 void wxFileName::AssignTempFileName( const wxString
&prefix
)
295 if ( wxGetTempFileName(prefix
, fullname
) )
305 // ----------------------------------------------------------------------------
306 // directory operations
307 // ----------------------------------------------------------------------------
309 bool wxFileName::Mkdir( int perm
, bool full
)
311 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
314 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
318 wxFileName
filename(dir
);
319 wxArrayString dirs
= filename
.GetDirs();
320 dirs
.Add(filename
.GetName());
322 size_t count
= dirs
.GetCount();
326 for ( i
= 0; i
< count
; i
++ )
330 if (currPath
.Last() == wxT(':'))
332 // Can't create a root directory so continue to next dir
333 currPath
+= wxFILE_SEP_PATH
;
337 if (!DirExists(currPath
))
338 if (!wxMkdir(currPath
, perm
))
341 if ( (i
< (count
-1)) )
342 currPath
+= wxFILE_SEP_PATH
;
345 return (noErrors
== 0);
349 return ::wxMkdir( dir
, perm
);
352 bool wxFileName::Rmdir()
354 return wxFileName::Rmdir( GetFullPath() );
357 bool wxFileName::Rmdir( const wxString
&dir
)
359 return ::wxRmdir( dir
);
362 // ----------------------------------------------------------------------------
363 // path normalization
364 // ----------------------------------------------------------------------------
366 bool wxFileName::Normalize(wxPathNormalize flags
,
370 // the existing path components
371 wxArrayString dirs
= GetDirs();
373 // the path to prepend in front to make the path absolute
376 format
= GetFormat(format
);
378 // make the path absolute
379 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute() )
384 curDir
.AssignDir(cwd
);
387 // handle ~ stuff under Unix only
388 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
390 if ( !dirs
.IsEmpty() )
392 wxString dir
= dirs
[0u];
393 if ( !dir
.empty() && dir
[0u] == _T('~') )
395 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
404 wxArrayString dirsNew
= curDir
.GetDirs();
405 size_t count
= dirs
.GetCount();
406 for ( size_t n
= 0; n
< count
; n
++ )
408 dirsNew
.Add(dirs
[n
]);
414 // now deal with ".", ".." and the rest
416 size_t count
= dirs
.GetCount();
417 for ( size_t n
= 0; n
< count
; n
++ )
419 wxString dir
= dirs
[n
];
421 if ( flags
&& wxPATH_NORM_DOTS
)
423 if ( dir
== wxT(".") )
429 if ( dir
== wxT("..") )
431 if ( m_dirs
.IsEmpty() )
433 wxLogError(_("The path '%s' contains too many \"..\"!"),
434 GetFullPath().c_str());
438 m_dirs
.Remove(m_dirs
.GetCount() - 1);
443 if ( flags
& wxPATH_NORM_ENV_VARS
)
445 dir
= wxExpandEnvVars(dir
);
448 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
456 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
458 // VZ: expand env vars here too?
464 #if defined(__WXMSW__) && defined(__WIN32__)
465 if (flags
& wxPATH_NORM_LONG
)
467 Assign(GetLongPath());
474 // ----------------------------------------------------------------------------
475 // filename kind tests
476 // ----------------------------------------------------------------------------
478 bool wxFileName::SameAs( const wxFileName
&filepath
, wxPathFormat format
)
480 wxFileName fn1
= *this,
483 // get cwd only once - small time saving
484 wxString cwd
= wxGetCwd();
485 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
486 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
488 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
491 // TODO: compare inodes for Unix, this works even when filenames are
492 // different but files are the same (symlinks) (VZ)
498 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
500 // only DOS and OpenVMS filenames are case-sensitive
501 return ( GetFormat(format
) != wxPATH_DOS
&
502 GetFormat(format
) != wxPATH_VMS
);
505 bool wxFileName::IsRelative( wxPathFormat format
)
507 return !IsAbsolute(format
);
510 bool wxFileName::IsAbsolute( wxPathFormat format
)
512 wxChar ch
= m_dirs
.IsEmpty() ? _T('\0') : m_dirs
[0u][0u];
514 // Hack to cope with e.g. c:\thing - need something better
515 wxChar driveSep
= _T('\0');
516 if (!m_dirs
.IsEmpty() && m_dirs
[0].Length() > 1)
517 driveSep
= m_dirs
[0u][1u];
519 // the path is absolute if it starts with a path separator or, only for
520 // Unix filenames, with "~" or "~user"
521 return IsPathSeparator(ch
, format
) ||
522 driveSep
== _T(':') ||
523 (GetFormat(format
) == wxPATH_UNIX
&& ch
== _T('~') );
527 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
530 switch ( GetFormat(format
) )
533 // accept both as native APIs do
534 seps
<< wxFILE_SEP_PATH_UNIX
<< wxFILE_SEP_PATH_DOS
;
538 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
542 seps
= wxFILE_SEP_PATH_UNIX
;
546 seps
= wxFILE_SEP_PATH_MAC
;
550 seps
= wxFILE_SEP_PATH_VMS
;
558 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
560 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
563 bool wxFileName::IsWild( wxPathFormat format
)
565 // FIXME: this is probably false for Mac and this is surely wrong for most
566 // of Unix shells (think about "[...]")
568 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
571 // ----------------------------------------------------------------------------
572 // path components manipulation
573 // ----------------------------------------------------------------------------
575 void wxFileName::AppendDir( const wxString
&dir
)
580 void wxFileName::PrependDir( const wxString
&dir
)
582 m_dirs
.Insert( dir
, 0 );
585 void wxFileName::InsertDir( int before
, const wxString
&dir
)
587 m_dirs
.Insert( dir
, before
);
590 void wxFileName::RemoveDir( int pos
)
592 m_dirs
.Remove( (size_t)pos
);
595 // ----------------------------------------------------------------------------
597 // ----------------------------------------------------------------------------
599 void wxFileName::SetFullName(const wxString
& fullname
)
601 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
604 wxString
wxFileName::GetFullName() const
606 wxString fullname
= m_name
;
607 if ( !m_ext
.empty() )
609 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
615 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
617 format
= GetFormat( format
);
620 size_t count
= m_dirs
.GetCount();
621 for ( size_t i
= 0; i
< count
; i
++ )
624 if ( add_separator
|| (i
< count
) )
625 ret
+= wxFILE_SEP_PATH
;
631 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
633 format
= GetFormat( format
);
636 if (format
== wxPATH_DOS
)
638 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
645 if (format
== wxPATH_UNIX
)
647 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
654 if (format
== wxPATH_VMS
)
657 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
666 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
675 if (!m_ext
.IsEmpty())
684 // Return the short form of the path (returns identity on non-Windows platforms)
685 wxString
wxFileName::GetShortPath() const
687 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
688 wxString
path(GetFullPath());
690 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
694 ok
= ::GetShortPathName
697 pathOut
.GetWriteBuf(sz
),
700 pathOut
.UngetWriteBuf();
707 return GetFullPath();
711 // Return the long form of the path (returns identity on non-Windows platforms)
712 wxString
wxFileName::GetLongPath() const
714 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
715 wxString
path(GetFullPath());
717 bool success
= FALSE
;
719 // VZ: this code was disabled, why?
720 #if 0 // wxUSE_DYNLIB_CLASS
721 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
723 static bool s_triedToLoad
= FALSE
;
725 if ( !s_triedToLoad
)
727 s_triedToLoad
= TRUE
;
728 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
731 // may succeed or fail depending on the Windows version
732 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
734 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
736 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
739 wxDllLoader::UnloadLibrary(dllKernel
);
741 if ( s_pfnGetLongPathName
)
743 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
744 bool ok
= dwSize
> 0;
748 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
752 ok
= (*s_pfnGetLongPathName
)
755 pathOut
.GetWriteBuf(sz
),
758 pathOut
.UngetWriteBuf();
768 #endif // wxUSE_DYNLIB_CLASS
772 // The OS didn't support GetLongPathName, or some other error.
773 // We need to call FindFirstFile on each component in turn.
775 WIN32_FIND_DATA findFileData
;
777 pathOut
= wxEmptyString
;
779 wxArrayString dirs
= GetDirs();
780 dirs
.Add(GetFullName());
782 size_t count
= dirs
.GetCount();
786 for ( i
= 0; i
< count
; i
++ )
788 // We're using pathOut to collect the long-name path,
789 // but using a temporary for appending the last path component which may be short-name
790 tmpPath
= pathOut
+ dirs
[i
];
792 if (tmpPath
.Last() == wxT(':'))
794 // Can't pass a drive and root dir to FindFirstFile,
795 // so continue to next dir
796 tmpPath
+= wxFILE_SEP_PATH
;
801 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
802 if (hFind
== INVALID_HANDLE_VALUE
)
804 // Error: return immediately with the original path
809 pathOut
+= findFileData
.cFileName
;
810 if ( (i
< (count
-1)) )
811 pathOut
+= wxFILE_SEP_PATH
;
820 return GetFullPath();
824 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
826 if (format
== wxPATH_NATIVE
)
828 #if defined(__WXMSW__) || defined(__WXPM__)
830 #elif defined(__WXMAC__) && !defined(__DARWIN__)
835 format
= wxPATH_UNIX
;
841 // ----------------------------------------------------------------------------
842 // path splitting function
843 // ----------------------------------------------------------------------------
845 void wxFileName::SplitPath(const wxString
& fullpath
,
851 format
= GetFormat(format
);
853 // find the positions of the last dot and last path separator in the path
854 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
855 size_t posLastSlash
= fullpath
.find_last_of(GetPathSeparators(format
));
857 if ( (posLastDot
!= wxString::npos
) && (format
== wxPATH_UNIX
) )
859 if ( (posLastDot
== 0) ||
860 (fullpath
[posLastDot
- 1] == wxFILE_SEP_PATH_UNIX
) )
862 // under Unix, dot may be (and commonly is) the first character of
863 // the filename, don't treat the entire filename as extension in
865 posLastDot
= wxString::npos
;
869 if ( (posLastDot
!= wxString::npos
) && (format
== wxPATH_VMS
) )
871 if ( (posLastDot
== 0) ||
872 (fullpath
[posLastDot
- 1] == ']' ) )
874 // under OpenVMS, dot may be (and commonly is) the first character of
875 // the filename, don't treat the entire filename as extension in
877 posLastDot
= wxString::npos
;
881 // if we do have a dot and a slash, check that the dot is in the name part
882 if ( (posLastDot
!= wxString::npos
) &&
883 (posLastSlash
!= wxString::npos
) &&
884 (posLastDot
< posLastSlash
) )
886 // the dot is part of the path, not the start of the extension
887 posLastDot
= wxString::npos
;
890 // now fill in the variables provided by user
893 if ( posLastSlash
== wxString::npos
)
900 // take all until the separator
901 *pstrPath
= fullpath
.Left(posLastSlash
);
907 // take all characters starting from the one after the last slash and
908 // up to, but excluding, the last dot
909 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
911 if ( posLastDot
== wxString::npos
)
913 // take all until the end
914 count
= wxString::npos
;
916 else if ( posLastSlash
== wxString::npos
)
920 else // have both dot and slash
922 count
= posLastDot
- posLastSlash
- 1;
925 *pstrName
= fullpath
.Mid(nStart
, count
);
930 if ( posLastDot
== wxString::npos
)
937 // take everything after the dot
938 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
943 // ----------------------------------------------------------------------------
945 // ----------------------------------------------------------------------------
947 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
948 const wxDateTime
*dtAccess
,
949 const wxDateTime
*dtMod
)
951 #if defined(__UNIX_LIKE__)
952 if ( !dtAccess
&& !dtMod
)
954 // can't modify the creation time anyhow, don't try
958 // if dtAccess or dtMod is not specified, use the other one (which must be
959 // non NULL because of the test above) for both times
961 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
962 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
963 if ( utime(GetFullPath(), &utm
) == 0 )
967 #elif defined(__WIN32__)
968 wxFileHandle
fh(GetFullPath());
971 FILETIME ftAccess
, ftCreate
, ftWrite
;
974 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
976 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
978 ConvertWxToFileTime(&ftWrite
, *dtMod
);
980 if ( ::SetFileTime(fh
,
981 dtCreate
? &ftCreate
: NULL
,
982 dtAccess
? &ftAccess
: NULL
,
983 dtMod
? &ftWrite
: NULL
) )
988 #else // other platform
991 wxLogSysError(_("Failed to modify file times for '%s'"),
992 GetFullPath().c_str());
997 bool wxFileName::Touch()
999 #if defined(__UNIX_LIKE__)
1000 // under Unix touching file is simple: just pass NULL to utime()
1001 if ( utime(GetFullPath(), NULL
) == 0 )
1006 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1009 #else // other platform
1010 wxDateTime dtNow
= wxDateTime::Now();
1012 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1016 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1018 wxDateTime
*dtChange
) const
1020 #if defined(__UNIX_LIKE__)
1022 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1025 dtAccess
->Set(stBuf
.st_atime
);
1027 dtMod
->Set(stBuf
.st_mtime
);
1029 dtChange
->Set(stBuf
.st_ctime
);
1033 #elif defined(__WIN32__)
1034 wxFileHandle
fh(GetFullPath());
1037 FILETIME ftAccess
, ftCreate
, ftWrite
;
1039 if ( ::GetFileTime(fh
,
1040 dtMod
? &ftCreate
: NULL
,
1041 dtAccess
? &ftAccess
: NULL
,
1042 dtChange
? &ftWrite
: NULL
) )
1045 ConvertFileTimeToWx(dtMod
, ftCreate
);
1047 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1049 ConvertFileTimeToWx(dtChange
, ftWrite
);
1054 #else // other platform
1057 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1058 GetFullPath().c_str());