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
48 #include "wx/msw/winundef.h"
51 // ============================================================================
53 // ============================================================================
55 // ----------------------------------------------------------------------------
56 // wxFileName construction
57 // ----------------------------------------------------------------------------
59 void wxFileName::Assign( const wxFileName
&filepath
)
61 m_ext
= filepath
.GetExt();
62 m_name
= filepath
.GetName();
63 m_dirs
= filepath
.GetDirs();
66 void wxFileName::Assign( const wxString
& path
,
71 wxStringTokenizer
tn(path
, GetPathSeparators(format
),
72 wxTOKEN_RET_EMPTY_ALL
);
75 while ( tn
.HasMoreTokens() )
77 wxString token
= tn
.GetNextToken();
79 // If the path starts with a slash, we need the first
80 // dir entry to be an empty for later reassembly.
81 if (first
|| !token
.IsEmpty())
91 void wxFileName::Assign(const wxString
& fullpath
,
94 wxString path
, name
, ext
;
95 SplitPath(fullpath
, &path
, &name
, &ext
, format
);
97 Assign(path
, name
, ext
, format
);
100 void wxFileName::Assign(const wxString
& path
,
101 const wxString
& fullname
,
105 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
107 Assign(path
, name
, ext
, format
);
110 void wxFileName::Clear()
114 m_ext
= wxEmptyString
;
118 wxFileName
wxFileName::FileName(const wxString
& file
)
120 return wxFileName(file
);
124 wxFileName
wxFileName::DirName(const wxString
& dir
)
131 // ----------------------------------------------------------------------------
133 // ----------------------------------------------------------------------------
135 bool wxFileName::FileExists()
137 return wxFileName::FileExists( GetFullPath() );
140 bool wxFileName::FileExists( const wxString
&file
)
142 return ::wxFileExists( file
);
145 bool wxFileName::DirExists()
147 return wxFileName::DirExists( GetFullPath() );
150 bool wxFileName::DirExists( const wxString
&dir
)
152 return ::wxDirExists( dir
);
155 // ----------------------------------------------------------------------------
156 // CWD and HOME stuff
157 // ----------------------------------------------------------------------------
159 void wxFileName::AssignCwd()
161 AssignDir(wxFileName::GetCwd());
165 wxString
wxFileName::GetCwd()
170 bool wxFileName::SetCwd()
172 return wxFileName::SetCwd( GetFullPath() );
175 bool wxFileName::SetCwd( const wxString
&cwd
)
177 return ::wxSetWorkingDirectory( cwd
);
180 void wxFileName::AssignHomeDir()
182 AssignDir(wxFileName::GetHomeDir());
185 wxString
wxFileName::GetHomeDir()
187 return ::wxGetHomeDir();
190 void wxFileName::AssignTempFileName( const wxString
&prefix
)
193 if ( wxGetTempFileName(prefix
, fullname
) )
203 // ----------------------------------------------------------------------------
204 // directory operations
205 // ----------------------------------------------------------------------------
207 bool wxFileName::Mkdir( int perm
)
209 return wxFileName::Mkdir( GetFullPath(), perm
);
212 bool wxFileName::Mkdir( const wxString
&dir
, int perm
)
214 return ::wxMkdir( dir
, perm
);
217 bool wxFileName::Rmdir()
219 return wxFileName::Rmdir( GetFullPath() );
222 bool wxFileName::Rmdir( const wxString
&dir
)
224 return ::wxRmdir( dir
);
227 // ----------------------------------------------------------------------------
228 // path normalization
229 // ----------------------------------------------------------------------------
231 bool wxFileName::Normalize(wxPathNormalize flags
,
235 // the existing path components
236 wxArrayString dirs
= GetDirs();
238 // the path to prepend in front to make the path absolute
241 format
= GetFormat(format
);
243 // make the path absolute
244 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute() )
249 curDir
.AssignDir(cwd
);
252 // handle ~ stuff under Unix only
253 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
255 if ( !dirs
.IsEmpty() )
257 wxString dir
= dirs
[0u];
258 if ( !dir
.empty() && dir
[0u] == _T('~') )
260 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
269 wxArrayString dirsNew
= curDir
.GetDirs();
270 size_t count
= dirs
.GetCount();
271 for ( size_t n
= 0; n
< count
; n
++ )
273 dirsNew
.Add(dirs
[n
]);
279 // now deal with ".", ".." and the rest
281 size_t count
= dirs
.GetCount();
282 for ( size_t n
= 0; n
< count
; n
++ )
284 wxString dir
= dirs
[n
];
286 if ( flags
&& wxPATH_NORM_DOTS
)
288 if ( dir
== wxT(".") )
294 if ( dir
== wxT("..") )
296 if ( m_dirs
.IsEmpty() )
298 wxLogError(_("The path '%s' contains too many \"..\"!"),
299 GetFullPath().c_str());
303 m_dirs
.Remove(m_dirs
.GetCount() - 1);
308 if ( flags
& wxPATH_NORM_ENV_VARS
)
310 dir
= wxExpandEnvVars(dir
);
313 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
321 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
323 // VZ: expand env vars here too?
329 #if defined(__WXMSW__) && defined(__WIN32__)
330 if (flags
& wxPATH_NORM_LONG
)
332 Assign(GetLongPath());
339 // ----------------------------------------------------------------------------
340 // filename kind tests
341 // ----------------------------------------------------------------------------
343 bool wxFileName::SameAs( const wxFileName
&filepath
, wxPathFormat format
)
345 wxFileName fn1
= *this,
348 // get cwd only once - small time saving
349 wxString cwd
= wxGetCwd();
350 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
351 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
353 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
356 // TODO: compare inodes for Unix, this works even when filenames are
357 // different but files are the same (symlinks) (VZ)
363 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
365 // only DOS filenames are case-sensitive
366 return GetFormat(format
) != wxPATH_DOS
;
369 bool wxFileName::IsRelative( wxPathFormat format
)
371 return !IsAbsolute(format
);
374 bool wxFileName::IsAbsolute( wxPathFormat format
)
376 wxChar ch
= m_dirs
.IsEmpty() ? _T('\0') : m_dirs
[0u][0u];
378 // Hack to cope with e.g. c:\thing - need something better
379 wxChar driveSep
= _T('\0');
380 if (!m_dirs
.IsEmpty() && m_dirs
[0].Length() > 1)
381 driveSep
= m_dirs
[0u][1u];
383 // the path is absolute if it starts with a path separator or, only for
384 // Unix filenames, with "~" or "~user"
385 return IsPathSeparator(ch
, format
) ||
386 driveSep
== _T(':') ||
387 (GetFormat(format
) == wxPATH_UNIX
&& ch
== _T('~') );
391 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
394 switch ( GetFormat(format
) )
397 // accept both as native APIs do
398 seps
<< wxFILE_SEP_PATH_UNIX
<< wxFILE_SEP_PATH_DOS
;
402 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
406 seps
= wxFILE_SEP_PATH_UNIX
;
410 seps
= wxFILE_SEP_PATH_MAC
;
418 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
420 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
423 bool wxFileName::IsWild( wxPathFormat format
)
425 // FIXME: this is probably false for Mac and this is surely wrong for most
426 // of Unix shells (think about "[...]")
427 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
430 // ----------------------------------------------------------------------------
431 // path components manipulation
432 // ----------------------------------------------------------------------------
434 void wxFileName::AppendDir( const wxString
&dir
)
439 void wxFileName::PrependDir( const wxString
&dir
)
441 m_dirs
.Insert( dir
, 0 );
444 void wxFileName::InsertDir( int before
, const wxString
&dir
)
446 m_dirs
.Insert( dir
, before
);
449 void wxFileName::RemoveDir( int pos
)
451 m_dirs
.Remove( (size_t)pos
);
454 // ----------------------------------------------------------------------------
456 // ----------------------------------------------------------------------------
458 void wxFileName::SetFullName(const wxString
& fullname
)
460 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
463 wxString
wxFileName::GetFullName() const
465 wxString fullname
= m_name
;
466 if ( !m_ext
.empty() )
468 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
474 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
476 format
= GetFormat( format
);
479 size_t count
= m_dirs
.GetCount();
480 for ( size_t i
= 0; i
< count
; i
++ )
483 if ( add_separator
|| (i
< count
) )
484 ret
+= wxFILE_SEP_PATH
;
490 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
492 return GetPathWithSep() + GetFullName();
495 // Return the short form of the path (returns identity on non-Windows platforms)
496 wxString
wxFileName::GetShortPath() const
498 #if defined(__WXMSW__) && defined(__WIN32__)
499 wxString
path(GetFullPath());
501 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
505 ok
= ::GetShortPathName
508 pathOut
.GetWriteBuf(sz
),
511 pathOut
.UngetWriteBuf();
518 return GetFullPath();
522 // Return the long form of the path (returns identity on non-Windows platforms)
523 wxString
wxFileName::GetLongPath() const
525 #if defined(__WXMSW__) && defined(__WIN32__)
526 wxString
path(GetFullPath());
528 bool success
= FALSE
;
530 #if wxUSE_DYNLIB_CLASS
531 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
533 static bool s_triedToLoad
= FALSE
;
534 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
536 if ( !s_triedToLoad
)
538 s_triedToLoad
= TRUE
;
540 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
541 if ( 0 ) // dllKernel )
543 // may succeed or fail depending on the Windows version
545 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
547 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
550 wxDllLoader::UnloadLibrary(dllKernel
);
552 if ( s_pfnGetLongPathName
)
554 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
555 bool ok
= dwSize
> 0;
559 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
563 ok
= (*s_pfnGetLongPathName
)
566 pathOut
.GetWriteBuf(sz
),
569 pathOut
.UngetWriteBuf();
580 // wxUSE_DYNLIB_CLASS
584 // The OS didn't support GetLongPathName, or some other error.
585 // We need to call FindFirstFile on each component in turn.
587 WIN32_FIND_DATA findFileData
;
589 pathOut
= wxEmptyString
;
591 size_t count
= m_dirs
.GetCount();
595 for ( i
= 0; i
< count
; i
++ )
597 // We're using pathOut to collect the long-name path,
598 // but using a temporary for appending the last path component which may be short-name
599 tmpPath
= pathOut
+ m_dirs
[i
];
601 if (tmpPath
.Last() == wxT(':'))
603 // Can't pass a drive and root dir to FindFirstFile,
604 // so continue to next dir
605 tmpPath
+= wxFILE_SEP_PATH
;
610 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
611 if (hFind
== INVALID_HANDLE_VALUE
)
613 // Error: return immediately with the original path
618 pathOut
+= findFileData
.cFileName
;
619 if ( (i
< (count
-1)) )
620 pathOut
+= wxFILE_SEP_PATH
;
628 return GetFullPath();
632 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
634 if (format
== wxPATH_NATIVE
)
636 #if defined(__WXMSW__) || defined(__WXPM__)
638 #elif defined(__WXMAC__)
639 format
= wxPATH_UNIX
; // that's the way the rest of wx' code works right now
641 format
= wxPATH_UNIX
;
647 // ----------------------------------------------------------------------------
648 // path splitting function
649 // ----------------------------------------------------------------------------
651 void wxFileName::SplitPath(const wxString
& fullpath
,
657 format
= GetFormat(format
);
659 // find the positions of the last dot and last path separator in the path
660 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
661 size_t posLastSlash
= fullpath
.find_last_of(GetPathSeparators(format
));
663 if ( (posLastDot
!= wxString::npos
) && (format
== wxPATH_UNIX
) )
665 if ( (posLastDot
== 0) ||
666 (fullpath
[posLastDot
- 1] == wxFILE_SEP_PATH_UNIX
) )
668 // under Unix, dot may be (and commonly is) the first character of
669 // the filename, don't treat the entire filename as extension in
671 posLastDot
= wxString::npos
;
675 // if we do have a dot and a slash, check that the dot is in the name part
676 if ( (posLastDot
!= wxString::npos
) &&
677 (posLastSlash
!= wxString::npos
) &&
678 (posLastDot
< posLastSlash
) )
680 // the dot is part of the path, not the start of the extension
681 posLastDot
= wxString::npos
;
684 // now fill in the variables provided by user
687 if ( posLastSlash
== wxString::npos
)
694 // take all until the separator
695 *pstrPath
= fullpath
.Left(posLastSlash
);
701 // take all characters starting from the one after the last slash and
702 // up to, but excluding, the last dot
703 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
705 if ( posLastDot
== wxString::npos
)
707 // take all until the end
708 count
= wxString::npos
;
710 else if ( posLastSlash
== wxString::npos
)
714 else // have both dot and slash
716 count
= posLastDot
- posLastSlash
- 1;
719 *pstrName
= fullpath
.Mid(nStart
, count
);
724 if ( posLastDot
== wxString::npos
)
731 // take everything after the dot
732 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);