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 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
128 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
135 // ============================================================================
137 // ============================================================================
139 // ----------------------------------------------------------------------------
140 // wxFileName construction
141 // ----------------------------------------------------------------------------
143 void wxFileName::Assign( const wxFileName
&filepath
)
145 m_ext
= filepath
.GetExt();
146 m_name
= filepath
.GetName();
147 m_dirs
= filepath
.GetDirs();
150 void wxFileName::Assign( const wxString
& path
,
151 const wxString
& name
,
153 wxPathFormat format
)
155 wxStringTokenizer
tn(path
, GetPathSeparators(format
),
156 wxTOKEN_RET_EMPTY_ALL
);
159 while ( tn
.HasMoreTokens() )
161 wxString token
= tn
.GetNextToken();
163 // If the path starts with a slash (or two for a network path),
164 // we need the first dir entry to be an empty for later reassembly.
165 if ((i
< 2) || !token
.IsEmpty())
175 void wxFileName::Assign(const wxString
& fullpath
,
178 wxString path
, name
, ext
;
179 SplitPath(fullpath
, &path
, &name
, &ext
, format
);
181 Assign(path
, name
, ext
, format
);
184 void wxFileName::Assign(const wxString
& path
,
185 const wxString
& fullname
,
189 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
191 Assign(path
, name
, ext
, format
);
194 void wxFileName::Clear()
198 m_ext
= wxEmptyString
;
202 wxFileName
wxFileName::FileName(const wxString
& file
)
204 return wxFileName(file
);
208 wxFileName
wxFileName::DirName(const wxString
& dir
)
215 // ----------------------------------------------------------------------------
217 // ----------------------------------------------------------------------------
219 bool wxFileName::FileExists()
221 return wxFileName::FileExists( GetFullPath() );
224 bool wxFileName::FileExists( const wxString
&file
)
226 return ::wxFileExists( file
);
229 bool wxFileName::DirExists()
231 return wxFileName::DirExists( GetFullPath() );
234 bool wxFileName::DirExists( const wxString
&dir
)
236 return ::wxDirExists( dir
);
239 // ----------------------------------------------------------------------------
240 // CWD and HOME stuff
241 // ----------------------------------------------------------------------------
243 void wxFileName::AssignCwd()
245 AssignDir(wxFileName::GetCwd());
249 wxString
wxFileName::GetCwd()
254 bool wxFileName::SetCwd()
256 return wxFileName::SetCwd( GetFullPath() );
259 bool wxFileName::SetCwd( const wxString
&cwd
)
261 return ::wxSetWorkingDirectory( cwd
);
264 void wxFileName::AssignHomeDir()
266 AssignDir(wxFileName::GetHomeDir());
269 wxString
wxFileName::GetHomeDir()
271 return ::wxGetHomeDir();
274 void wxFileName::AssignTempFileName( const wxString
&prefix
)
277 if ( wxGetTempFileName(prefix
, fullname
) )
287 // ----------------------------------------------------------------------------
288 // directory operations
289 // ----------------------------------------------------------------------------
291 bool wxFileName::Mkdir( int perm
, bool full
)
293 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
296 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
300 wxFileName
filename(dir
);
301 wxArrayString dirs
= filename
.GetDirs();
302 dirs
.Add(filename
.GetName());
304 size_t count
= dirs
.GetCount();
308 for ( i
= 0; i
< count
; i
++ )
312 if (currPath
.Last() == wxT(':'))
314 // Can't create a root directory so continue to next dir
315 currPath
+= wxFILE_SEP_PATH
;
319 if (!DirExists(currPath
))
320 if (!wxMkdir(currPath
, perm
))
323 if ( (i
< (count
-1)) )
324 currPath
+= wxFILE_SEP_PATH
;
327 return (noErrors
== 0);
331 return ::wxMkdir( dir
, perm
);
334 bool wxFileName::Rmdir()
336 return wxFileName::Rmdir( GetFullPath() );
339 bool wxFileName::Rmdir( const wxString
&dir
)
341 return ::wxRmdir( dir
);
344 // ----------------------------------------------------------------------------
345 // path normalization
346 // ----------------------------------------------------------------------------
348 bool wxFileName::Normalize(wxPathNormalize flags
,
352 // the existing path components
353 wxArrayString dirs
= GetDirs();
355 // the path to prepend in front to make the path absolute
358 format
= GetFormat(format
);
360 // make the path absolute
361 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute() )
366 curDir
.AssignDir(cwd
);
369 // handle ~ stuff under Unix only
370 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
372 if ( !dirs
.IsEmpty() )
374 wxString dir
= dirs
[0u];
375 if ( !dir
.empty() && dir
[0u] == _T('~') )
377 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
386 wxArrayString dirsNew
= curDir
.GetDirs();
387 size_t count
= dirs
.GetCount();
388 for ( size_t n
= 0; n
< count
; n
++ )
390 dirsNew
.Add(dirs
[n
]);
396 // now deal with ".", ".." and the rest
398 size_t count
= dirs
.GetCount();
399 for ( size_t n
= 0; n
< count
; n
++ )
401 wxString dir
= dirs
[n
];
403 if ( flags
&& wxPATH_NORM_DOTS
)
405 if ( dir
== wxT(".") )
411 if ( dir
== wxT("..") )
413 if ( m_dirs
.IsEmpty() )
415 wxLogError(_("The path '%s' contains too many \"..\"!"),
416 GetFullPath().c_str());
420 m_dirs
.Remove(m_dirs
.GetCount() - 1);
425 if ( flags
& wxPATH_NORM_ENV_VARS
)
427 dir
= wxExpandEnvVars(dir
);
430 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
438 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
440 // VZ: expand env vars here too?
446 #if defined(__WXMSW__) && defined(__WIN32__)
447 if (flags
& wxPATH_NORM_LONG
)
449 Assign(GetLongPath());
456 // ----------------------------------------------------------------------------
457 // filename kind tests
458 // ----------------------------------------------------------------------------
460 bool wxFileName::SameAs( const wxFileName
&filepath
, wxPathFormat format
)
462 wxFileName fn1
= *this,
465 // get cwd only once - small time saving
466 wxString cwd
= wxGetCwd();
467 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
468 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
470 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
473 // TODO: compare inodes for Unix, this works even when filenames are
474 // different but files are the same (symlinks) (VZ)
480 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
482 // only DOS filenames are case-sensitive
483 return GetFormat(format
) != wxPATH_DOS
;
486 bool wxFileName::IsRelative( wxPathFormat format
)
488 return !IsAbsolute(format
);
491 bool wxFileName::IsAbsolute( wxPathFormat format
)
493 wxChar ch
= m_dirs
.IsEmpty() ? _T('\0') : m_dirs
[0u][0u];
495 // Hack to cope with e.g. c:\thing - need something better
496 wxChar driveSep
= _T('\0');
497 if (!m_dirs
.IsEmpty() && m_dirs
[0].Length() > 1)
498 driveSep
= m_dirs
[0u][1u];
500 // the path is absolute if it starts with a path separator or, only for
501 // Unix filenames, with "~" or "~user"
502 return IsPathSeparator(ch
, format
) ||
503 driveSep
== _T(':') ||
504 (GetFormat(format
) == wxPATH_UNIX
&& ch
== _T('~') );
508 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
511 switch ( GetFormat(format
) )
514 // accept both as native APIs do
515 seps
<< wxFILE_SEP_PATH_UNIX
<< wxFILE_SEP_PATH_DOS
;
519 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
523 seps
= wxFILE_SEP_PATH_UNIX
;
527 seps
= wxFILE_SEP_PATH_MAC
;
535 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
537 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
540 bool wxFileName::IsWild( wxPathFormat format
)
542 // FIXME: this is probably false for Mac and this is surely wrong for most
543 // of Unix shells (think about "[...]")
545 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
548 // ----------------------------------------------------------------------------
549 // path components manipulation
550 // ----------------------------------------------------------------------------
552 void wxFileName::AppendDir( const wxString
&dir
)
557 void wxFileName::PrependDir( const wxString
&dir
)
559 m_dirs
.Insert( dir
, 0 );
562 void wxFileName::InsertDir( int before
, const wxString
&dir
)
564 m_dirs
.Insert( dir
, before
);
567 void wxFileName::RemoveDir( int pos
)
569 m_dirs
.Remove( (size_t)pos
);
572 // ----------------------------------------------------------------------------
574 // ----------------------------------------------------------------------------
576 void wxFileName::SetFullName(const wxString
& fullname
)
578 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
581 wxString
wxFileName::GetFullName() const
583 wxString fullname
= m_name
;
584 if ( !m_ext
.empty() )
586 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
592 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
594 format
= GetFormat( format
);
597 size_t count
= m_dirs
.GetCount();
598 for ( size_t i
= 0; i
< count
; i
++ )
601 if ( add_separator
|| (i
< count
) )
602 ret
+= wxFILE_SEP_PATH
;
608 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
610 format
= GetFormat( format
);
613 if (format
== wxPATH_DOS
)
615 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
622 if (format
== wxPATH_UNIX
)
624 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
632 for (size_t i
= 0; i
< m_dirs
.GetCount(); i
++)
641 if (!m_ext
.IsEmpty())
650 // Return the short form of the path (returns identity on non-Windows platforms)
651 wxString
wxFileName::GetShortPath() const
653 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
654 wxString
path(GetFullPath());
656 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
660 ok
= ::GetShortPathName
663 pathOut
.GetWriteBuf(sz
),
666 pathOut
.UngetWriteBuf();
673 return GetFullPath();
677 // Return the long form of the path (returns identity on non-Windows platforms)
678 wxString
wxFileName::GetLongPath() const
680 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
681 wxString
path(GetFullPath());
683 bool success
= FALSE
;
685 // VZ: this code was disabled, why?
686 #if 0 // wxUSE_DYNLIB_CLASS
687 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
689 static bool s_triedToLoad
= FALSE
;
691 if ( !s_triedToLoad
)
693 s_triedToLoad
= TRUE
;
694 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
697 // may succeed or fail depending on the Windows version
698 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
700 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
702 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
705 wxDllLoader::UnloadLibrary(dllKernel
);
707 if ( s_pfnGetLongPathName
)
709 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
710 bool ok
= dwSize
> 0;
714 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
718 ok
= (*s_pfnGetLongPathName
)
721 pathOut
.GetWriteBuf(sz
),
724 pathOut
.UngetWriteBuf();
734 #endif // wxUSE_DYNLIB_CLASS
738 // The OS didn't support GetLongPathName, or some other error.
739 // We need to call FindFirstFile on each component in turn.
741 WIN32_FIND_DATA findFileData
;
743 pathOut
= wxEmptyString
;
745 wxArrayString dirs
= GetDirs();
746 dirs
.Add(GetFullName());
748 size_t count
= dirs
.GetCount();
752 for ( i
= 0; i
< count
; i
++ )
754 // We're using pathOut to collect the long-name path,
755 // but using a temporary for appending the last path component which may be short-name
756 tmpPath
= pathOut
+ dirs
[i
];
758 if (tmpPath
.Last() == wxT(':'))
760 // Can't pass a drive and root dir to FindFirstFile,
761 // so continue to next dir
762 tmpPath
+= wxFILE_SEP_PATH
;
767 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
768 if (hFind
== INVALID_HANDLE_VALUE
)
770 // Error: return immediately with the original path
775 pathOut
+= findFileData
.cFileName
;
776 if ( (i
< (count
-1)) )
777 pathOut
+= wxFILE_SEP_PATH
;
786 return GetFullPath();
790 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
792 if (format
== wxPATH_NATIVE
)
794 #if defined(__WXMSW__) || defined(__WXPM__)
796 #elif defined(__WXMAC__)
799 format
= wxPATH_UNIX
;
805 // ----------------------------------------------------------------------------
806 // path splitting function
807 // ----------------------------------------------------------------------------
809 void wxFileName::SplitPath(const wxString
& fullpath
,
815 format
= GetFormat(format
);
817 // find the positions of the last dot and last path separator in the path
818 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
819 size_t posLastSlash
= fullpath
.find_last_of(GetPathSeparators(format
));
821 if ( (posLastDot
!= wxString::npos
) && (format
== wxPATH_UNIX
) )
823 if ( (posLastDot
== 0) ||
824 (fullpath
[posLastDot
- 1] == wxFILE_SEP_PATH_UNIX
) )
826 // under Unix, dot may be (and commonly is) the first character of
827 // the filename, don't treat the entire filename as extension in
829 posLastDot
= wxString::npos
;
833 // if we do have a dot and a slash, check that the dot is in the name part
834 if ( (posLastDot
!= wxString::npos
) &&
835 (posLastSlash
!= wxString::npos
) &&
836 (posLastDot
< posLastSlash
) )
838 // the dot is part of the path, not the start of the extension
839 posLastDot
= wxString::npos
;
842 // now fill in the variables provided by user
845 if ( posLastSlash
== wxString::npos
)
852 // take all until the separator
853 *pstrPath
= fullpath
.Left(posLastSlash
);
859 // take all characters starting from the one after the last slash and
860 // up to, but excluding, the last dot
861 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
863 if ( posLastDot
== wxString::npos
)
865 // take all until the end
866 count
= wxString::npos
;
868 else if ( posLastSlash
== wxString::npos
)
872 else // have both dot and slash
874 count
= posLastDot
- posLastSlash
- 1;
877 *pstrName
= fullpath
.Mid(nStart
, count
);
882 if ( posLastDot
== wxString::npos
)
889 // take everything after the dot
890 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
895 // ----------------------------------------------------------------------------
897 // ----------------------------------------------------------------------------
899 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
900 const wxDateTime
*dtAccess
,
901 const wxDateTime
*dtMod
)
903 #if defined(__UNIX_LIKE__)
904 if ( !dtAccess
&& !dtMod
)
906 // can't modify the creation time anyhow, don't try
910 // if dtAccess or dtMod is not specified, use the other one (which must be
911 // non NULL because of the test above) for both times
913 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
914 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
915 if ( utime(GetFullPath(), &utm
) == 0 )
919 #elif defined(__WIN32__)
920 wxFileHandle
fh(GetFullPath());
923 FILETIME ftAccess
, ftCreate
, ftWrite
;
926 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
928 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
930 ConvertWxToFileTime(&ftWrite
, *dtMod
);
932 if ( ::SetFileTime(fh
,
933 dtCreate
? &ftCreate
: NULL
,
934 dtAccess
? &ftAccess
: NULL
,
935 dtMod
? &ftWrite
: NULL
) )
940 #else // other platform
943 wxLogSysError(_("Failed to modify file times for '%s'"),
944 GetFullPath().c_str());
949 bool wxFileName::Touch()
951 #if defined(__UNIX_LIKE__)
952 // under Unix touching file is simple: just pass NULL to utime()
953 if ( utime(GetFullPath(), NULL
) == 0 )
958 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
961 #else // other platform
962 wxDateTime dtNow
= wxDateTime::Now();
964 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
968 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
970 wxDateTime
*dtChange
) const
972 #if defined(__UNIX_LIKE__)
974 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
977 dtAccess
->Set(stBuf
.st_atime
);
979 dtMod
->Set(stBuf
.st_mtime
);
981 dtChange
->Set(stBuf
.st_ctime
);
985 #elif defined(__WIN32__)
986 wxFileHandle
fh(GetFullPath());
989 FILETIME ftAccess
, ftCreate
, ftWrite
;
991 if ( ::GetFileTime(fh
,
992 dtMod
? &ftCreate
: NULL
,
993 dtAccess
? &ftAccess
: NULL
,
994 dtChange
? &ftWrite
: NULL
) )
997 ConvertFileTimeToWx(dtMod
, ftCreate
);
999 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1001 ConvertFileTimeToWx(dtChange
, ftWrite
);
1006 #else // other platform
1009 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1010 GetFullPath().c_str());