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()...
632 // NB: GetTempFileName() under Windows creates the file, so using
633 // write_excl there would fail
634 if ( !fileTemp
->Open(path
,
635 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
640 wxS_IRUSR
| wxS_IWUSR
) )
642 // FIXME: If !ok here should we loop and try again with another
643 // file name? That is the standard recourse if open(O_EXCL)
644 // fails, though of course it should be protected against
645 // possible infinite looping too.
647 wxLogError(_("Failed to open temporary file."));
656 // ----------------------------------------------------------------------------
657 // directory operations
658 // ----------------------------------------------------------------------------
660 bool wxFileName::Mkdir( int perm
, bool full
)
662 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
665 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
669 wxFileName
filename(dir
);
670 wxArrayString dirs
= filename
.GetDirs();
671 dirs
.Add(filename
.GetName());
673 size_t count
= dirs
.GetCount();
677 for ( i
= 0; i
< count
; i
++ )
681 if (currPath
.Last() == wxT(':'))
683 // Can't create a root directory so continue to next dir
684 currPath
+= wxFILE_SEP_PATH
;
688 if (!DirExists(currPath
))
689 if (!wxMkdir(currPath
, perm
))
692 if ( (i
< (count
-1)) )
693 currPath
+= wxFILE_SEP_PATH
;
696 return (noErrors
== 0);
700 return ::wxMkdir( dir
, perm
);
703 bool wxFileName::Rmdir()
705 return wxFileName::Rmdir( GetFullPath() );
708 bool wxFileName::Rmdir( const wxString
&dir
)
710 return ::wxRmdir( dir
);
713 // ----------------------------------------------------------------------------
714 // path normalization
715 // ----------------------------------------------------------------------------
717 bool wxFileName::Normalize(wxPathNormalize flags
,
721 // the existing path components
722 wxArrayString dirs
= GetDirs();
724 // the path to prepend in front to make the path absolute
727 format
= GetFormat(format
);
729 // make the path absolute
730 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
734 curDir
.AssignCwd(GetVolume());
738 curDir
.AssignDir(cwd
);
742 // the path may be not absolute because it doesn't have the volume name
743 // but in this case we shouldn't modify the directory components of it
744 // but just set the current volume
745 if ( !HasVolume() && curDir
.HasVolume() )
747 SetVolume(curDir
.GetVolume());
751 // yes, it was the case - we don't need curDir then
759 // handle ~ stuff under Unix only
760 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
762 if ( !dirs
.IsEmpty() )
764 wxString dir
= dirs
[0u];
765 if ( !dir
.empty() && dir
[0u] == _T('~') )
767 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
774 // transform relative path into abs one
777 wxArrayString dirsNew
= curDir
.GetDirs();
778 size_t count
= dirs
.GetCount();
779 for ( size_t n
= 0; n
< count
; n
++ )
781 dirsNew
.Add(dirs
[n
]);
787 // now deal with ".", ".." and the rest
789 size_t count
= dirs
.GetCount();
790 for ( size_t n
= 0; n
< count
; n
++ )
792 wxString dir
= dirs
[n
];
794 if ( flags
& wxPATH_NORM_DOTS
)
796 if ( dir
== wxT(".") )
802 if ( dir
== wxT("..") )
804 if ( m_dirs
.IsEmpty() )
806 wxLogError(_("The path '%s' contains too many \"..\"!"),
807 GetFullPath().c_str());
811 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
816 if ( flags
& wxPATH_NORM_ENV_VARS
)
818 dir
= wxExpandEnvVars(dir
);
821 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
829 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
831 // VZ: expand env vars here too?
837 #if defined(__WIN32__)
838 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
840 Assign(GetLongPath());
847 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
849 wxFileName
fnBase(pathBase
, format
);
851 // get cwd only once - small time saving
852 wxString cwd
= wxGetCwd();
853 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
854 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
856 bool withCase
= IsCaseSensitive(format
);
858 // we can't do anything if the files live on different volumes
859 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
865 // same drive, so we don't need our volume
868 // remove common directories starting at the top
869 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
870 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
873 fnBase
.m_dirs
.RemoveAt(0);
876 // add as many ".." as needed
877 size_t count
= fnBase
.m_dirs
.GetCount();
878 for ( size_t i
= 0; i
< count
; i
++ )
880 m_dirs
.Insert(wxT(".."), 0u);
889 // ----------------------------------------------------------------------------
890 // filename kind tests
891 // ----------------------------------------------------------------------------
893 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
895 wxFileName fn1
= *this,
898 // get cwd only once - small time saving
899 wxString cwd
= wxGetCwd();
900 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
901 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
903 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
906 // TODO: compare inodes for Unix, this works even when filenames are
907 // different but files are the same (symlinks) (VZ)
913 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
915 // only Unix filenames are truely case-sensitive
916 return GetFormat(format
) == wxPATH_UNIX
;
920 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
924 if ( (GetFormat(format
) == wxPATH_DOS
) ||
925 (GetFormat(format
) == wxPATH_VMS
) )
927 sepVol
= wxFILE_SEP_DSK
;
935 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
938 switch ( GetFormat(format
) )
941 // accept both as native APIs do but put the native one first as
942 // this is the one we use in GetFullPath()
943 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
947 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
951 seps
= wxFILE_SEP_PATH_UNIX
;
955 seps
= wxFILE_SEP_PATH_MAC
;
959 seps
= wxFILE_SEP_PATH_VMS
;
967 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
969 // wxString::Find() doesn't work as expected with NUL - it will always find
970 // it, so it is almost surely a bug if this function is called with NUL arg
971 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
973 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
976 bool wxFileName::IsWild( wxPathFormat format
)
978 // FIXME: this is probably false for Mac and this is surely wrong for most
979 // of Unix shells (think about "[...]")
981 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
984 // ----------------------------------------------------------------------------
985 // path components manipulation
986 // ----------------------------------------------------------------------------
988 void wxFileName::AppendDir( const wxString
&dir
)
993 void wxFileName::PrependDir( const wxString
&dir
)
995 m_dirs
.Insert( dir
, 0 );
998 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1000 m_dirs
.Insert( dir
, before
);
1003 void wxFileName::RemoveDir( int pos
)
1005 m_dirs
.Remove( (size_t)pos
);
1008 // ----------------------------------------------------------------------------
1010 // ----------------------------------------------------------------------------
1012 void wxFileName::SetFullName(const wxString
& fullname
)
1014 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1017 wxString
wxFileName::GetFullName() const
1019 wxString fullname
= m_name
;
1020 if ( !m_ext
.empty() )
1022 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1028 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1030 format
= GetFormat( format
);
1034 // the leading character
1035 if ( format
== wxPATH_MAC
&& m_relative
)
1037 fullpath
+= wxFILE_SEP_PATH_MAC
;
1039 else if ( format
== wxPATH_DOS
)
1042 fullpath
+= wxFILE_SEP_PATH_DOS
;
1044 else if ( format
== wxPATH_UNIX
)
1047 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1050 // then concatenate all the path components using the path separator
1051 size_t dirCount
= m_dirs
.GetCount();
1054 if ( format
== wxPATH_VMS
)
1056 fullpath
+= wxT('[');
1060 for ( size_t i
= 0; i
< dirCount
; i
++ )
1062 // TODO: What to do with ".." under VMS
1068 if (m_dirs
[i
] == wxT("."))
1070 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1071 fullpath
+= m_dirs
[i
];
1072 fullpath
+= wxT(':');
1077 fullpath
+= m_dirs
[i
];
1078 fullpath
+= wxT('\\');
1083 fullpath
+= m_dirs
[i
];
1084 fullpath
+= wxT('/');
1089 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1090 fullpath
+= m_dirs
[i
];
1091 if (i
== dirCount
-1)
1092 fullpath
+= wxT(']');
1094 fullpath
+= wxT('.');
1099 wxFAIL_MSG( wxT("error") );
1110 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1112 format
= GetFormat(format
);
1116 // first put the volume
1117 if ( !m_volume
.empty() )
1120 // Special Windows UNC paths hack, part 2: undo what we did in
1121 // SplitPath() and make an UNC path if we have a drive which is not a
1122 // single letter (hopefully the network shares can't be one letter only
1123 // although I didn't find any authoritative docs on this)
1124 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1126 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1128 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1130 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1136 // the leading character
1137 if ( format
== wxPATH_MAC
&& m_relative
)
1139 fullpath
+= wxFILE_SEP_PATH_MAC
;
1141 else if ( format
== wxPATH_DOS
)
1144 fullpath
+= wxFILE_SEP_PATH_DOS
;
1146 else if ( format
== wxPATH_UNIX
)
1149 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1152 // then concatenate all the path components using the path separator
1153 size_t dirCount
= m_dirs
.GetCount();
1156 if ( format
== wxPATH_VMS
)
1158 fullpath
+= wxT('[');
1162 for ( size_t i
= 0; i
< dirCount
; i
++ )
1164 // TODO: What to do with ".." under VMS
1170 if (m_dirs
[i
] == wxT("."))
1172 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1173 fullpath
+= m_dirs
[i
];
1174 fullpath
+= wxT(':');
1179 fullpath
+= m_dirs
[i
];
1180 fullpath
+= wxT('\\');
1185 fullpath
+= m_dirs
[i
];
1186 fullpath
+= wxT('/');
1191 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1192 fullpath
+= m_dirs
[i
];
1193 if (i
== dirCount
-1)
1194 fullpath
+= wxT(']');
1196 fullpath
+= wxT('.');
1201 wxFAIL_MSG( wxT("error") );
1207 // finally add the file name and extension
1208 fullpath
+= GetFullName();
1213 // Return the short form of the path (returns identity on non-Windows platforms)
1214 wxString
wxFileName::GetShortPath() const
1216 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1217 wxString
path(GetFullPath());
1219 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1223 ok
= ::GetShortPathName
1226 pathOut
.GetWriteBuf(sz
),
1229 pathOut
.UngetWriteBuf();
1236 return GetFullPath();
1240 // Return the long form of the path (returns identity on non-Windows platforms)
1241 wxString
wxFileName::GetLongPath() const
1244 path
= GetFullPath();
1246 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1247 bool success
= FALSE
;
1249 // VZ: this code was disabled, why?
1250 #if 0 // wxUSE_DYNAMIC_LOADER
1251 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1253 static bool s_triedToLoad
= FALSE
;
1255 if ( !s_triedToLoad
)
1257 s_triedToLoad
= TRUE
;
1258 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1261 // may succeed or fail depending on the Windows version
1262 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1264 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1266 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1269 wxDllLoader::UnloadLibrary(dllKernel
);
1271 if ( s_pfnGetLongPathName
)
1273 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1274 bool ok
= dwSize
> 0;
1278 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1282 ok
= (*s_pfnGetLongPathName
)
1285 pathOut
.GetWriteBuf(sz
),
1288 pathOut
.UngetWriteBuf();
1298 #endif // wxUSE_DYNAMIC_LOADER
1302 // The OS didn't support GetLongPathName, or some other error.
1303 // We need to call FindFirstFile on each component in turn.
1305 WIN32_FIND_DATA findFileData
;
1307 pathOut
= wxEmptyString
;
1309 wxArrayString dirs
= GetDirs();
1310 dirs
.Add(GetFullName());
1314 size_t count
= dirs
.GetCount();
1315 for ( size_t i
= 0; i
< count
; i
++ )
1317 // We're using pathOut to collect the long-name path, but using a
1318 // temporary for appending the last path component which may be
1320 tmpPath
= pathOut
+ dirs
[i
];
1322 if ( tmpPath
.empty() )
1325 if ( tmpPath
.Last() == wxT(':') )
1327 // Can't pass a drive and root dir to FindFirstFile,
1328 // so continue to next dir
1329 tmpPath
+= wxFILE_SEP_PATH
;
1334 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1335 if (hFind
== INVALID_HANDLE_VALUE
)
1337 // Error: return immediately with the original path
1341 pathOut
+= findFileData
.cFileName
;
1342 if ( (i
< (count
-1)) )
1343 pathOut
+= wxFILE_SEP_PATH
;
1350 #endif // Win32/!Win32
1355 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1357 if (format
== wxPATH_NATIVE
)
1359 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1360 format
= wxPATH_DOS
;
1361 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1362 format
= wxPATH_MAC
;
1363 #elif defined(__VMS)
1364 format
= wxPATH_VMS
;
1366 format
= wxPATH_UNIX
;
1372 // ----------------------------------------------------------------------------
1373 // path splitting function
1374 // ----------------------------------------------------------------------------
1377 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1378 wxString
*pstrVolume
,
1382 wxPathFormat format
)
1384 format
= GetFormat(format
);
1386 wxString fullpath
= fullpathWithVolume
;
1388 // under VMS the end of the path is ']', not the path separator used to
1389 // separate the components
1390 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1391 : GetPathSeparators(format
);
1393 // special Windows UNC paths hack: transform \\share\path into share:path
1394 if ( format
== wxPATH_DOS
)
1396 if ( fullpath
.length() >= 4 &&
1397 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1398 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1400 fullpath
.erase(0, 2);
1402 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1403 if ( posFirstSlash
!= wxString::npos
)
1405 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1407 // UNC paths are always absolute, right? (FIXME)
1408 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1413 // We separate the volume here
1414 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1416 wxString sepVol
= GetVolumeSeparator(format
);
1418 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1419 if ( posFirstColon
!= wxString::npos
)
1423 *pstrVolume
= fullpath
.Left(posFirstColon
);
1426 // remove the volume name and the separator from the full path
1427 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1431 // find the positions of the last dot and last path separator in the path
1432 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1433 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1435 if ( (posLastDot
!= wxString::npos
) &&
1436 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1438 if ( (posLastDot
== 0) ||
1439 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1441 // under Unix and VMS, dot may be (and commonly is) the first
1442 // character of the filename, don't treat the entire filename as
1443 // extension in this case
1444 posLastDot
= wxString::npos
;
1448 // if we do have a dot and a slash, check that the dot is in the name part
1449 if ( (posLastDot
!= wxString::npos
) &&
1450 (posLastSlash
!= wxString::npos
) &&
1451 (posLastDot
< posLastSlash
) )
1453 // the dot is part of the path, not the start of the extension
1454 posLastDot
= wxString::npos
;
1457 // now fill in the variables provided by user
1460 if ( posLastSlash
== wxString::npos
)
1467 // take everything up to the path separator but take care to make
1468 // the path equal to something like '/', not empty, for the files
1469 // immediately under root directory
1470 size_t len
= posLastSlash
;
1474 *pstrPath
= fullpath
.Left(len
);
1476 // special VMS hack: remove the initial bracket
1477 if ( format
== wxPATH_VMS
)
1479 if ( (*pstrPath
)[0u] == _T('[') )
1480 pstrPath
->erase(0, 1);
1487 // take all characters starting from the one after the last slash and
1488 // up to, but excluding, the last dot
1489 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1491 if ( posLastDot
== wxString::npos
)
1493 // take all until the end
1494 count
= wxString::npos
;
1496 else if ( posLastSlash
== wxString::npos
)
1500 else // have both dot and slash
1502 count
= posLastDot
- posLastSlash
- 1;
1505 *pstrName
= fullpath
.Mid(nStart
, count
);
1510 if ( posLastDot
== wxString::npos
)
1517 // take everything after the dot
1518 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1524 void wxFileName::SplitPath(const wxString
& fullpath
,
1528 wxPathFormat format
)
1531 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1533 if ( path
&& !volume
.empty() )
1535 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1539 // ----------------------------------------------------------------------------
1541 // ----------------------------------------------------------------------------
1543 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1544 const wxDateTime
*dtAccess
,
1545 const wxDateTime
*dtMod
)
1547 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1548 if ( !dtAccess
&& !dtMod
)
1550 // can't modify the creation time anyhow, don't try
1554 // if dtAccess or dtMod is not specified, use the other one (which must be
1555 // non NULL because of the test above) for both times
1557 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1558 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1559 if ( utime(GetFullPath(), &utm
) == 0 )
1563 #elif defined(__WIN32__)
1564 wxFileHandle
fh(GetFullPath());
1567 FILETIME ftAccess
, ftCreate
, ftWrite
;
1570 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1572 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1574 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1576 if ( ::SetFileTime(fh
,
1577 dtCreate
? &ftCreate
: NULL
,
1578 dtAccess
? &ftAccess
: NULL
,
1579 dtMod
? &ftWrite
: NULL
) )
1584 #else // other platform
1587 wxLogSysError(_("Failed to modify file times for '%s'"),
1588 GetFullPath().c_str());
1593 bool wxFileName::Touch()
1595 #if defined(__UNIX_LIKE__)
1596 // under Unix touching file is simple: just pass NULL to utime()
1597 if ( utime(GetFullPath(), NULL
) == 0 )
1602 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1605 #else // other platform
1606 wxDateTime dtNow
= wxDateTime::Now();
1608 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1612 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1614 wxDateTime
*dtChange
) const
1616 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1618 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1621 dtAccess
->Set(stBuf
.st_atime
);
1623 dtMod
->Set(stBuf
.st_mtime
);
1625 dtChange
->Set(stBuf
.st_ctime
);
1629 #elif defined(__WIN32__)
1630 wxFileHandle
fh(GetFullPath());
1633 FILETIME ftAccess
, ftCreate
, ftWrite
;
1635 if ( ::GetFileTime(fh
,
1636 dtMod
? &ftCreate
: NULL
,
1637 dtAccess
? &ftAccess
: NULL
,
1638 dtChange
? &ftWrite
: NULL
) )
1641 ConvertFileTimeToWx(dtMod
, ftCreate
);
1643 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1645 ConvertFileTimeToWx(dtChange
, ftWrite
);
1650 #else // other platform
1653 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1654 GetFullPath().c_str());