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 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
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"
80 #include "wx/filename.h"
81 #include "wx/tokenzr.h"
82 #include "wx/config.h" // for wxExpandEnvVars
86 #if wxUSE_DYNAMIC_LOADER || wxUSE_DYNLIB_CLASS
87 #include "wx/dynlib.h"
90 // For GetShort/LongPathName
93 #include "wx/msw/winundef.h"
96 // utime() is POSIX so should normally be available on all Unices
98 #include <sys/types.h>
100 #include <sys/stat.h>
112 #include <sys/utime.h>
113 #include <sys/stat.h>
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
126 // small helper class which opens and closes the file - we use it just to get
127 // a file handle for the given file name to pass it to some Win32 API function
128 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
133 wxFileHandle(const wxString
& filename
)
135 m_hFile
= ::CreateFile
138 GENERIC_READ
, // access mask
140 NULL
, // no secutity attr
141 OPEN_EXISTING
, // creation disposition
143 NULL
// no template file
146 if ( m_hFile
== INVALID_HANDLE_VALUE
)
148 wxLogSysError(_("Failed to open '%s' for reading"),
155 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
157 if ( !::CloseHandle(m_hFile
) )
159 wxLogSysError(_("Failed to close file handle"));
164 // return TRUE only if the file could be opened successfully
165 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
168 operator HANDLE() const { return m_hFile
; }
176 // ----------------------------------------------------------------------------
178 // ----------------------------------------------------------------------------
180 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
182 // convert between wxDateTime and FILETIME which is a 64-bit value representing
183 // the number of 100-nanosecond intervals since January 1, 1601.
185 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
186 // FILETIME reference point (January 1, 1601)
187 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
189 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
191 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
193 // convert 100ns to ms
196 // move it to our Epoch
197 ll
-= FILETIME_EPOCH_OFFSET
;
199 *dt
= wxDateTime(ll
);
202 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
204 // do the reverse of ConvertFileTimeToWx()
205 wxLongLong ll
= dt
.GetValue();
207 ll
+= FILETIME_EPOCH_OFFSET
;
209 ft
->dwHighDateTime
= ll
.GetHi();
210 ft
->dwLowDateTime
= ll
.GetLo();
215 // ============================================================================
217 // ============================================================================
219 // ----------------------------------------------------------------------------
220 // wxFileName construction
221 // ----------------------------------------------------------------------------
223 void wxFileName::Assign( const wxFileName
&filepath
)
225 m_volume
= filepath
.GetVolume();
226 m_dirs
= filepath
.GetDirs();
227 m_name
= filepath
.GetName();
228 m_ext
= filepath
.GetExt();
229 m_relative
= filepath
.IsRelative();
232 void wxFileName::Assign(const wxString
& volume
,
233 const wxString
& path
,
234 const wxString
& name
,
236 wxPathFormat format
)
238 wxPathFormat my_format
= GetFormat( format
);
239 wxString my_path
= path
;
243 if (!my_path
.empty())
245 // 1) Determine if the path is relative or absolute.
250 m_relative
= ( my_path
[0u] == wxT(':') );
251 // We then remove a leading ":". The reason is in our
252 // storage form for relative paths:
253 // ":dir:file.txt" actually means "./dir/file.txt" in
254 // DOS notation and should get stored as
255 // (relative) (dir) (file.txt)
256 // "::dir:file.txt" actually means "../dir/file.txt"
257 // stored as (relative) (..) (dir) (file.txt)
258 // This is important only for the Mac as an empty dir
259 // actually means <UP>, whereas under DOS, double
260 // slashes can be ignored: "\\\\" is the same as "\\".
262 my_path
.Remove( 0, 1 );
265 // TODO: what is the relative path format here?
269 m_relative
= ( my_path
[0u] != wxT('/') );
272 m_relative
= ( (my_path
[0u] != wxT('/')) && (my_path
[0u] != wxT('\\')) );
275 wxFAIL_MSG( wxT("error") );
279 // 2) Break up the path into its members. If the original path
280 // was just "/" or "\\", m_dirs will be empty. We know from
281 // the m_relative field, if this means "nothing" or "root dir".
283 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
285 while ( tn
.HasMoreTokens() )
287 wxString token
= tn
.GetNextToken();
289 // Remove empty token under DOS and Unix, interpret them
293 if (my_format
== wxPATH_MAC
)
294 m_dirs
.Add( wxT("..") );
309 void wxFileName::Assign(const wxString
& fullpath
,
312 wxString volume
, path
, name
, ext
;
313 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
315 Assign(volume
, path
, name
, ext
, format
);
318 void wxFileName::Assign(const wxString
& fullpathOrig
,
319 const wxString
& fullname
,
322 // always recognize fullpath as directory, even if it doesn't end with a
324 wxString fullpath
= fullpathOrig
;
325 if ( !wxEndsWithPathSeparator(fullpath
) )
327 fullpath
+= GetPathSeparators(format
)[0u];
330 wxString volume
, path
, name
, ext
;
332 // do some consistency checks in debug mode: the name should be really just
333 // the filename and the path should be really just a path
335 wxString pathDummy
, nameDummy
, extDummy
;
337 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
339 wxASSERT_MSG( pathDummy
.empty(),
340 _T("the file name shouldn't contain the path") );
342 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
344 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
345 _T("the path shouldn't contain file name nor extension") );
347 #else // !__WXDEBUG__
348 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
349 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
350 #endif // __WXDEBUG__/!__WXDEBUG__
352 Assign(volume
, path
, name
, ext
, format
);
355 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
357 Assign(dir
, _T(""), format
);
360 void wxFileName::Clear()
366 m_ext
= wxEmptyString
;
370 wxFileName
wxFileName::FileName(const wxString
& file
)
372 return wxFileName(file
);
376 wxFileName
wxFileName::DirName(const wxString
& dir
)
383 // ----------------------------------------------------------------------------
385 // ----------------------------------------------------------------------------
387 bool wxFileName::FileExists()
389 return wxFileName::FileExists( GetFullPath() );
392 bool wxFileName::FileExists( const wxString
&file
)
394 return ::wxFileExists( file
);
397 bool wxFileName::DirExists()
399 return wxFileName::DirExists( GetFullPath() );
402 bool wxFileName::DirExists( const wxString
&dir
)
404 return ::wxDirExists( dir
);
407 // ----------------------------------------------------------------------------
408 // CWD and HOME stuff
409 // ----------------------------------------------------------------------------
411 void wxFileName::AssignCwd(const wxString
& volume
)
413 AssignDir(wxFileName::GetCwd(volume
));
417 wxString
wxFileName::GetCwd(const wxString
& volume
)
419 // if we have the volume, we must get the current directory on this drive
420 // and to do this we have to chdir to this volume - at least under Windows,
421 // I don't know how to get the current drive on another volume elsewhere
424 if ( !volume
.empty() )
427 SetCwd(volume
+ GetVolumeSeparator());
430 wxString cwd
= ::wxGetCwd();
432 if ( !volume
.empty() )
440 bool wxFileName::SetCwd()
442 return wxFileName::SetCwd( GetFullPath() );
445 bool wxFileName::SetCwd( const wxString
&cwd
)
447 return ::wxSetWorkingDirectory( cwd
);
450 void wxFileName::AssignHomeDir()
452 AssignDir(wxFileName::GetHomeDir());
455 wxString
wxFileName::GetHomeDir()
457 return ::wxGetHomeDir();
460 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
462 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
463 if ( tempname
.empty() )
465 // error, failed to get temp file name
476 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
478 wxString path
, dir
, name
;
480 // use the directory specified by the prefix
481 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
483 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
488 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
490 wxLogLastError(_T("GetTempPath"));
495 // GetTempFileName() fails if we pass it an empty string
500 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
502 wxLogLastError(_T("GetTempFileName"));
507 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
513 #elif defined(__WXPM__)
514 // for now just create a file
516 // future enhancements can be to set some extended attributes for file
517 // systems OS/2 supports that have them (HPFS, FAT32) and security
519 static const wxChar
*szMktempSuffix
= wxT("XXX");
520 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
522 // Temporarily remove - MN
524 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
527 #else // !Windows, !OS/2
530 dir
= wxGetenv(_T("TMP"));
533 dir
= wxGetenv(_T("TEMP"));
549 if ( !wxEndsWithPathSeparator(dir
) &&
550 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
552 path
+= wxFILE_SEP_PATH
;
557 #if defined(HAVE_MKSTEMP)
558 // scratch space for mkstemp()
559 path
+= _T("XXXXXX");
561 // can use the cast here because the length doesn't change and the string
563 int fdTemp
= mkstemp((char *)path
.mb_str());
566 // this might be not necessary as mkstemp() on most systems should have
567 // already done it but it doesn't hurt neither...
570 else // mkstemp() succeeded
572 // avoid leaking the fd
575 fileTemp
->Attach(fdTemp
);
582 #else // !HAVE_MKSTEMP
586 path
+= _T("XXXXXX");
588 if ( !mktemp((char *)path
.mb_str()) )
592 #else // !HAVE_MKTEMP (includes __DOS__)
593 // generate the unique file name ourselves
595 path
<< (unsigned int)getpid();
600 static const size_t numTries
= 1000;
601 for ( size_t n
= 0; n
< numTries
; n
++ )
603 // 3 hex digits is enough for numTries == 1000 < 4096
604 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
605 if ( !wxFile::Exists(pathTry
) )
614 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
619 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
621 #endif // Windows/!Windows
625 wxLogSysError(_("Failed to create a temporary file name"));
627 else if ( fileTemp
&& !fileTemp
->IsOpened() )
629 // open the file - of course, there is a race condition here, this is
630 // why we always prefer using mkstemp()...
631 if ( !fileTemp
->Open(path
, wxFile::write_excl
, wxS_IRUSR
| wxS_IWUSR
) )
633 // FIXME: If !ok here should we loop and try again with another
634 // file name? That is the standard recourse if open(O_EXCL)
635 // fails, though of course it should be protected against
636 // possible infinite looping too.
638 wxLogError(_("Failed to open temporary file."));
647 // ----------------------------------------------------------------------------
648 // directory operations
649 // ----------------------------------------------------------------------------
651 bool wxFileName::Mkdir( int perm
, bool full
)
653 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
656 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
660 wxFileName
filename(dir
);
661 wxArrayString dirs
= filename
.GetDirs();
662 dirs
.Add(filename
.GetName());
664 size_t count
= dirs
.GetCount();
668 for ( i
= 0; i
< count
; i
++ )
672 if (currPath
.Last() == wxT(':'))
674 // Can't create a root directory so continue to next dir
675 currPath
+= wxFILE_SEP_PATH
;
679 if (!DirExists(currPath
))
680 if (!wxMkdir(currPath
, perm
))
683 if ( (i
< (count
-1)) )
684 currPath
+= wxFILE_SEP_PATH
;
687 return (noErrors
== 0);
691 return ::wxMkdir( dir
, perm
);
694 bool wxFileName::Rmdir()
696 return wxFileName::Rmdir( GetFullPath() );
699 bool wxFileName::Rmdir( const wxString
&dir
)
701 return ::wxRmdir( dir
);
704 // ----------------------------------------------------------------------------
705 // path normalization
706 // ----------------------------------------------------------------------------
708 bool wxFileName::Normalize(wxPathNormalize flags
,
712 // the existing path components
713 wxArrayString dirs
= GetDirs();
715 // the path to prepend in front to make the path absolute
718 format
= GetFormat(format
);
720 // make the path absolute
721 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
725 curDir
.AssignCwd(GetVolume());
729 curDir
.AssignDir(cwd
);
733 // the path may be not absolute because it doesn't have the volume name
734 // but in this case we shouldn't modify the directory components of it
735 // but just set the current volume
736 if ( !HasVolume() && curDir
.HasVolume() )
738 SetVolume(curDir
.GetVolume());
742 // yes, it was the case - we don't need curDir then
750 // handle ~ stuff under Unix only
751 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
753 if ( !dirs
.IsEmpty() )
755 wxString dir
= dirs
[0u];
756 if ( !dir
.empty() && dir
[0u] == _T('~') )
758 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
765 // transform relative path into abs one
768 wxArrayString dirsNew
= curDir
.GetDirs();
769 size_t count
= dirs
.GetCount();
770 for ( size_t n
= 0; n
< count
; n
++ )
772 dirsNew
.Add(dirs
[n
]);
778 // now deal with ".", ".." and the rest
780 size_t count
= dirs
.GetCount();
781 for ( size_t n
= 0; n
< count
; n
++ )
783 wxString dir
= dirs
[n
];
785 if ( flags
& wxPATH_NORM_DOTS
)
787 if ( dir
== wxT(".") )
793 if ( dir
== wxT("..") )
795 if ( m_dirs
.IsEmpty() )
797 wxLogError(_("The path '%s' contains too many \"..\"!"),
798 GetFullPath().c_str());
802 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
807 if ( flags
& wxPATH_NORM_ENV_VARS
)
809 dir
= wxExpandEnvVars(dir
);
812 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
820 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
822 // VZ: expand env vars here too?
828 #if defined(__WIN32__)
829 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
831 Assign(GetLongPath());
838 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
840 wxFileName
fnBase(pathBase
, format
);
842 // get cwd only once - small time saving
843 wxString cwd
= wxGetCwd();
844 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
845 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
847 bool withCase
= IsCaseSensitive(format
);
849 // we can't do anything if the files live on different volumes
850 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
856 // same drive, so we don't need our volume
859 // remove common directories starting at the top
860 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
861 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
864 fnBase
.m_dirs
.RemoveAt(0);
867 // add as many ".." as needed
868 size_t count
= fnBase
.m_dirs
.GetCount();
869 for ( size_t i
= 0; i
< count
; i
++ )
871 m_dirs
.Insert(wxT(".."), 0u);
880 // ----------------------------------------------------------------------------
881 // filename kind tests
882 // ----------------------------------------------------------------------------
884 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
886 wxFileName fn1
= *this,
889 // get cwd only once - small time saving
890 wxString cwd
= wxGetCwd();
891 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
892 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
894 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
897 // TODO: compare inodes for Unix, this works even when filenames are
898 // different but files are the same (symlinks) (VZ)
904 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
906 // only Unix filenames are truely case-sensitive
907 return GetFormat(format
) == wxPATH_UNIX
;
911 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
915 if ( (GetFormat(format
) == wxPATH_DOS
) ||
916 (GetFormat(format
) == wxPATH_VMS
) )
918 sepVol
= wxFILE_SEP_DSK
;
926 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
929 switch ( GetFormat(format
) )
932 // accept both as native APIs do but put the native one first as
933 // this is the one we use in GetFullPath()
934 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
938 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
942 seps
= wxFILE_SEP_PATH_UNIX
;
946 seps
= wxFILE_SEP_PATH_MAC
;
950 seps
= wxFILE_SEP_PATH_VMS
;
958 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
960 // wxString::Find() doesn't work as expected with NUL - it will always find
961 // it, so it is almost surely a bug if this function is called with NUL arg
962 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
964 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
967 bool wxFileName::IsWild( wxPathFormat format
)
969 // FIXME: this is probably false for Mac and this is surely wrong for most
970 // of Unix shells (think about "[...]")
972 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
975 // ----------------------------------------------------------------------------
976 // path components manipulation
977 // ----------------------------------------------------------------------------
979 void wxFileName::AppendDir( const wxString
&dir
)
984 void wxFileName::PrependDir( const wxString
&dir
)
986 m_dirs
.Insert( dir
, 0 );
989 void wxFileName::InsertDir( int before
, const wxString
&dir
)
991 m_dirs
.Insert( dir
, before
);
994 void wxFileName::RemoveDir( int pos
)
996 m_dirs
.Remove( (size_t)pos
);
999 // ----------------------------------------------------------------------------
1001 // ----------------------------------------------------------------------------
1003 void wxFileName::SetFullName(const wxString
& fullname
)
1005 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1008 wxString
wxFileName::GetFullName() const
1010 wxString fullname
= m_name
;
1011 if ( !m_ext
.empty() )
1013 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1019 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1021 format
= GetFormat( format
);
1025 // the leading character
1026 if ( format
== wxPATH_MAC
&& m_relative
)
1028 fullpath
+= wxFILE_SEP_PATH_MAC
;
1030 else if ( format
== wxPATH_DOS
)
1033 fullpath
+= wxFILE_SEP_PATH_DOS
;
1035 else if ( format
== wxPATH_UNIX
)
1038 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1041 // then concatenate all the path components using the path separator
1042 size_t dirCount
= m_dirs
.GetCount();
1045 if ( format
== wxPATH_VMS
)
1047 fullpath
+= wxT('[');
1051 for ( size_t i
= 0; i
< dirCount
; i
++ )
1053 // TODO: What to do with ".." under VMS
1059 if (m_dirs
[i
] == wxT("."))
1061 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1062 fullpath
+= m_dirs
[i
];
1063 fullpath
+= wxT(':');
1068 fullpath
+= m_dirs
[i
];
1069 fullpath
+= wxT('\\');
1074 fullpath
+= m_dirs
[i
];
1075 fullpath
+= wxT('/');
1080 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1081 fullpath
+= m_dirs
[i
];
1082 if (i
== dirCount
-1)
1083 fullpath
+= wxT(']');
1085 fullpath
+= wxT('.');
1090 wxFAIL_MSG( wxT("error") );
1101 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1103 format
= GetFormat(format
);
1107 // first put the volume
1108 if ( !m_volume
.empty() )
1111 // Special Windows UNC paths hack, part 2: undo what we did in
1112 // SplitPath() and make an UNC path if we have a drive which is not a
1113 // single letter (hopefully the network shares can't be one letter only
1114 // although I didn't find any authoritative docs on this)
1115 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1117 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1119 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1121 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1127 // the leading character
1128 if ( format
== wxPATH_MAC
&& m_relative
)
1130 fullpath
+= wxFILE_SEP_PATH_MAC
;
1132 else if ( format
== wxPATH_DOS
)
1135 fullpath
+= wxFILE_SEP_PATH_DOS
;
1137 else if ( format
== wxPATH_UNIX
)
1140 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1143 // then concatenate all the path components using the path separator
1144 size_t dirCount
= m_dirs
.GetCount();
1147 if ( format
== wxPATH_VMS
)
1149 fullpath
+= wxT('[');
1153 for ( size_t i
= 0; i
< dirCount
; i
++ )
1155 // TODO: What to do with ".." under VMS
1161 if (m_dirs
[i
] == wxT("."))
1163 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1164 fullpath
+= m_dirs
[i
];
1165 fullpath
+= wxT(':');
1170 fullpath
+= m_dirs
[i
];
1171 fullpath
+= wxT('\\');
1176 fullpath
+= m_dirs
[i
];
1177 fullpath
+= wxT('/');
1182 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1183 fullpath
+= m_dirs
[i
];
1184 if (i
== dirCount
-1)
1185 fullpath
+= wxT(']');
1187 fullpath
+= wxT('.');
1192 wxFAIL_MSG( wxT("error") );
1198 // finally add the file name and extension
1199 fullpath
+= GetFullName();
1204 // Return the short form of the path (returns identity on non-Windows platforms)
1205 wxString
wxFileName::GetShortPath() const
1207 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1208 wxString
path(GetFullPath());
1210 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1214 ok
= ::GetShortPathName
1217 pathOut
.GetWriteBuf(sz
),
1220 pathOut
.UngetWriteBuf();
1227 return GetFullPath();
1231 // Return the long form of the path (returns identity on non-Windows platforms)
1232 wxString
wxFileName::GetLongPath() const
1235 path
= GetFullPath();
1237 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1238 bool success
= FALSE
;
1240 // VZ: this code was disabled, why?
1241 #if 0 // wxUSE_DYNAMIC_LOADER
1242 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1244 static bool s_triedToLoad
= FALSE
;
1246 if ( !s_triedToLoad
)
1248 s_triedToLoad
= TRUE
;
1249 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1252 // may succeed or fail depending on the Windows version
1253 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1255 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1257 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1260 wxDllLoader::UnloadLibrary(dllKernel
);
1262 if ( s_pfnGetLongPathName
)
1264 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1265 bool ok
= dwSize
> 0;
1269 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1273 ok
= (*s_pfnGetLongPathName
)
1276 pathOut
.GetWriteBuf(sz
),
1279 pathOut
.UngetWriteBuf();
1289 #endif // wxUSE_DYNAMIC_LOADER
1293 // The OS didn't support GetLongPathName, or some other error.
1294 // We need to call FindFirstFile on each component in turn.
1296 WIN32_FIND_DATA findFileData
;
1298 pathOut
= wxEmptyString
;
1300 wxArrayString dirs
= GetDirs();
1301 dirs
.Add(GetFullName());
1305 size_t count
= dirs
.GetCount();
1306 for ( size_t i
= 0; i
< count
; i
++ )
1308 // We're using pathOut to collect the long-name path, but using a
1309 // temporary for appending the last path component which may be
1311 tmpPath
= pathOut
+ dirs
[i
];
1313 if ( tmpPath
.empty() )
1316 if ( tmpPath
.Last() == wxT(':') )
1318 // Can't pass a drive and root dir to FindFirstFile,
1319 // so continue to next dir
1320 tmpPath
+= wxFILE_SEP_PATH
;
1325 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1326 if (hFind
== INVALID_HANDLE_VALUE
)
1328 // Error: return immediately with the original path
1332 pathOut
+= findFileData
.cFileName
;
1333 if ( (i
< (count
-1)) )
1334 pathOut
+= wxFILE_SEP_PATH
;
1341 #endif // Win32/!Win32
1346 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1348 if (format
== wxPATH_NATIVE
)
1350 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1351 format
= wxPATH_DOS
;
1352 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1353 format
= wxPATH_MAC
;
1354 #elif defined(__VMS)
1355 format
= wxPATH_VMS
;
1357 format
= wxPATH_UNIX
;
1363 // ----------------------------------------------------------------------------
1364 // path splitting function
1365 // ----------------------------------------------------------------------------
1368 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1369 wxString
*pstrVolume
,
1373 wxPathFormat format
)
1375 format
= GetFormat(format
);
1377 wxString fullpath
= fullpathWithVolume
;
1379 // under VMS the end of the path is ']', not the path separator used to
1380 // separate the components
1381 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1382 : GetPathSeparators(format
);
1384 // special Windows UNC paths hack: transform \\share\path into share:path
1385 if ( format
== wxPATH_DOS
)
1387 if ( fullpath
.length() >= 4 &&
1388 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1389 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1391 fullpath
.erase(0, 2);
1393 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1394 if ( posFirstSlash
!= wxString::npos
)
1396 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1398 // UNC paths are always absolute, right? (FIXME)
1399 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1404 // We separate the volume here
1405 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1407 wxString sepVol
= GetVolumeSeparator(format
);
1409 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1410 if ( posFirstColon
!= wxString::npos
)
1414 *pstrVolume
= fullpath
.Left(posFirstColon
);
1417 // remove the volume name and the separator from the full path
1418 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1422 // find the positions of the last dot and last path separator in the path
1423 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1424 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1426 if ( (posLastDot
!= wxString::npos
) &&
1427 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1429 if ( (posLastDot
== 0) ||
1430 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1432 // under Unix and VMS, dot may be (and commonly is) the first
1433 // character of the filename, don't treat the entire filename as
1434 // extension in this case
1435 posLastDot
= wxString::npos
;
1439 // if we do have a dot and a slash, check that the dot is in the name part
1440 if ( (posLastDot
!= wxString::npos
) &&
1441 (posLastSlash
!= wxString::npos
) &&
1442 (posLastDot
< posLastSlash
) )
1444 // the dot is part of the path, not the start of the extension
1445 posLastDot
= wxString::npos
;
1448 // now fill in the variables provided by user
1451 if ( posLastSlash
== wxString::npos
)
1458 // take everything up to the path separator but take care to make
1459 // the path equal to something like '/', not empty, for the files
1460 // immediately under root directory
1461 size_t len
= posLastSlash
;
1465 *pstrPath
= fullpath
.Left(len
);
1467 // special VMS hack: remove the initial bracket
1468 if ( format
== wxPATH_VMS
)
1470 if ( (*pstrPath
)[0u] == _T('[') )
1471 pstrPath
->erase(0, 1);
1478 // take all characters starting from the one after the last slash and
1479 // up to, but excluding, the last dot
1480 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1482 if ( posLastDot
== wxString::npos
)
1484 // take all until the end
1485 count
= wxString::npos
;
1487 else if ( posLastSlash
== wxString::npos
)
1491 else // have both dot and slash
1493 count
= posLastDot
- posLastSlash
- 1;
1496 *pstrName
= fullpath
.Mid(nStart
, count
);
1501 if ( posLastDot
== wxString::npos
)
1508 // take everything after the dot
1509 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1515 void wxFileName::SplitPath(const wxString
& fullpath
,
1519 wxPathFormat format
)
1522 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1524 if ( path
&& !volume
.empty() )
1526 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1530 // ----------------------------------------------------------------------------
1532 // ----------------------------------------------------------------------------
1534 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1535 const wxDateTime
*dtAccess
,
1536 const wxDateTime
*dtMod
)
1538 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1539 if ( !dtAccess
&& !dtMod
)
1541 // can't modify the creation time anyhow, don't try
1545 // if dtAccess or dtMod is not specified, use the other one (which must be
1546 // non NULL because of the test above) for both times
1548 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1549 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1550 if ( utime(GetFullPath(), &utm
) == 0 )
1554 #elif defined(__WIN32__)
1555 wxFileHandle
fh(GetFullPath());
1558 FILETIME ftAccess
, ftCreate
, ftWrite
;
1561 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1563 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1565 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1567 if ( ::SetFileTime(fh
,
1568 dtCreate
? &ftCreate
: NULL
,
1569 dtAccess
? &ftAccess
: NULL
,
1570 dtMod
? &ftWrite
: NULL
) )
1575 #else // other platform
1578 wxLogSysError(_("Failed to modify file times for '%s'"),
1579 GetFullPath().c_str());
1584 bool wxFileName::Touch()
1586 #if defined(__UNIX_LIKE__)
1587 // under Unix touching file is simple: just pass NULL to utime()
1588 if ( utime(GetFullPath(), NULL
) == 0 )
1593 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1596 #else // other platform
1597 wxDateTime dtNow
= wxDateTime::Now();
1599 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1603 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1605 wxDateTime
*dtChange
) const
1607 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1609 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1612 dtAccess
->Set(stBuf
.st_atime
);
1614 dtMod
->Set(stBuf
.st_mtime
);
1616 dtChange
->Set(stBuf
.st_ctime
);
1620 #elif defined(__WIN32__)
1621 wxFileHandle
fh(GetFullPath());
1624 FILETIME ftAccess
, ftCreate
, ftWrite
;
1626 if ( ::GetFileTime(fh
,
1627 dtMod
? &ftCreate
: NULL
,
1628 dtAccess
? &ftAccess
: NULL
,
1629 dtChange
? &ftWrite
: NULL
) )
1632 ConvertFileTimeToWx(dtMod
, ftCreate
);
1634 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1636 ConvertFileTimeToWx(dtChange
, ftWrite
);
1641 #else // other platform
1644 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1645 GetFullPath().c_str());