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 :::filename.ext is not yet supported. TODO.
36 Since the volume is just part of the file path, it is not
37 treated like a separate entity as it is done under DOS.
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"
79 #include "wx/filename.h"
80 #include "wx/tokenzr.h"
81 #include "wx/config.h" // for wxExpandEnvVars
84 #if wxUSE_DYNLIB_CLASS
85 #include "wx/dynlib.h"
88 // For GetShort/LongPathName
92 #include "wx/msw/winundef.h"
95 // utime() is POSIX so should normally be available on all Unices
97 #include <sys/types.h>
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 // small helper class which opens and closes the file - we use it just to get
114 // a file handle for the given file name to pass it to some Win32 API function
115 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
120 wxFileHandle(const wxString
& filename
)
122 m_hFile
= ::CreateFile
125 GENERIC_READ
, // access mask
127 NULL
, // no secutity attr
128 OPEN_EXISTING
, // creation disposition
130 NULL
// no template file
133 if ( m_hFile
== INVALID_HANDLE_VALUE
)
135 wxLogSysError(_("Failed to open '%s' for reading"),
142 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
144 if ( !::CloseHandle(m_hFile
) )
146 wxLogSysError(_("Failed to close file handle"));
151 // return TRUE only if the file could be opened successfully
152 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
155 operator HANDLE() const { return m_hFile
; }
163 // ----------------------------------------------------------------------------
165 // ----------------------------------------------------------------------------
167 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
169 // convert between wxDateTime and FILETIME which is a 64-bit value representing
170 // the number of 100-nanosecond intervals since January 1, 1601.
172 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
173 // FILETIME reference point (January 1, 1601)
174 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
176 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
178 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
180 // convert 100ns to ms
183 // move it to our Epoch
184 ll
-= FILETIME_EPOCH_OFFSET
;
186 *dt
= wxDateTime(ll
);
189 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
191 // do the reverse of ConvertFileTimeToWx()
192 wxLongLong ll
= dt
.GetValue();
194 ll
+= FILETIME_EPOCH_OFFSET
;
196 ft
->dwHighDateTime
= ll
.GetHi();
197 ft
->dwLowDateTime
= ll
.GetLo();
202 // ============================================================================
204 // ============================================================================
206 // ----------------------------------------------------------------------------
207 // wxFileName construction
208 // ----------------------------------------------------------------------------
210 void wxFileName::Assign( const wxFileName
&filepath
)
212 m_volume
= filepath
.GetVolume();
213 m_dirs
= filepath
.GetDirs();
214 m_name
= filepath
.GetName();
215 m_ext
= filepath
.GetExt();
218 void wxFileName::Assign(const wxString
& volume
,
219 const wxString
& path
,
220 const wxString
& name
,
222 wxPathFormat format
)
224 wxStringTokenizer
tn(path
, GetPathSeparators(format
));
227 while ( tn
.HasMoreTokens() )
229 wxString token
= tn
.GetNextToken();
231 // if the path starts with a slash, we do need the first empty dir
232 // entry to be able to tell later that it was an absolute path, but
233 // otherwise ignore the double slashes
234 if ( m_dirs
.IsEmpty() || !token
.IsEmpty() )
243 void wxFileName::Assign(const wxString
& fullpath
,
246 wxString volume
, path
, name
, ext
;
247 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
249 Assign(volume
, path
, name
, ext
, format
);
252 void wxFileName::Assign(const wxString
& fullpathOrig
,
253 const wxString
& fullname
,
256 // always recognize fullpath as directory, even if it doesn't end with a
258 wxString fullpath
= fullpathOrig
;
259 if ( !wxEndsWithPathSeparator(fullpath
) )
261 fullpath
+= GetPathSeparators(format
)[0u];
264 wxString volume
, path
, name
, ext
;
266 // do some consistency checks in debug mode: the name should be really just
267 // the filename and the path should be realyl just a path
269 wxString pathDummy
, nameDummy
, extDummy
;
271 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
273 wxASSERT_MSG( pathDummy
.empty(),
274 _T("the file name shouldn't contain the path") );
276 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
278 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
279 _T("the path shouldn't contain file name nor extension") );
281 #else // !__WXDEBUG__
282 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
283 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
284 #endif // __WXDEBUG__/!__WXDEBUG__
286 Assign(volume
, path
, name
, ext
, format
);
289 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
291 Assign(dir
, _T(""), format
);
294 void wxFileName::Clear()
300 m_ext
= wxEmptyString
;
304 wxFileName
wxFileName::FileName(const wxString
& file
)
306 return wxFileName(file
);
310 wxFileName
wxFileName::DirName(const wxString
& dir
)
317 // ----------------------------------------------------------------------------
319 // ----------------------------------------------------------------------------
321 bool wxFileName::FileExists()
323 return wxFileName::FileExists( GetFullPath() );
326 bool wxFileName::FileExists( const wxString
&file
)
328 return ::wxFileExists( file
);
331 bool wxFileName::DirExists()
333 return wxFileName::DirExists( GetFullPath() );
336 bool wxFileName::DirExists( const wxString
&dir
)
338 return ::wxDirExists( dir
);
341 // ----------------------------------------------------------------------------
342 // CWD and HOME stuff
343 // ----------------------------------------------------------------------------
345 void wxFileName::AssignCwd(const wxString
& volume
)
347 AssignDir(wxFileName::GetCwd(volume
));
351 wxString
wxFileName::GetCwd(const wxString
& volume
)
353 // if we have the volume, we must get the current directory on this drive
354 // and to do this we have to chdir to this volume - at least under Windows,
355 // I don't know how to get the current drive on another volume elsewhere
358 if ( !volume
.empty() )
361 SetCwd(volume
+ GetVolumeSeparator());
364 wxString cwd
= ::wxGetCwd();
366 if ( !volume
.empty() )
374 bool wxFileName::SetCwd()
376 return wxFileName::SetCwd( GetFullPath() );
379 bool wxFileName::SetCwd( const wxString
&cwd
)
381 return ::wxSetWorkingDirectory( cwd
);
384 void wxFileName::AssignHomeDir()
386 AssignDir(wxFileName::GetHomeDir());
389 wxString
wxFileName::GetHomeDir()
391 return ::wxGetHomeDir();
394 void wxFileName::AssignTempFileName( const wxString
& prefix
)
396 wxString tempname
= CreateTempFileName(prefix
);
397 if ( tempname
.empty() )
399 // error, failed to get temp file name
409 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
411 wxString path
, dir
, name
;
413 // use the directory specified by the prefix
414 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
416 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
421 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
423 wxLogLastError(_T("GetTempPath"));
428 // GetTempFileName() fails if we pass it an empty string
433 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
435 wxLogLastError(_T("GetTempFileName"));
440 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
446 #elif defined(__WXPM__)
447 // for now just create a file
449 // future enhancements can be to set some extended attributes for file
450 // systems OS/2 supports that have them (HPFS, FAT32) and security
452 static const wxChar
*szMktempSuffix
= wxT("XXX");
453 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
455 // Temporarily remove - MN
457 ::DosCreateDir(wxStringBuffer(MAX_PATH
), NULL
);
460 #else // !Windows, !OS/2
463 dir
= wxGetenv(_T("TMP"));
466 dir
= wxGetenv(_T("TEMP"));
478 if ( !wxEndsWithPathSeparator(dir
) &&
479 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
487 // scratch space for mkstemp()
488 path
+= _T("XXXXXX");
490 // can use the cast here because the length doesn't change and the string
492 if ( mkstemp((char *)path
.mb_str()) == -1 )
494 // this might be not necessary as mkstemp() on most systems should have
495 // already done it but it doesn't hurt neither...
498 //else: file already created
499 #else // !HAVE_MKSTEMP
503 path
+= _T("XXXXXX");
505 if ( !mktemp((char *)path
.mb_str()) )
509 #else // !HAVE_MKTEMP
510 // generate the unique file name ourselves
511 path
<< (unsigned int)getpid();
515 static const size_t numTries
= 1000;
516 for ( size_t n
= 0; n
< numTries
; n
++ )
518 // 3 hex digits is enough for numTries == 1000 < 4096
519 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
520 if ( !wxFile::Exists(pathTry
) )
529 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
533 // create the file - of course, there is a race condition here, this is
534 // why we always prefer using mkstemp()...
536 if ( !file
.Open(path
, wxFile::write_excl
, wxS_IRUSR
| wxS_IWUSR
) )
538 // FIXME: If !ok here should we loop and try again with another
539 // file name? That is the standard recourse if open(O_EXCL)
540 // fails, though of course it should be protected against
541 // possible infinite looping too.
543 wxLogError(_("Failed to open temporary file."));
548 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
550 #endif // Windows/!Windows
554 wxLogSysError(_("Failed to create a temporary file name"));
560 // ----------------------------------------------------------------------------
561 // directory operations
562 // ----------------------------------------------------------------------------
564 bool wxFileName::Mkdir( int perm
, bool full
)
566 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
569 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
573 wxFileName
filename(dir
);
574 wxArrayString dirs
= filename
.GetDirs();
575 dirs
.Add(filename
.GetName());
577 size_t count
= dirs
.GetCount();
581 for ( i
= 0; i
< count
; i
++ )
585 if (currPath
.Last() == wxT(':'))
587 // Can't create a root directory so continue to next dir
588 currPath
+= wxFILE_SEP_PATH
;
592 if (!DirExists(currPath
))
593 if (!wxMkdir(currPath
, perm
))
596 if ( (i
< (count
-1)) )
597 currPath
+= wxFILE_SEP_PATH
;
600 return (noErrors
== 0);
604 return ::wxMkdir( dir
, perm
);
607 bool wxFileName::Rmdir()
609 return wxFileName::Rmdir( GetFullPath() );
612 bool wxFileName::Rmdir( const wxString
&dir
)
614 return ::wxRmdir( dir
);
617 // ----------------------------------------------------------------------------
618 // path normalization
619 // ----------------------------------------------------------------------------
621 bool wxFileName::Normalize(wxPathNormalize flags
,
625 // the existing path components
626 wxArrayString dirs
= GetDirs();
628 // the path to prepend in front to make the path absolute
631 format
= GetFormat(format
);
633 // make the path absolute
634 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute() )
638 curDir
.AssignCwd(GetVolume());
642 curDir
.AssignDir(cwd
);
645 // the path may be not absolute because it doesn't have the volume name
646 // but in this case we shouldn't modify the directory components of it
647 // but just set the current volume
648 if ( !HasVolume() && curDir
.HasVolume() )
650 SetVolume(curDir
.GetVolume());
654 // yes, it was the case - we don't need curDir then
660 // handle ~ stuff under Unix only
661 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
663 if ( !dirs
.IsEmpty() )
665 wxString dir
= dirs
[0u];
666 if ( !dir
.empty() && dir
[0u] == _T('~') )
668 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
675 // transform relative path into abs one
678 wxArrayString dirsNew
= curDir
.GetDirs();
679 size_t count
= dirs
.GetCount();
680 for ( size_t n
= 0; n
< count
; n
++ )
682 dirsNew
.Add(dirs
[n
]);
688 // now deal with ".", ".." and the rest
690 size_t count
= dirs
.GetCount();
691 for ( size_t n
= 0; n
< count
; n
++ )
693 wxString dir
= dirs
[n
];
695 if ( flags
& wxPATH_NORM_DOTS
)
697 if ( dir
== wxT(".") )
703 if ( dir
== wxT("..") )
705 if ( m_dirs
.IsEmpty() )
707 wxLogError(_("The path '%s' contains too many \"..\"!"),
708 GetFullPath().c_str());
712 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
717 if ( flags
& wxPATH_NORM_ENV_VARS
)
719 dir
= wxExpandEnvVars(dir
);
722 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
730 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
732 // VZ: expand env vars here too?
738 #if defined(__WIN32__)
739 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
741 Assign(GetLongPath());
748 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
750 wxFileName
fnBase(pathBase
, format
);
752 // get cwd only once - small time saving
753 wxString cwd
= wxGetCwd();
754 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
755 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
757 bool withCase
= IsCaseSensitive(format
);
759 // we can't do anything if the files live on different volumes
760 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
766 // same drive, so we don't need our volume
769 // remove common directories starting at the top
770 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
771 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
774 fnBase
.m_dirs
.RemoveAt(0);
777 // add as many ".." as needed
778 size_t count
= fnBase
.m_dirs
.GetCount();
779 for ( size_t i
= 0; i
< count
; i
++ )
781 m_dirs
.Insert(wxT(".."), 0u);
788 // ----------------------------------------------------------------------------
789 // filename kind tests
790 // ----------------------------------------------------------------------------
792 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
794 wxFileName fn1
= *this,
797 // get cwd only once - small time saving
798 wxString cwd
= wxGetCwd();
799 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
800 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
802 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
805 // TODO: compare inodes for Unix, this works even when filenames are
806 // different but files are the same (symlinks) (VZ)
812 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
814 // only Unix filenames are truely case-sensitive
815 return GetFormat(format
) == wxPATH_UNIX
;
818 bool wxFileName::IsAbsolute( wxPathFormat format
)
820 // if we have no path, we can't be an abs filename
821 if ( m_dirs
.IsEmpty() )
826 format
= GetFormat(format
);
828 if ( format
== wxPATH_UNIX
)
830 const wxString
& str
= m_dirs
[0u];
833 // the path started with '/', it's an absolute one
837 // the path is absolute if it starts with a path separator or
838 // with "~" or "~user"
841 return IsPathSeparator(ch
, format
) || ch
== _T('~');
845 // must have the drive
846 if ( m_volume
.empty() )
852 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
856 return m_dirs
[0u].empty();
859 // TODO: what is the relative path format here?
863 return !m_dirs
[0u].empty();
869 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
873 if ( (GetFormat(format
) == wxPATH_DOS
) ||
874 (GetFormat(format
) == wxPATH_VMS
) )
876 sepVol
= wxFILE_SEP_DSK
;
884 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
887 switch ( GetFormat(format
) )
890 // accept both as native APIs do but put the native one first as
891 // this is the one we use in GetFullPath()
892 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
896 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
900 seps
= wxFILE_SEP_PATH_UNIX
;
904 seps
= wxFILE_SEP_PATH_MAC
;
908 seps
= wxFILE_SEP_PATH_VMS
;
916 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
918 // wxString::Find() doesn't work as expected with NUL - it will always find
919 // it, so it is almost surely a bug if this function is called with NUL arg
920 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
922 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
925 bool wxFileName::IsWild( wxPathFormat format
)
927 // FIXME: this is probably false for Mac and this is surely wrong for most
928 // of Unix shells (think about "[...]")
930 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
933 // ----------------------------------------------------------------------------
934 // path components manipulation
935 // ----------------------------------------------------------------------------
937 void wxFileName::AppendDir( const wxString
&dir
)
942 void wxFileName::PrependDir( const wxString
&dir
)
944 m_dirs
.Insert( dir
, 0 );
947 void wxFileName::InsertDir( int before
, const wxString
&dir
)
949 m_dirs
.Insert( dir
, before
);
952 void wxFileName::RemoveDir( int pos
)
954 m_dirs
.Remove( (size_t)pos
);
957 // ----------------------------------------------------------------------------
959 // ----------------------------------------------------------------------------
961 void wxFileName::SetFullName(const wxString
& fullname
)
963 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
966 wxString
wxFileName::GetFullName() const
968 wxString fullname
= m_name
;
969 if ( !m_ext
.empty() )
971 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
977 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
979 format
= GetFormat( format
);
982 size_t count
= m_dirs
.GetCount();
983 for ( size_t i
= 0; i
< count
; i
++ )
986 if ( add_separator
|| (i
< count
) )
987 ret
+= wxFILE_SEP_PATH
;
993 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
995 format
= GetFormat(format
);
999 // first put the volume
1000 if ( !m_volume
.empty() )
1003 // Special Windows UNC paths hack, part 2: undo what we did in
1004 // SplitPath() and make an UNC path if we have a drive which is not a
1005 // single letter (hopefully the network shares can't be one letter only
1006 // although I didn't find any authoritative docs on this)
1007 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1009 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1013 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1018 // then concatenate all the path components using the path separator
1019 size_t dirCount
= m_dirs
.GetCount();
1022 // under Mac, we must have a path separator in the beginning of the
1023 // relative path - otherwise it would be parsed as an absolute one
1024 if ( format
== wxPATH_MAC
&& m_dirs
[0].empty() )
1026 fullpath
+= wxFILE_SEP_PATH_MAC
;
1029 wxChar chPathSep
= GetPathSeparators(format
)[0u];
1030 if ( format
== wxPATH_VMS
)
1032 fullpath
+= _T('[');
1035 for ( size_t i
= 0; i
< dirCount
; i
++ )
1037 // under VMS, we shouldn't have a leading dot
1038 if ( i
&& (format
!= wxPATH_VMS
|| !m_dirs
[i
- 1].empty()) )
1039 fullpath
+= chPathSep
;
1041 fullpath
+= m_dirs
[i
];
1044 if ( format
== wxPATH_VMS
)
1046 fullpath
+= _T(']');
1050 // separate the file name from the last directory, notice that we
1051 // intentionally do it even if the name and extension are empty as
1052 // this allows us to distinguish the directories from the file
1053 // names (the directories have the trailing slash)
1054 fullpath
+= chPathSep
;
1058 // finally add the file name and extension
1059 fullpath
+= GetFullName();
1064 // Return the short form of the path (returns identity on non-Windows platforms)
1065 wxString
wxFileName::GetShortPath() const
1067 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1068 wxString
path(GetFullPath());
1070 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1074 ok
= ::GetShortPathName
1077 pathOut
.GetWriteBuf(sz
),
1080 pathOut
.UngetWriteBuf();
1087 return GetFullPath();
1091 // Return the long form of the path (returns identity on non-Windows platforms)
1092 wxString
wxFileName::GetLongPath() const
1095 path
= GetFullPath();
1097 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1098 bool success
= FALSE
;
1100 // VZ: this code was disabled, why?
1101 #if 0 // wxUSE_DYNLIB_CLASS
1102 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1104 static bool s_triedToLoad
= FALSE
;
1106 if ( !s_triedToLoad
)
1108 s_triedToLoad
= TRUE
;
1109 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1112 // may succeed or fail depending on the Windows version
1113 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1115 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1117 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1120 wxDllLoader::UnloadLibrary(dllKernel
);
1122 if ( s_pfnGetLongPathName
)
1124 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1125 bool ok
= dwSize
> 0;
1129 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1133 ok
= (*s_pfnGetLongPathName
)
1136 pathOut
.GetWriteBuf(sz
),
1139 pathOut
.UngetWriteBuf();
1149 #endif // wxUSE_DYNLIB_CLASS
1153 // The OS didn't support GetLongPathName, or some other error.
1154 // We need to call FindFirstFile on each component in turn.
1156 WIN32_FIND_DATA findFileData
;
1158 pathOut
= wxEmptyString
;
1160 wxArrayString dirs
= GetDirs();
1161 dirs
.Add(GetFullName());
1165 size_t count
= dirs
.GetCount();
1166 for ( size_t i
= 0; i
< count
; i
++ )
1168 // We're using pathOut to collect the long-name path, but using a
1169 // temporary for appending the last path component which may be
1171 tmpPath
= pathOut
+ dirs
[i
];
1173 if ( tmpPath
.empty() )
1176 if ( tmpPath
.Last() == wxT(':') )
1178 // Can't pass a drive and root dir to FindFirstFile,
1179 // so continue to next dir
1180 tmpPath
+= wxFILE_SEP_PATH
;
1185 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1186 if (hFind
== INVALID_HANDLE_VALUE
)
1188 // Error: return immediately with the original path
1192 pathOut
+= findFileData
.cFileName
;
1193 if ( (i
< (count
-1)) )
1194 pathOut
+= wxFILE_SEP_PATH
;
1201 #endif // Win32/!Win32
1206 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1208 if (format
== wxPATH_NATIVE
)
1210 #if defined(__WXMSW__) || defined(__WXPM__)
1211 format
= wxPATH_DOS
;
1212 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1213 format
= wxPATH_MAC
;
1214 #elif defined(__VMS)
1215 format
= wxPATH_VMS
;
1217 format
= wxPATH_UNIX
;
1223 // ----------------------------------------------------------------------------
1224 // path splitting function
1225 // ----------------------------------------------------------------------------
1228 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1229 wxString
*pstrVolume
,
1233 wxPathFormat format
)
1235 format
= GetFormat(format
);
1237 wxString fullpath
= fullpathWithVolume
;
1239 // under VMS the end of the path is ']', not the path separator used to
1240 // separate the components
1241 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1242 : GetPathSeparators(format
);
1244 // special Windows UNC paths hack: transform \\share\path into share:path
1245 if ( format
== wxPATH_DOS
)
1247 if ( fullpath
.length() >= 4 &&
1248 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1249 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1251 fullpath
.erase(0, 2);
1253 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1254 if ( posFirstSlash
!= wxString::npos
)
1256 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1258 // UNC paths are always absolute, right? (FIXME)
1259 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1264 // We separate the volume here
1265 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1267 wxString sepVol
= GetVolumeSeparator(format
);
1269 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1270 if ( posFirstColon
!= wxString::npos
)
1274 *pstrVolume
= fullpath
.Left(posFirstColon
);
1277 // remove the volume name and the separator from the full path
1278 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1282 // find the positions of the last dot and last path separator in the path
1283 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1284 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1286 if ( (posLastDot
!= wxString::npos
) &&
1287 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1289 if ( (posLastDot
== 0) ||
1290 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1292 // under Unix and VMS, dot may be (and commonly is) the first
1293 // character of the filename, don't treat the entire filename as
1294 // extension in this case
1295 posLastDot
= wxString::npos
;
1299 // if we do have a dot and a slash, check that the dot is in the name part
1300 if ( (posLastDot
!= wxString::npos
) &&
1301 (posLastSlash
!= wxString::npos
) &&
1302 (posLastDot
< posLastSlash
) )
1304 // the dot is part of the path, not the start of the extension
1305 posLastDot
= wxString::npos
;
1308 // now fill in the variables provided by user
1311 if ( posLastSlash
== wxString::npos
)
1318 // take everything up to the path separator but take care to make
1319 // tha path equal to something like '/', not empty, for the files
1320 // immediately under root directory
1321 size_t len
= posLastSlash
;
1325 *pstrPath
= fullpath
.Left(len
);
1327 // special VMS hack: remove the initial bracket
1328 if ( format
== wxPATH_VMS
)
1330 if ( (*pstrPath
)[0u] == _T('[') )
1331 pstrPath
->erase(0, 1);
1338 // take all characters starting from the one after the last slash and
1339 // up to, but excluding, the last dot
1340 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1342 if ( posLastDot
== wxString::npos
)
1344 // take all until the end
1345 count
= wxString::npos
;
1347 else if ( posLastSlash
== wxString::npos
)
1351 else // have both dot and slash
1353 count
= posLastDot
- posLastSlash
- 1;
1356 *pstrName
= fullpath
.Mid(nStart
, count
);
1361 if ( posLastDot
== wxString::npos
)
1368 // take everything after the dot
1369 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1375 void wxFileName::SplitPath(const wxString
& fullpath
,
1379 wxPathFormat format
)
1382 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1384 if ( path
&& !volume
.empty() )
1386 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1390 // ----------------------------------------------------------------------------
1392 // ----------------------------------------------------------------------------
1394 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1395 const wxDateTime
*dtAccess
,
1396 const wxDateTime
*dtMod
)
1398 #if defined(__UNIX_LIKE__)
1399 if ( !dtAccess
&& !dtMod
)
1401 // can't modify the creation time anyhow, don't try
1405 // if dtAccess or dtMod is not specified, use the other one (which must be
1406 // non NULL because of the test above) for both times
1408 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1409 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1410 if ( utime(GetFullPath(), &utm
) == 0 )
1414 #elif defined(__WIN32__)
1415 wxFileHandle
fh(GetFullPath());
1418 FILETIME ftAccess
, ftCreate
, ftWrite
;
1421 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1423 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1425 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1427 if ( ::SetFileTime(fh
,
1428 dtCreate
? &ftCreate
: NULL
,
1429 dtAccess
? &ftAccess
: NULL
,
1430 dtMod
? &ftWrite
: NULL
) )
1435 #else // other platform
1438 wxLogSysError(_("Failed to modify file times for '%s'"),
1439 GetFullPath().c_str());
1444 bool wxFileName::Touch()
1446 #if defined(__UNIX_LIKE__)
1447 // under Unix touching file is simple: just pass NULL to utime()
1448 if ( utime(GetFullPath(), NULL
) == 0 )
1453 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1456 #else // other platform
1457 wxDateTime dtNow
= wxDateTime::Now();
1459 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1463 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1465 wxDateTime
*dtChange
) const
1467 #if defined(__UNIX_LIKE__)
1469 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1472 dtAccess
->Set(stBuf
.st_atime
);
1474 dtMod
->Set(stBuf
.st_mtime
);
1476 dtChange
->Set(stBuf
.st_ctime
);
1480 #elif defined(__WXMAC__)
1482 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1485 dtAccess
->Set(stBuf
.st_atime
);
1487 dtMod
->Set(stBuf
.st_mtime
);
1489 dtChange
->Set(stBuf
.st_ctime
);
1493 #elif defined(__WIN32__)
1494 wxFileHandle
fh(GetFullPath());
1497 FILETIME ftAccess
, ftCreate
, ftWrite
;
1499 if ( ::GetFileTime(fh
,
1500 dtMod
? &ftCreate
: NULL
,
1501 dtAccess
? &ftAccess
: NULL
,
1502 dtChange
? &ftWrite
: NULL
) )
1505 ConvertFileTimeToWx(dtMod
, ftCreate
);
1507 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1509 ConvertFileTimeToWx(dtChange
, ftWrite
);
1514 #else // other platform
1517 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1518 GetFullPath().c_str());