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
85 //#include "wx/dynlib.h" // see GetLongPath below, code disabled.
87 // For GetShort/LongPathName
90 #include "wx/msw/winundef.h"
93 // utime() is POSIX so should normally be available on all Unices
95 #include <sys/types.h>
109 #include <sys/utime.h>
110 #include <sys/stat.h>
119 // ----------------------------------------------------------------------------
121 // ----------------------------------------------------------------------------
123 // small helper class which opens and closes the file - we use it just to get
124 // a file handle for the given file name to pass it to some Win32 API function
125 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
130 wxFileHandle(const wxString
& filename
)
132 m_hFile
= ::CreateFile
135 GENERIC_READ
, // access mask
137 NULL
, // no secutity attr
138 OPEN_EXISTING
, // creation disposition
140 NULL
// no template file
143 if ( m_hFile
== INVALID_HANDLE_VALUE
)
145 wxLogSysError(_("Failed to open '%s' for reading"),
152 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
154 if ( !::CloseHandle(m_hFile
) )
156 wxLogSysError(_("Failed to close file handle"));
161 // return TRUE only if the file could be opened successfully
162 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
165 operator HANDLE() const { return m_hFile
; }
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
177 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
179 // convert between wxDateTime and FILETIME which is a 64-bit value representing
180 // the number of 100-nanosecond intervals since January 1, 1601.
182 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
183 // FILETIME reference point (January 1, 1601)
184 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
186 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
188 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
190 // convert 100ns to ms
193 // move it to our Epoch
194 ll
-= FILETIME_EPOCH_OFFSET
;
196 *dt
= wxDateTime(ll
);
199 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
201 // do the reverse of ConvertFileTimeToWx()
202 wxLongLong ll
= dt
.GetValue();
204 ll
+= FILETIME_EPOCH_OFFSET
;
206 ft
->dwHighDateTime
= ll
.GetHi();
207 ft
->dwLowDateTime
= ll
.GetLo();
212 // ============================================================================
214 // ============================================================================
216 // ----------------------------------------------------------------------------
217 // wxFileName construction
218 // ----------------------------------------------------------------------------
220 void wxFileName::Assign( const wxFileName
&filepath
)
222 m_volume
= filepath
.GetVolume();
223 m_dirs
= filepath
.GetDirs();
224 m_name
= filepath
.GetName();
225 m_ext
= filepath
.GetExt();
226 m_relative
= filepath
.IsRelative();
229 void wxFileName::Assign(const wxString
& volume
,
230 const wxString
& path
,
231 const wxString
& name
,
233 wxPathFormat format
)
235 wxPathFormat my_format
= GetFormat( format
);
236 wxString my_path
= path
;
240 if (!my_path
.empty())
242 // 1) Determine if the path is relative or absolute.
247 m_relative
= ( my_path
[0u] == wxT(':') );
248 // We then remove a leading ":". The reason is in our
249 // storage form for relative paths:
250 // ":dir:file.txt" actually means "./dir/file.txt" in
251 // DOS notation and should get stored as
252 // (relative) (dir) (file.txt)
253 // "::dir:file.txt" actually means "../dir/file.txt"
254 // stored as (relative) (..) (dir) (file.txt)
255 // This is important only for the Mac as an empty dir
256 // actually means <UP>, whereas under DOS, double
257 // slashes can be ignored: "\\\\" is the same as "\\".
259 my_path
.Remove( 0, 1 );
262 // TODO: what is the relative path format here?
266 m_relative
= ( my_path
[0u] != wxT('/') );
269 m_relative
= ( (my_path
[0u] != wxT('/')) && (my_path
[0u] != wxT('\\')) );
272 wxFAIL_MSG( wxT("error") );
276 // 2) Break up the path into its members. If the original path
277 // was just "/" or "\\", m_dirs will be empty. We know from
278 // the m_relative field, if this means "nothing" or "root dir".
280 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
282 while ( tn
.HasMoreTokens() )
284 wxString token
= tn
.GetNextToken();
286 // Remove empty token under DOS and Unix, interpret them
290 if (my_format
== wxPATH_MAC
)
291 m_dirs
.Add( wxT("..") );
306 void wxFileName::Assign(const wxString
& fullpath
,
309 wxString volume
, path
, name
, ext
;
310 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
312 Assign(volume
, path
, name
, ext
, format
);
315 void wxFileName::Assign(const wxString
& fullpathOrig
,
316 const wxString
& fullname
,
319 // always recognize fullpath as directory, even if it doesn't end with a
321 wxString fullpath
= fullpathOrig
;
322 if ( !wxEndsWithPathSeparator(fullpath
) )
324 fullpath
+= GetPathSeparators(format
)[0u];
327 wxString volume
, path
, name
, ext
;
329 // do some consistency checks in debug mode: the name should be really just
330 // the filename and the path should be really just a path
332 wxString pathDummy
, nameDummy
, extDummy
;
334 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
336 wxASSERT_MSG( pathDummy
.empty(),
337 _T("the file name shouldn't contain the path") );
339 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
341 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
342 _T("the path shouldn't contain file name nor extension") );
344 #else // !__WXDEBUG__
345 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
346 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
347 #endif // __WXDEBUG__/!__WXDEBUG__
349 Assign(volume
, path
, name
, ext
, format
);
352 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
354 Assign(dir
, _T(""), format
);
357 void wxFileName::Clear()
363 m_ext
= wxEmptyString
;
367 wxFileName
wxFileName::FileName(const wxString
& file
)
369 return wxFileName(file
);
373 wxFileName
wxFileName::DirName(const wxString
& dir
)
380 // ----------------------------------------------------------------------------
382 // ----------------------------------------------------------------------------
384 bool wxFileName::FileExists()
386 return wxFileName::FileExists( GetFullPath() );
389 bool wxFileName::FileExists( const wxString
&file
)
391 return ::wxFileExists( file
);
394 bool wxFileName::DirExists()
396 return wxFileName::DirExists( GetFullPath() );
399 bool wxFileName::DirExists( const wxString
&dir
)
401 return ::wxDirExists( dir
);
404 // ----------------------------------------------------------------------------
405 // CWD and HOME stuff
406 // ----------------------------------------------------------------------------
408 void wxFileName::AssignCwd(const wxString
& volume
)
410 AssignDir(wxFileName::GetCwd(volume
));
414 wxString
wxFileName::GetCwd(const wxString
& volume
)
416 // if we have the volume, we must get the current directory on this drive
417 // and to do this we have to chdir to this volume - at least under Windows,
418 // I don't know how to get the current drive on another volume elsewhere
421 if ( !volume
.empty() )
424 SetCwd(volume
+ GetVolumeSeparator());
427 wxString cwd
= ::wxGetCwd();
429 if ( !volume
.empty() )
437 bool wxFileName::SetCwd()
439 return wxFileName::SetCwd( GetFullPath() );
442 bool wxFileName::SetCwd( const wxString
&cwd
)
444 return ::wxSetWorkingDirectory( cwd
);
447 void wxFileName::AssignHomeDir()
449 AssignDir(wxFileName::GetHomeDir());
452 wxString
wxFileName::GetHomeDir()
454 return ::wxGetHomeDir();
457 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
459 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
460 if ( tempname
.empty() )
462 // error, failed to get temp file name
473 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
475 wxString path
, dir
, name
;
477 // use the directory specified by the prefix
478 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
480 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
485 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
487 wxLogLastError(_T("GetTempPath"));
492 // GetTempFileName() fails if we pass it an empty string
497 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
499 wxLogLastError(_T("GetTempFileName"));
504 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
510 #elif defined(__WXPM__)
511 // for now just create a file
513 // future enhancements can be to set some extended attributes for file
514 // systems OS/2 supports that have them (HPFS, FAT32) and security
516 static const wxChar
*szMktempSuffix
= wxT("XXX");
517 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
519 // Temporarily remove - MN
521 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
524 #else // !Windows, !OS/2
527 dir
= wxGetenv(_T("TMP"));
530 dir
= wxGetenv(_T("TEMP"));
546 if ( !wxEndsWithPathSeparator(dir
) &&
547 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
549 path
+= wxFILE_SEP_PATH
;
554 #if defined(HAVE_MKSTEMP)
555 // scratch space for mkstemp()
556 path
+= _T("XXXXXX");
558 // can use the cast here because the length doesn't change and the string
560 int fdTemp
= mkstemp((char *)path
.mb_str());
563 // this might be not necessary as mkstemp() on most systems should have
564 // already done it but it doesn't hurt neither...
567 else // mkstemp() succeeded
569 // avoid leaking the fd
572 fileTemp
->Attach(fdTemp
);
579 #else // !HAVE_MKSTEMP
583 path
+= _T("XXXXXX");
585 if ( !mktemp((char *)path
.mb_str()) )
589 #else // !HAVE_MKTEMP (includes __DOS__)
590 // generate the unique file name ourselves
592 path
<< (unsigned int)getpid();
597 static const size_t numTries
= 1000;
598 for ( size_t n
= 0; n
< numTries
; n
++ )
600 // 3 hex digits is enough for numTries == 1000 < 4096
601 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
602 if ( !wxFile::Exists(pathTry
) )
611 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
616 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
618 #endif // Windows/!Windows
622 wxLogSysError(_("Failed to create a temporary file name"));
624 else if ( fileTemp
&& !fileTemp
->IsOpened() )
626 // open the file - of course, there is a race condition here, this is
627 // why we always prefer using mkstemp()...
629 // NB: GetTempFileName() under Windows creates the file, so using
630 // write_excl there would fail
631 if ( !fileTemp
->Open(path
,
632 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
637 wxS_IRUSR
| wxS_IWUSR
) )
639 // FIXME: If !ok here should we loop and try again with another
640 // file name? That is the standard recourse if open(O_EXCL)
641 // fails, though of course it should be protected against
642 // possible infinite looping too.
644 wxLogError(_("Failed to open temporary file."));
653 // ----------------------------------------------------------------------------
654 // directory operations
655 // ----------------------------------------------------------------------------
657 bool wxFileName::Mkdir( int perm
, bool full
)
659 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
662 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
666 wxFileName
filename(dir
);
667 wxArrayString dirs
= filename
.GetDirs();
668 dirs
.Add(filename
.GetName());
670 size_t count
= dirs
.GetCount();
674 for ( i
= 0; i
< count
; i
++ )
678 if (currPath
.Last() == wxT(':'))
680 // Can't create a root directory so continue to next dir
681 currPath
+= wxFILE_SEP_PATH
;
685 if (!DirExists(currPath
))
686 if (!wxMkdir(currPath
, perm
))
689 if ( (i
< (count
-1)) )
690 currPath
+= wxFILE_SEP_PATH
;
693 return (noErrors
== 0);
697 return ::wxMkdir( dir
, perm
);
700 bool wxFileName::Rmdir()
702 return wxFileName::Rmdir( GetFullPath() );
705 bool wxFileName::Rmdir( const wxString
&dir
)
707 return ::wxRmdir( dir
);
710 // ----------------------------------------------------------------------------
711 // path normalization
712 // ----------------------------------------------------------------------------
714 bool wxFileName::Normalize(wxPathNormalize flags
,
718 // the existing path components
719 wxArrayString dirs
= GetDirs();
721 // the path to prepend in front to make the path absolute
724 format
= GetFormat(format
);
726 // make the path absolute
727 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
731 curDir
.AssignCwd(GetVolume());
735 curDir
.AssignDir(cwd
);
739 // the path may be not absolute because it doesn't have the volume name
740 // but in this case we shouldn't modify the directory components of it
741 // but just set the current volume
742 if ( !HasVolume() && curDir
.HasVolume() )
744 SetVolume(curDir
.GetVolume());
748 // yes, it was the case - we don't need curDir then
756 // handle ~ stuff under Unix only
757 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
759 if ( !dirs
.IsEmpty() )
761 wxString dir
= dirs
[0u];
762 if ( !dir
.empty() && dir
[0u] == _T('~') )
764 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
771 // transform relative path into abs one
774 wxArrayString dirsNew
= curDir
.GetDirs();
775 size_t count
= dirs
.GetCount();
776 for ( size_t n
= 0; n
< count
; n
++ )
778 dirsNew
.Add(dirs
[n
]);
784 // now deal with ".", ".." and the rest
786 size_t count
= dirs
.GetCount();
787 for ( size_t n
= 0; n
< count
; n
++ )
789 wxString dir
= dirs
[n
];
791 if ( flags
& wxPATH_NORM_DOTS
)
793 if ( dir
== wxT(".") )
799 if ( dir
== wxT("..") )
801 if ( m_dirs
.IsEmpty() )
803 wxLogError(_("The path '%s' contains too many \"..\"!"),
804 GetFullPath().c_str());
808 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
813 if ( flags
& wxPATH_NORM_ENV_VARS
)
815 dir
= wxExpandEnvVars(dir
);
818 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
826 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
828 // VZ: expand env vars here too?
834 #if defined(__WIN32__)
835 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
837 Assign(GetLongPath());
844 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
846 wxFileName
fnBase(pathBase
, format
);
848 // get cwd only once - small time saving
849 wxString cwd
= wxGetCwd();
850 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
851 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
853 bool withCase
= IsCaseSensitive(format
);
855 // we can't do anything if the files live on different volumes
856 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
862 // same drive, so we don't need our volume
865 // remove common directories starting at the top
866 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
867 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
870 fnBase
.m_dirs
.RemoveAt(0);
873 // add as many ".." as needed
874 size_t count
= fnBase
.m_dirs
.GetCount();
875 for ( size_t i
= 0; i
< count
; i
++ )
877 m_dirs
.Insert(wxT(".."), 0u);
886 // ----------------------------------------------------------------------------
887 // filename kind tests
888 // ----------------------------------------------------------------------------
890 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
892 wxFileName fn1
= *this,
895 // get cwd only once - small time saving
896 wxString cwd
= wxGetCwd();
897 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
898 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
900 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
903 // TODO: compare inodes for Unix, this works even when filenames are
904 // different but files are the same (symlinks) (VZ)
910 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
912 // only Unix filenames are truely case-sensitive
913 return GetFormat(format
) == wxPATH_UNIX
;
917 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
921 if ( (GetFormat(format
) == wxPATH_DOS
) ||
922 (GetFormat(format
) == wxPATH_VMS
) )
924 sepVol
= wxFILE_SEP_DSK
;
932 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
935 switch ( GetFormat(format
) )
938 // accept both as native APIs do but put the native one first as
939 // this is the one we use in GetFullPath()
940 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
944 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
948 seps
= wxFILE_SEP_PATH_UNIX
;
952 seps
= wxFILE_SEP_PATH_MAC
;
956 seps
= wxFILE_SEP_PATH_VMS
;
964 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
966 // wxString::Find() doesn't work as expected with NUL - it will always find
967 // it, so it is almost surely a bug if this function is called with NUL arg
968 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
970 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
973 bool wxFileName::IsWild( wxPathFormat format
)
975 // FIXME: this is probably false for Mac and this is surely wrong for most
976 // of Unix shells (think about "[...]")
978 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
981 // ----------------------------------------------------------------------------
982 // path components manipulation
983 // ----------------------------------------------------------------------------
985 void wxFileName::AppendDir( const wxString
&dir
)
990 void wxFileName::PrependDir( const wxString
&dir
)
992 m_dirs
.Insert( dir
, 0 );
995 void wxFileName::InsertDir( int before
, const wxString
&dir
)
997 m_dirs
.Insert( dir
, before
);
1000 void wxFileName::RemoveDir( int pos
)
1002 m_dirs
.Remove( (size_t)pos
);
1005 // ----------------------------------------------------------------------------
1007 // ----------------------------------------------------------------------------
1009 void wxFileName::SetFullName(const wxString
& fullname
)
1011 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1014 wxString
wxFileName::GetFullName() const
1016 wxString fullname
= m_name
;
1017 if ( !m_ext
.empty() )
1019 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1025 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1027 format
= GetFormat( format
);
1031 // the leading character
1032 if ( format
== wxPATH_MAC
&& m_relative
)
1034 fullpath
+= wxFILE_SEP_PATH_MAC
;
1036 else if ( format
== wxPATH_DOS
)
1039 fullpath
+= wxFILE_SEP_PATH_DOS
;
1041 else if ( format
== wxPATH_UNIX
)
1044 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1047 // then concatenate all the path components using the path separator
1048 size_t dirCount
= m_dirs
.GetCount();
1051 if ( format
== wxPATH_VMS
)
1053 fullpath
+= wxT('[');
1057 for ( size_t i
= 0; i
< dirCount
; i
++ )
1059 // TODO: What to do with ".." under VMS
1065 if (m_dirs
[i
] == wxT("."))
1067 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1068 fullpath
+= m_dirs
[i
];
1069 fullpath
+= wxT(':');
1074 fullpath
+= m_dirs
[i
];
1075 fullpath
+= wxT('\\');
1080 fullpath
+= m_dirs
[i
];
1081 fullpath
+= wxT('/');
1086 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1087 fullpath
+= m_dirs
[i
];
1088 if (i
== dirCount
-1)
1089 fullpath
+= wxT(']');
1091 fullpath
+= wxT('.');
1096 wxFAIL_MSG( wxT("error") );
1107 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1109 format
= GetFormat(format
);
1113 // first put the volume
1114 if ( !m_volume
.empty() )
1117 // Special Windows UNC paths hack, part 2: undo what we did in
1118 // SplitPath() and make an UNC path if we have a drive which is not a
1119 // single letter (hopefully the network shares can't be one letter only
1120 // although I didn't find any authoritative docs on this)
1121 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1123 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1125 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1127 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1133 // the leading character
1134 if ( format
== wxPATH_MAC
&& m_relative
)
1136 fullpath
+= wxFILE_SEP_PATH_MAC
;
1138 else if ( format
== wxPATH_DOS
)
1141 fullpath
+= wxFILE_SEP_PATH_DOS
;
1143 else if ( format
== wxPATH_UNIX
)
1146 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1149 // then concatenate all the path components using the path separator
1150 size_t dirCount
= m_dirs
.GetCount();
1153 if ( format
== wxPATH_VMS
)
1155 fullpath
+= wxT('[');
1159 for ( size_t i
= 0; i
< dirCount
; i
++ )
1161 // TODO: What to do with ".." under VMS
1167 if (m_dirs
[i
] == wxT("."))
1169 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1170 fullpath
+= m_dirs
[i
];
1171 fullpath
+= wxT(':');
1176 fullpath
+= m_dirs
[i
];
1177 fullpath
+= wxT('\\');
1182 fullpath
+= m_dirs
[i
];
1183 fullpath
+= wxT('/');
1188 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1189 fullpath
+= m_dirs
[i
];
1190 if (i
== dirCount
-1)
1191 fullpath
+= wxT(']');
1193 fullpath
+= wxT('.');
1198 wxFAIL_MSG( wxT("error") );
1204 // finally add the file name and extension
1205 fullpath
+= GetFullName();
1210 // Return the short form of the path (returns identity on non-Windows platforms)
1211 wxString
wxFileName::GetShortPath() const
1213 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1214 wxString
path(GetFullPath());
1216 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1220 ok
= ::GetShortPathName
1223 pathOut
.GetWriteBuf(sz
),
1226 pathOut
.UngetWriteBuf();
1233 return GetFullPath();
1237 // Return the long form of the path (returns identity on non-Windows platforms)
1238 wxString
wxFileName::GetLongPath() const
1241 path
= GetFullPath();
1243 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1244 bool success
= FALSE
;
1246 // VZ: this code was disabled, why?
1247 #if 0 // wxUSE_DYNAMIC_LOADER
1248 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1250 static bool s_triedToLoad
= FALSE
;
1252 if ( !s_triedToLoad
)
1254 s_triedToLoad
= TRUE
;
1255 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1258 // may succeed or fail depending on the Windows version
1259 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1261 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1263 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1266 wxDllLoader::UnloadLibrary(dllKernel
);
1268 if ( s_pfnGetLongPathName
)
1270 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1271 bool ok
= dwSize
> 0;
1275 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1279 ok
= (*s_pfnGetLongPathName
)
1282 pathOut
.GetWriteBuf(sz
),
1285 pathOut
.UngetWriteBuf();
1295 #endif // wxUSE_DYNAMIC_LOADER
1299 // The OS didn't support GetLongPathName, or some other error.
1300 // We need to call FindFirstFile on each component in turn.
1302 WIN32_FIND_DATA findFileData
;
1304 pathOut
= wxEmptyString
;
1306 wxArrayString dirs
= GetDirs();
1307 dirs
.Add(GetFullName());
1311 size_t count
= dirs
.GetCount();
1312 for ( size_t i
= 0; i
< count
; i
++ )
1314 // We're using pathOut to collect the long-name path, but using a
1315 // temporary for appending the last path component which may be
1317 tmpPath
= pathOut
+ dirs
[i
];
1319 if ( tmpPath
.empty() )
1322 if ( tmpPath
.Last() == wxT(':') )
1324 // Can't pass a drive and root dir to FindFirstFile,
1325 // so continue to next dir
1326 tmpPath
+= wxFILE_SEP_PATH
;
1331 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1332 if (hFind
== INVALID_HANDLE_VALUE
)
1334 // Error: return immediately with the original path
1338 pathOut
+= findFileData
.cFileName
;
1339 if ( (i
< (count
-1)) )
1340 pathOut
+= wxFILE_SEP_PATH
;
1347 #endif // Win32/!Win32
1352 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1354 if (format
== wxPATH_NATIVE
)
1356 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1357 format
= wxPATH_DOS
;
1358 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1359 format
= wxPATH_MAC
;
1360 #elif defined(__VMS)
1361 format
= wxPATH_VMS
;
1363 format
= wxPATH_UNIX
;
1369 // ----------------------------------------------------------------------------
1370 // path splitting function
1371 // ----------------------------------------------------------------------------
1374 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1375 wxString
*pstrVolume
,
1379 wxPathFormat format
)
1381 format
= GetFormat(format
);
1383 wxString fullpath
= fullpathWithVolume
;
1385 // under VMS the end of the path is ']', not the path separator used to
1386 // separate the components
1387 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1388 : GetPathSeparators(format
);
1390 // special Windows UNC paths hack: transform \\share\path into share:path
1391 if ( format
== wxPATH_DOS
)
1393 if ( fullpath
.length() >= 4 &&
1394 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1395 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1397 fullpath
.erase(0, 2);
1399 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1400 if ( posFirstSlash
!= wxString::npos
)
1402 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1404 // UNC paths are always absolute, right? (FIXME)
1405 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1410 // We separate the volume here
1411 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1413 wxString sepVol
= GetVolumeSeparator(format
);
1415 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1416 if ( posFirstColon
!= wxString::npos
)
1420 *pstrVolume
= fullpath
.Left(posFirstColon
);
1423 // remove the volume name and the separator from the full path
1424 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1428 // find the positions of the last dot and last path separator in the path
1429 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1430 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1432 if ( (posLastDot
!= wxString::npos
) &&
1433 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1435 if ( (posLastDot
== 0) ||
1436 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1438 // under Unix and VMS, dot may be (and commonly is) the first
1439 // character of the filename, don't treat the entire filename as
1440 // extension in this case
1441 posLastDot
= wxString::npos
;
1445 // if we do have a dot and a slash, check that the dot is in the name part
1446 if ( (posLastDot
!= wxString::npos
) &&
1447 (posLastSlash
!= wxString::npos
) &&
1448 (posLastDot
< posLastSlash
) )
1450 // the dot is part of the path, not the start of the extension
1451 posLastDot
= wxString::npos
;
1454 // now fill in the variables provided by user
1457 if ( posLastSlash
== wxString::npos
)
1464 // take everything up to the path separator but take care to make
1465 // the path equal to something like '/', not empty, for the files
1466 // immediately under root directory
1467 size_t len
= posLastSlash
;
1471 *pstrPath
= fullpath
.Left(len
);
1473 // special VMS hack: remove the initial bracket
1474 if ( format
== wxPATH_VMS
)
1476 if ( (*pstrPath
)[0u] == _T('[') )
1477 pstrPath
->erase(0, 1);
1484 // take all characters starting from the one after the last slash and
1485 // up to, but excluding, the last dot
1486 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1488 if ( posLastDot
== wxString::npos
)
1490 // take all until the end
1491 count
= wxString::npos
;
1493 else if ( posLastSlash
== wxString::npos
)
1497 else // have both dot and slash
1499 count
= posLastDot
- posLastSlash
- 1;
1502 *pstrName
= fullpath
.Mid(nStart
, count
);
1507 if ( posLastDot
== wxString::npos
)
1514 // take everything after the dot
1515 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1521 void wxFileName::SplitPath(const wxString
& fullpath
,
1525 wxPathFormat format
)
1528 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1530 if ( path
&& !volume
.empty() )
1532 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1536 // ----------------------------------------------------------------------------
1538 // ----------------------------------------------------------------------------
1540 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1541 const wxDateTime
*dtAccess
,
1542 const wxDateTime
*dtMod
)
1544 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1545 if ( !dtAccess
&& !dtMod
)
1547 // can't modify the creation time anyhow, don't try
1551 // if dtAccess or dtMod is not specified, use the other one (which must be
1552 // non NULL because of the test above) for both times
1554 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1555 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1556 if ( utime(GetFullPath(), &utm
) == 0 )
1560 #elif defined(__WIN32__)
1561 wxFileHandle
fh(GetFullPath());
1564 FILETIME ftAccess
, ftCreate
, ftWrite
;
1567 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1569 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1571 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1573 if ( ::SetFileTime(fh
,
1574 dtCreate
? &ftCreate
: NULL
,
1575 dtAccess
? &ftAccess
: NULL
,
1576 dtMod
? &ftWrite
: NULL
) )
1581 #else // other platform
1584 wxLogSysError(_("Failed to modify file times for '%s'"),
1585 GetFullPath().c_str());
1590 bool wxFileName::Touch()
1592 #if defined(__UNIX_LIKE__)
1593 // under Unix touching file is simple: just pass NULL to utime()
1594 if ( utime(GetFullPath(), NULL
) == 0 )
1599 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1602 #else // other platform
1603 wxDateTime dtNow
= wxDateTime::Now();
1605 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1609 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1611 wxDateTime
*dtChange
) const
1613 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1615 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1618 dtAccess
->Set(stBuf
.st_atime
);
1620 dtMod
->Set(stBuf
.st_mtime
);
1622 dtChange
->Set(stBuf
.st_ctime
);
1626 #elif defined(__WIN32__)
1627 wxFileHandle
fh(GetFullPath());
1630 FILETIME ftAccess
, ftCreate
, ftWrite
;
1632 if ( ::GetFileTime(fh
,
1633 dtMod
? &ftCreate
: NULL
,
1634 dtAccess
? &ftAccess
: NULL
,
1635 dtChange
? &ftWrite
: NULL
) )
1638 ConvertFileTimeToWx(dtMod
, ftCreate
);
1640 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1642 ConvertFileTimeToWx(dtChange
, ftWrite
);
1647 #else // other platform
1650 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1651 GetFullPath().c_str());