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 filenames are case-sensitive
501 return GetFormat(format
) != wxPATH_DOS
;
504 bool wxFileName::IsRelative( wxPathFormat format
)
506 return !IsAbsolute(format
);
509 bool wxFileName::IsAbsolute( wxPathFormat format
)
511 wxChar ch
= m_dirs
.IsEmpty() ? _T('\0') : m_dirs
[0u][0u];
513 // Hack to cope with e.g. c:\thing - need something better
514 wxChar driveSep
= _T('\0');
515 if (!m_dirs
.IsEmpty() && m_dirs
[0].Length() > 1)
516 driveSep
= m_dirs
[0u][1u];
518 // the path is absolute if it starts with a path separator or, only for
519 // Unix filenames, with "~" or "~user"
520 return IsPathSeparator(ch
, format
) ||
521 driveSep
== _T(':') ||
522 (GetFormat(format
) == wxPATH_UNIX
&& ch
== _T('~') );
526 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
529 switch ( GetFormat(format
) )
532 // accept both as native APIs do
533 seps
<< wxFILE_SEP_PATH_UNIX
<< wxFILE_SEP_PATH_DOS
;
537 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
541 seps
= wxFILE_SEP_PATH_UNIX
;
545 seps
= wxFILE_SEP_PATH_MAC
;
553 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
555 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
558 bool wxFileName::IsWild( wxPathFormat format
)
560 // FIXME: this is probably false for Mac and this is surely wrong for most
561 // of Unix shells (think about "[...]")
563 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
566 // ----------------------------------------------------------------------------
567 // path components manipulation
568 // ----------------------------------------------------------------------------
570 void wxFileName::AppendDir( const wxString
&dir
)
575 void wxFileName::PrependDir( const wxString
&dir
)
577 m_dirs
.Insert( dir
, 0 );
580 void wxFileName::InsertDir( int before
, const wxString
&dir
)
582 m_dirs
.Insert( dir
, before
);
585 void wxFileName::RemoveDir( int pos
)
587 m_dirs
.Remove( (size_t)pos
);
590 // ----------------------------------------------------------------------------
592 // ----------------------------------------------------------------------------
594 void wxFileName::SetFullName(const wxString
& fullname
)
596 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
599 wxString
wxFileName::GetFullName() const
601 wxString fullname
= m_name
;
602 if ( !m_ext
.empty() )
604 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
610 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
612 format
= GetFormat( format
);
615 size_t count
= m_dirs
.GetCount();
616 for ( size_t i
= 0; i
< count
; i
++ )
619 if ( add_separator
|| (i
< count
) )
620 ret
+= wxFILE_SEP_PATH
;
626 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
628 format
= GetFormat( format
);
631 if (format
== wxPATH_DOS
)
633 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
640 if (format
== wxPATH_UNIX
)
642 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
650 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
659 if (!m_ext
.IsEmpty())
668 // Return the short form of the path (returns identity on non-Windows platforms)
669 wxString
wxFileName::GetShortPath() const
671 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
672 wxString
path(GetFullPath());
674 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
678 ok
= ::GetShortPathName
681 pathOut
.GetWriteBuf(sz
),
684 pathOut
.UngetWriteBuf();
691 return GetFullPath();
695 // Return the long form of the path (returns identity on non-Windows platforms)
696 wxString
wxFileName::GetLongPath() const
698 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
699 wxString
path(GetFullPath());
701 bool success
= FALSE
;
703 // VZ: this code was disabled, why?
704 #if 0 // wxUSE_DYNLIB_CLASS
705 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
707 static bool s_triedToLoad
= FALSE
;
709 if ( !s_triedToLoad
)
711 s_triedToLoad
= TRUE
;
712 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
715 // may succeed or fail depending on the Windows version
716 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
718 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
720 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
723 wxDllLoader::UnloadLibrary(dllKernel
);
725 if ( s_pfnGetLongPathName
)
727 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
728 bool ok
= dwSize
> 0;
732 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
736 ok
= (*s_pfnGetLongPathName
)
739 pathOut
.GetWriteBuf(sz
),
742 pathOut
.UngetWriteBuf();
752 #endif // wxUSE_DYNLIB_CLASS
756 // The OS didn't support GetLongPathName, or some other error.
757 // We need to call FindFirstFile on each component in turn.
759 WIN32_FIND_DATA findFileData
;
761 pathOut
= wxEmptyString
;
763 wxArrayString dirs
= GetDirs();
764 dirs
.Add(GetFullName());
766 size_t count
= dirs
.GetCount();
770 for ( i
= 0; i
< count
; i
++ )
772 // We're using pathOut to collect the long-name path,
773 // but using a temporary for appending the last path component which may be short-name
774 tmpPath
= pathOut
+ dirs
[i
];
776 if (tmpPath
.Last() == wxT(':'))
778 // Can't pass a drive and root dir to FindFirstFile,
779 // so continue to next dir
780 tmpPath
+= wxFILE_SEP_PATH
;
785 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
786 if (hFind
== INVALID_HANDLE_VALUE
)
788 // Error: return immediately with the original path
793 pathOut
+= findFileData
.cFileName
;
794 if ( (i
< (count
-1)) )
795 pathOut
+= wxFILE_SEP_PATH
;
804 return GetFullPath();
808 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
810 if (format
== wxPATH_NATIVE
)
812 #if defined(__WXMSW__) || defined(__WXPM__)
814 #elif defined(__WXMAC__) && !defined(__DARWIN__)
817 format
= wxPATH_UNIX
;
823 // ----------------------------------------------------------------------------
824 // path splitting function
825 // ----------------------------------------------------------------------------
827 void wxFileName::SplitPath(const wxString
& fullpath
,
833 format
= GetFormat(format
);
835 // find the positions of the last dot and last path separator in the path
836 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
837 size_t posLastSlash
= fullpath
.find_last_of(GetPathSeparators(format
));
839 if ( (posLastDot
!= wxString::npos
) && (format
== wxPATH_UNIX
) )
841 if ( (posLastDot
== 0) ||
842 (fullpath
[posLastDot
- 1] == wxFILE_SEP_PATH_UNIX
) )
844 // under Unix, dot may be (and commonly is) the first character of
845 // the filename, don't treat the entire filename as extension in
847 posLastDot
= wxString::npos
;
851 // if we do have a dot and a slash, check that the dot is in the name part
852 if ( (posLastDot
!= wxString::npos
) &&
853 (posLastSlash
!= wxString::npos
) &&
854 (posLastDot
< posLastSlash
) )
856 // the dot is part of the path, not the start of the extension
857 posLastDot
= wxString::npos
;
860 // now fill in the variables provided by user
863 if ( posLastSlash
== wxString::npos
)
870 // take all until the separator
871 *pstrPath
= fullpath
.Left(posLastSlash
);
877 // take all characters starting from the one after the last slash and
878 // up to, but excluding, the last dot
879 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
881 if ( posLastDot
== wxString::npos
)
883 // take all until the end
884 count
= wxString::npos
;
886 else if ( posLastSlash
== wxString::npos
)
890 else // have both dot and slash
892 count
= posLastDot
- posLastSlash
- 1;
895 *pstrName
= fullpath
.Mid(nStart
, count
);
900 if ( posLastDot
== wxString::npos
)
907 // take everything after the dot
908 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
913 // ----------------------------------------------------------------------------
915 // ----------------------------------------------------------------------------
917 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
918 const wxDateTime
*dtAccess
,
919 const wxDateTime
*dtMod
)
921 #if defined(__UNIX_LIKE__)
922 if ( !dtAccess
&& !dtMod
)
924 // can't modify the creation time anyhow, don't try
928 // if dtAccess or dtMod is not specified, use the other one (which must be
929 // non NULL because of the test above) for both times
931 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
932 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
933 if ( utime(GetFullPath(), &utm
) == 0 )
937 #elif defined(__WIN32__)
938 wxFileHandle
fh(GetFullPath());
941 FILETIME ftAccess
, ftCreate
, ftWrite
;
944 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
946 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
948 ConvertWxToFileTime(&ftWrite
, *dtMod
);
950 if ( ::SetFileTime(fh
,
951 dtCreate
? &ftCreate
: NULL
,
952 dtAccess
? &ftAccess
: NULL
,
953 dtMod
? &ftWrite
: NULL
) )
958 #else // other platform
961 wxLogSysError(_("Failed to modify file times for '%s'"),
962 GetFullPath().c_str());
967 bool wxFileName::Touch()
969 #if defined(__UNIX_LIKE__)
970 // under Unix touching file is simple: just pass NULL to utime()
971 if ( utime(GetFullPath(), NULL
) == 0 )
976 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
979 #else // other platform
980 wxDateTime dtNow
= wxDateTime::Now();
982 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
986 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
988 wxDateTime
*dtChange
) const
990 #if defined(__UNIX_LIKE__)
992 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
995 dtAccess
->Set(stBuf
.st_atime
);
997 dtMod
->Set(stBuf
.st_mtime
);
999 dtChange
->Set(stBuf
.st_ctime
);
1003 #elif defined(__WIN32__)
1004 wxFileHandle
fh(GetFullPath());
1007 FILETIME ftAccess
, ftCreate
, ftWrite
;
1009 if ( ::GetFileTime(fh
,
1010 dtMod
? &ftCreate
: NULL
,
1011 dtAccess
? &ftAccess
: NULL
,
1012 dtChange
? &ftWrite
: NULL
) )
1015 ConvertFileTimeToWx(dtMod
, ftCreate
);
1017 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1019 ConvertFileTimeToWx(dtChange
, ftWrite
);
1024 #else // other platform
1027 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1028 GetFullPath().c_str());