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>
113 #include <sys/utime.h>
114 #include <sys/stat.h>
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 // small helper class which opens and closes the file - we use it just to get
128 // a file handle for the given file name to pass it to some Win32 API function
129 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
134 wxFileHandle(const wxString
& filename
)
136 m_hFile
= ::CreateFile
139 GENERIC_READ
, // access mask
141 NULL
, // no secutity attr
142 OPEN_EXISTING
, // creation disposition
144 NULL
// no template file
147 if ( m_hFile
== INVALID_HANDLE_VALUE
)
149 wxLogSysError(_("Failed to open '%s' for reading"),
156 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
158 if ( !::CloseHandle(m_hFile
) )
160 wxLogSysError(_("Failed to close file handle"));
165 // return TRUE only if the file could be opened successfully
166 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
169 operator HANDLE() const { return m_hFile
; }
177 // ----------------------------------------------------------------------------
179 // ----------------------------------------------------------------------------
181 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
183 // convert between wxDateTime and FILETIME which is a 64-bit value representing
184 // the number of 100-nanosecond intervals since January 1, 1601.
186 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
187 // FILETIME reference point (January 1, 1601)
188 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
190 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
192 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
194 // convert 100ns to ms
197 // move it to our Epoch
198 ll
-= FILETIME_EPOCH_OFFSET
;
200 *dt
= wxDateTime(ll
);
203 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
205 // do the reverse of ConvertFileTimeToWx()
206 wxLongLong ll
= dt
.GetValue();
208 ll
+= FILETIME_EPOCH_OFFSET
;
210 ft
->dwHighDateTime
= ll
.GetHi();
211 ft
->dwLowDateTime
= ll
.GetLo();
216 // ============================================================================
218 // ============================================================================
220 // ----------------------------------------------------------------------------
221 // wxFileName construction
222 // ----------------------------------------------------------------------------
224 void wxFileName::Assign( const wxFileName
&filepath
)
226 m_volume
= filepath
.GetVolume();
227 m_dirs
= filepath
.GetDirs();
228 m_name
= filepath
.GetName();
229 m_ext
= filepath
.GetExt();
230 m_relative
= filepath
.IsRelative();
233 void wxFileName::Assign(const wxString
& volume
,
234 const wxString
& path
,
235 const wxString
& name
,
237 wxPathFormat format
)
239 SetPath( path
, format
);
246 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
248 wxPathFormat my_format
= GetFormat( format
);
249 wxString my_path
= path
;
253 if (!my_path
.empty())
255 // 1) Determine if the path is relative or absolute.
260 m_relative
= ( my_path
[0u] == wxT(':') );
261 // We then remove a leading ":". The reason is in our
262 // storage form for relative paths:
263 // ":dir:file.txt" actually means "./dir/file.txt" in
264 // DOS notation and should get stored as
265 // (relative) (dir) (file.txt)
266 // "::dir:file.txt" actually means "../dir/file.txt"
267 // stored as (relative) (..) (dir) (file.txt)
268 // This is important only for the Mac as an empty dir
269 // actually means <UP>, whereas under DOS, double
270 // slashes can be ignored: "\\\\" is the same as "\\".
272 my_path
.Remove( 0, 1 );
275 // TODO: what is the relative path format here?
279 m_relative
= ( my_path
[0u] != wxT('/') );
282 m_relative
= ( (my_path
[0u] != wxT('/')) && (my_path
[0u] != wxT('\\')) );
285 wxFAIL_MSG( wxT("error") );
289 // 2) Break up the path into its members. If the original path
290 // was just "/" or "\\", m_dirs will be empty. We know from
291 // the m_relative field, if this means "nothing" or "root dir".
293 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
295 while ( tn
.HasMoreTokens() )
297 wxString token
= tn
.GetNextToken();
299 // Remove empty token under DOS and Unix, interpret them
303 if (my_format
== wxPATH_MAC
)
304 m_dirs
.Add( wxT("..") );
319 void wxFileName::Assign(const wxString
& fullpath
,
322 wxString volume
, path
, name
, ext
;
323 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
325 Assign(volume
, path
, name
, ext
, format
);
328 void wxFileName::Assign(const wxString
& fullpathOrig
,
329 const wxString
& fullname
,
332 // always recognize fullpath as directory, even if it doesn't end with a
334 wxString fullpath
= fullpathOrig
;
335 if ( !wxEndsWithPathSeparator(fullpath
) )
337 fullpath
+= GetPathSeparators(format
)[0u];
340 wxString volume
, path
, name
, ext
;
342 // do some consistency checks in debug mode: the name should be really just
343 // the filename and the path should be really just a path
345 wxString pathDummy
, nameDummy
, extDummy
;
347 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
349 wxASSERT_MSG( pathDummy
.empty(),
350 _T("the file name shouldn't contain the path") );
352 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
354 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
355 _T("the path shouldn't contain file name nor extension") );
357 #else // !__WXDEBUG__
358 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
359 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
360 #endif // __WXDEBUG__/!__WXDEBUG__
362 Assign(volume
, path
, name
, ext
, format
);
365 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
367 Assign(dir
, _T(""), format
);
370 void wxFileName::Clear()
376 m_ext
= wxEmptyString
;
380 wxFileName
wxFileName::FileName(const wxString
& file
)
382 return wxFileName(file
);
386 wxFileName
wxFileName::DirName(const wxString
& dir
)
393 // ----------------------------------------------------------------------------
395 // ----------------------------------------------------------------------------
397 bool wxFileName::FileExists()
399 return wxFileName::FileExists( GetFullPath() );
402 bool wxFileName::FileExists( const wxString
&file
)
404 return ::wxFileExists( file
);
407 bool wxFileName::DirExists()
409 return wxFileName::DirExists( GetFullPath() );
412 bool wxFileName::DirExists( const wxString
&dir
)
414 return ::wxDirExists( dir
);
417 // ----------------------------------------------------------------------------
418 // CWD and HOME stuff
419 // ----------------------------------------------------------------------------
421 void wxFileName::AssignCwd(const wxString
& volume
)
423 AssignDir(wxFileName::GetCwd(volume
));
427 wxString
wxFileName::GetCwd(const wxString
& volume
)
429 // if we have the volume, we must get the current directory on this drive
430 // and to do this we have to chdir to this volume - at least under Windows,
431 // I don't know how to get the current drive on another volume elsewhere
434 if ( !volume
.empty() )
437 SetCwd(volume
+ GetVolumeSeparator());
440 wxString cwd
= ::wxGetCwd();
442 if ( !volume
.empty() )
450 bool wxFileName::SetCwd()
452 return wxFileName::SetCwd( GetFullPath() );
455 bool wxFileName::SetCwd( const wxString
&cwd
)
457 return ::wxSetWorkingDirectory( cwd
);
460 void wxFileName::AssignHomeDir()
462 AssignDir(wxFileName::GetHomeDir());
465 wxString
wxFileName::GetHomeDir()
467 return ::wxGetHomeDir();
470 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
472 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
473 if ( tempname
.empty() )
475 // error, failed to get temp file name
486 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
488 wxString path
, dir
, name
;
490 // use the directory specified by the prefix
491 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
493 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
498 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
500 wxLogLastError(_T("GetTempPath"));
505 // GetTempFileName() fails if we pass it an empty string
510 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
512 wxLogLastError(_T("GetTempFileName"));
517 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
523 #elif defined(__WXPM__)
524 // for now just create a file
526 // future enhancements can be to set some extended attributes for file
527 // systems OS/2 supports that have them (HPFS, FAT32) and security
529 static const wxChar
*szMktempSuffix
= wxT("XXX");
530 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
532 // Temporarily remove - MN
534 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
537 #else // !Windows, !OS/2
540 dir
= wxGetenv(_T("TMP"));
543 dir
= wxGetenv(_T("TEMP"));
559 if ( !wxEndsWithPathSeparator(dir
) &&
560 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
562 path
+= wxFILE_SEP_PATH
;
567 #if defined(HAVE_MKSTEMP)
568 // scratch space for mkstemp()
569 path
+= _T("XXXXXX");
571 // can use the cast here because the length doesn't change and the string
573 int fdTemp
= mkstemp((char *)path
.mb_str());
576 // this might be not necessary as mkstemp() on most systems should have
577 // already done it but it doesn't hurt neither...
580 else // mkstemp() succeeded
582 // avoid leaking the fd
585 fileTemp
->Attach(fdTemp
);
592 #else // !HAVE_MKSTEMP
596 path
+= _T("XXXXXX");
598 if ( !mktemp((char *)path
.mb_str()) )
602 #else // !HAVE_MKTEMP (includes __DOS__)
603 // generate the unique file name ourselves
605 path
<< (unsigned int)getpid();
610 static const size_t numTries
= 1000;
611 for ( size_t n
= 0; n
< numTries
; n
++ )
613 // 3 hex digits is enough for numTries == 1000 < 4096
614 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
615 if ( !wxFile::Exists(pathTry
) )
624 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
629 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
631 #endif // Windows/!Windows
635 wxLogSysError(_("Failed to create a temporary file name"));
637 else if ( fileTemp
&& !fileTemp
->IsOpened() )
639 // open the file - of course, there is a race condition here, this is
640 // why we always prefer using mkstemp()...
642 // NB: GetTempFileName() under Windows creates the file, so using
643 // write_excl there would fail
644 if ( !fileTemp
->Open(path
,
645 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
650 wxS_IRUSR
| wxS_IWUSR
) )
652 // FIXME: If !ok here should we loop and try again with another
653 // file name? That is the standard recourse if open(O_EXCL)
654 // fails, though of course it should be protected against
655 // possible infinite looping too.
657 wxLogError(_("Failed to open temporary file."));
666 // ----------------------------------------------------------------------------
667 // directory operations
668 // ----------------------------------------------------------------------------
670 bool wxFileName::Mkdir( int perm
, bool full
)
672 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
675 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
679 wxFileName
filename(dir
);
680 wxArrayString dirs
= filename
.GetDirs();
681 dirs
.Add(filename
.GetName());
683 size_t count
= dirs
.GetCount();
687 for ( i
= 0; i
< count
; i
++ )
691 if (currPath
.Last() == wxT(':'))
693 // Can't create a root directory so continue to next dir
694 currPath
+= wxFILE_SEP_PATH
;
698 if (!DirExists(currPath
))
699 if (!wxMkdir(currPath
, perm
))
702 if ( (i
< (count
-1)) )
703 currPath
+= wxFILE_SEP_PATH
;
706 return (noErrors
== 0);
710 return ::wxMkdir( dir
, perm
);
713 bool wxFileName::Rmdir()
715 return wxFileName::Rmdir( GetFullPath() );
718 bool wxFileName::Rmdir( const wxString
&dir
)
720 return ::wxRmdir( dir
);
723 // ----------------------------------------------------------------------------
724 // path normalization
725 // ----------------------------------------------------------------------------
727 bool wxFileName::Normalize(wxPathNormalize flags
,
731 // the existing path components
732 wxArrayString dirs
= GetDirs();
734 // the path to prepend in front to make the path absolute
737 format
= GetFormat(format
);
739 // make the path absolute
740 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
744 curDir
.AssignCwd(GetVolume());
748 curDir
.AssignDir(cwd
);
752 // the path may be not absolute because it doesn't have the volume name
753 // but in this case we shouldn't modify the directory components of it
754 // but just set the current volume
755 if ( !HasVolume() && curDir
.HasVolume() )
757 SetVolume(curDir
.GetVolume());
761 // yes, it was the case - we don't need curDir then
769 // handle ~ stuff under Unix only
770 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
772 if ( !dirs
.IsEmpty() )
774 wxString dir
= dirs
[0u];
775 if ( !dir
.empty() && dir
[0u] == _T('~') )
777 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
784 // transform relative path into abs one
787 wxArrayString dirsNew
= curDir
.GetDirs();
788 size_t count
= dirs
.GetCount();
789 for ( size_t n
= 0; n
< count
; n
++ )
791 dirsNew
.Add(dirs
[n
]);
797 // now deal with ".", ".." and the rest
799 size_t count
= dirs
.GetCount();
800 for ( size_t n
= 0; n
< count
; n
++ )
802 wxString dir
= dirs
[n
];
804 if ( flags
& wxPATH_NORM_DOTS
)
806 if ( dir
== wxT(".") )
812 if ( dir
== wxT("..") )
814 if ( m_dirs
.IsEmpty() )
816 wxLogError(_("The path '%s' contains too many \"..\"!"),
817 GetFullPath().c_str());
821 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
826 if ( flags
& wxPATH_NORM_ENV_VARS
)
828 dir
= wxExpandEnvVars(dir
);
831 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
839 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
841 // VZ: expand env vars here too?
847 #if defined(__WIN32__)
848 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
850 Assign(GetLongPath());
857 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
859 wxFileName
fnBase(pathBase
, format
);
861 // get cwd only once - small time saving
862 wxString cwd
= wxGetCwd();
863 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
864 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
866 bool withCase
= IsCaseSensitive(format
);
868 // we can't do anything if the files live on different volumes
869 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
875 // same drive, so we don't need our volume
878 // remove common directories starting at the top
879 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
880 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
883 fnBase
.m_dirs
.RemoveAt(0);
886 // add as many ".." as needed
887 size_t count
= fnBase
.m_dirs
.GetCount();
888 for ( size_t i
= 0; i
< count
; i
++ )
890 m_dirs
.Insert(wxT(".."), 0u);
899 // ----------------------------------------------------------------------------
900 // filename kind tests
901 // ----------------------------------------------------------------------------
903 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
905 wxFileName fn1
= *this,
908 // get cwd only once - small time saving
909 wxString cwd
= wxGetCwd();
910 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
911 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
913 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
916 // TODO: compare inodes for Unix, this works even when filenames are
917 // different but files are the same (symlinks) (VZ)
923 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
925 // only Unix filenames are truely case-sensitive
926 return GetFormat(format
) == wxPATH_UNIX
;
930 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
934 if ( (GetFormat(format
) == wxPATH_DOS
) ||
935 (GetFormat(format
) == wxPATH_VMS
) )
937 sepVol
= wxFILE_SEP_DSK
;
945 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
948 switch ( GetFormat(format
) )
951 // accept both as native APIs do but put the native one first as
952 // this is the one we use in GetFullPath()
953 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
957 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
961 seps
= wxFILE_SEP_PATH_UNIX
;
965 seps
= wxFILE_SEP_PATH_MAC
;
969 seps
= wxFILE_SEP_PATH_VMS
;
977 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
979 // wxString::Find() doesn't work as expected with NUL - it will always find
980 // it, so it is almost surely a bug if this function is called with NUL arg
981 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
983 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
986 bool wxFileName::IsWild( wxPathFormat format
)
988 // FIXME: this is probably false for Mac and this is surely wrong for most
989 // of Unix shells (think about "[...]")
991 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
994 // ----------------------------------------------------------------------------
995 // path components manipulation
996 // ----------------------------------------------------------------------------
998 void wxFileName::AppendDir( const wxString
&dir
)
1003 void wxFileName::PrependDir( const wxString
&dir
)
1005 m_dirs
.Insert( dir
, 0 );
1008 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1010 m_dirs
.Insert( dir
, before
);
1013 void wxFileName::RemoveDir( int pos
)
1015 m_dirs
.Remove( (size_t)pos
);
1018 // ----------------------------------------------------------------------------
1020 // ----------------------------------------------------------------------------
1022 void wxFileName::SetFullName(const wxString
& fullname
)
1024 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1027 wxString
wxFileName::GetFullName() const
1029 wxString fullname
= m_name
;
1030 if ( !m_ext
.empty() )
1032 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1038 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1040 format
= GetFormat( format
);
1044 // the leading character
1045 if ( format
== wxPATH_MAC
&& m_relative
)
1047 fullpath
+= wxFILE_SEP_PATH_MAC
;
1049 else if ( format
== wxPATH_DOS
)
1052 fullpath
+= wxFILE_SEP_PATH_DOS
;
1054 else if ( format
== wxPATH_UNIX
)
1057 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1060 // then concatenate all the path components using the path separator
1061 size_t dirCount
= m_dirs
.GetCount();
1064 if ( format
== wxPATH_VMS
)
1066 fullpath
+= wxT('[');
1070 for ( size_t i
= 0; i
< dirCount
; i
++ )
1072 // TODO: What to do with ".." under VMS
1078 if (m_dirs
[i
] == wxT("."))
1080 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1081 fullpath
+= m_dirs
[i
];
1082 fullpath
+= wxT(':');
1087 fullpath
+= m_dirs
[i
];
1088 fullpath
+= wxT('\\');
1093 fullpath
+= m_dirs
[i
];
1094 fullpath
+= wxT('/');
1099 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1100 fullpath
+= m_dirs
[i
];
1101 if (i
== dirCount
-1)
1102 fullpath
+= wxT(']');
1104 fullpath
+= wxT('.');
1109 wxFAIL_MSG( wxT("error") );
1120 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1122 format
= GetFormat(format
);
1126 // first put the volume
1127 if ( !m_volume
.empty() )
1130 // Special Windows UNC paths hack, part 2: undo what we did in
1131 // SplitPath() and make an UNC path if we have a drive which is not a
1132 // single letter (hopefully the network shares can't be one letter only
1133 // although I didn't find any authoritative docs on this)
1134 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1136 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1138 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1140 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1146 // the leading character
1147 if ( format
== wxPATH_MAC
&& m_relative
)
1149 fullpath
+= wxFILE_SEP_PATH_MAC
;
1151 else if ( format
== wxPATH_DOS
)
1154 fullpath
+= wxFILE_SEP_PATH_DOS
;
1156 else if ( format
== wxPATH_UNIX
)
1159 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1162 // then concatenate all the path components using the path separator
1163 size_t dirCount
= m_dirs
.GetCount();
1166 if ( format
== wxPATH_VMS
)
1168 fullpath
+= wxT('[');
1172 for ( size_t i
= 0; i
< dirCount
; i
++ )
1174 // TODO: What to do with ".." under VMS
1180 if (m_dirs
[i
] == wxT("."))
1182 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1183 fullpath
+= m_dirs
[i
];
1184 fullpath
+= wxT(':');
1189 fullpath
+= m_dirs
[i
];
1190 fullpath
+= wxT('\\');
1195 fullpath
+= m_dirs
[i
];
1196 fullpath
+= wxT('/');
1201 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1202 fullpath
+= m_dirs
[i
];
1203 if (i
== dirCount
-1)
1204 fullpath
+= wxT(']');
1206 fullpath
+= wxT('.');
1211 wxFAIL_MSG( wxT("error") );
1217 // finally add the file name and extension
1218 fullpath
+= GetFullName();
1223 // Return the short form of the path (returns identity on non-Windows platforms)
1224 wxString
wxFileName::GetShortPath() const
1226 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1227 wxString
path(GetFullPath());
1229 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1233 ok
= ::GetShortPathName
1236 pathOut
.GetWriteBuf(sz
),
1239 pathOut
.UngetWriteBuf();
1246 return GetFullPath();
1250 // Return the long form of the path (returns identity on non-Windows platforms)
1251 wxString
wxFileName::GetLongPath() const
1254 path
= GetFullPath();
1256 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1257 bool success
= FALSE
;
1259 // VZ: this code was disabled, why?
1260 #if 0 // wxUSE_DYNAMIC_LOADER
1261 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1263 static bool s_triedToLoad
= FALSE
;
1265 if ( !s_triedToLoad
)
1267 s_triedToLoad
= TRUE
;
1268 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1271 // may succeed or fail depending on the Windows version
1272 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1274 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1276 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1279 wxDllLoader::UnloadLibrary(dllKernel
);
1281 if ( s_pfnGetLongPathName
)
1283 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1284 bool ok
= dwSize
> 0;
1288 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1292 ok
= (*s_pfnGetLongPathName
)
1295 pathOut
.GetWriteBuf(sz
),
1298 pathOut
.UngetWriteBuf();
1308 #endif // wxUSE_DYNAMIC_LOADER
1312 // The OS didn't support GetLongPathName, or some other error.
1313 // We need to call FindFirstFile on each component in turn.
1315 WIN32_FIND_DATA findFileData
;
1317 pathOut
= wxEmptyString
;
1319 wxArrayString dirs
= GetDirs();
1320 dirs
.Add(GetFullName());
1324 size_t count
= dirs
.GetCount();
1325 for ( size_t i
= 0; i
< count
; i
++ )
1327 // We're using pathOut to collect the long-name path, but using a
1328 // temporary for appending the last path component which may be
1330 tmpPath
= pathOut
+ dirs
[i
];
1332 if ( tmpPath
.empty() )
1335 if ( tmpPath
.Last() == wxT(':') )
1337 // Can't pass a drive and root dir to FindFirstFile,
1338 // so continue to next dir
1339 tmpPath
+= wxFILE_SEP_PATH
;
1344 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1345 if (hFind
== INVALID_HANDLE_VALUE
)
1347 // Error: return immediately with the original path
1351 pathOut
+= findFileData
.cFileName
;
1352 if ( (i
< (count
-1)) )
1353 pathOut
+= wxFILE_SEP_PATH
;
1360 #endif // Win32/!Win32
1365 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1367 if (format
== wxPATH_NATIVE
)
1369 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1370 format
= wxPATH_DOS
;
1371 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1372 format
= wxPATH_MAC
;
1373 #elif defined(__VMS)
1374 format
= wxPATH_VMS
;
1376 format
= wxPATH_UNIX
;
1382 // ----------------------------------------------------------------------------
1383 // path splitting function
1384 // ----------------------------------------------------------------------------
1387 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1388 wxString
*pstrVolume
,
1392 wxPathFormat format
)
1394 format
= GetFormat(format
);
1396 wxString fullpath
= fullpathWithVolume
;
1398 // under VMS the end of the path is ']', not the path separator used to
1399 // separate the components
1400 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1401 : GetPathSeparators(format
);
1403 // special Windows UNC paths hack: transform \\share\path into share:path
1404 if ( format
== wxPATH_DOS
)
1406 if ( fullpath
.length() >= 4 &&
1407 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1408 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1410 fullpath
.erase(0, 2);
1412 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1413 if ( posFirstSlash
!= wxString::npos
)
1415 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1417 // UNC paths are always absolute, right? (FIXME)
1418 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1423 // We separate the volume here
1424 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1426 wxString sepVol
= GetVolumeSeparator(format
);
1428 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1429 if ( posFirstColon
!= wxString::npos
)
1433 *pstrVolume
= fullpath
.Left(posFirstColon
);
1436 // remove the volume name and the separator from the full path
1437 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1441 // find the positions of the last dot and last path separator in the path
1442 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1443 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1445 if ( (posLastDot
!= wxString::npos
) &&
1446 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1448 if ( (posLastDot
== 0) ||
1449 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1451 // under Unix and VMS, dot may be (and commonly is) the first
1452 // character of the filename, don't treat the entire filename as
1453 // extension in this case
1454 posLastDot
= wxString::npos
;
1458 // if we do have a dot and a slash, check that the dot is in the name part
1459 if ( (posLastDot
!= wxString::npos
) &&
1460 (posLastSlash
!= wxString::npos
) &&
1461 (posLastDot
< posLastSlash
) )
1463 // the dot is part of the path, not the start of the extension
1464 posLastDot
= wxString::npos
;
1467 // now fill in the variables provided by user
1470 if ( posLastSlash
== wxString::npos
)
1477 // take everything up to the path separator but take care to make
1478 // the path equal to something like '/', not empty, for the files
1479 // immediately under root directory
1480 size_t len
= posLastSlash
;
1484 *pstrPath
= fullpath
.Left(len
);
1486 // special VMS hack: remove the initial bracket
1487 if ( format
== wxPATH_VMS
)
1489 if ( (*pstrPath
)[0u] == _T('[') )
1490 pstrPath
->erase(0, 1);
1497 // take all characters starting from the one after the last slash and
1498 // up to, but excluding, the last dot
1499 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1501 if ( posLastDot
== wxString::npos
)
1503 // take all until the end
1504 count
= wxString::npos
;
1506 else if ( posLastSlash
== wxString::npos
)
1510 else // have both dot and slash
1512 count
= posLastDot
- posLastSlash
- 1;
1515 *pstrName
= fullpath
.Mid(nStart
, count
);
1520 if ( posLastDot
== wxString::npos
)
1527 // take everything after the dot
1528 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1534 void wxFileName::SplitPath(const wxString
& fullpath
,
1538 wxPathFormat format
)
1541 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1543 if ( path
&& !volume
.empty() )
1545 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1549 // ----------------------------------------------------------------------------
1551 // ----------------------------------------------------------------------------
1553 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1554 const wxDateTime
*dtAccess
,
1555 const wxDateTime
*dtMod
)
1557 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1558 if ( !dtAccess
&& !dtMod
)
1560 // can't modify the creation time anyhow, don't try
1564 // if dtAccess or dtMod is not specified, use the other one (which must be
1565 // non NULL because of the test above) for both times
1567 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1568 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1569 if ( utime(GetFullPath(), &utm
) == 0 )
1573 #elif defined(__WIN32__)
1574 wxFileHandle
fh(GetFullPath());
1577 FILETIME ftAccess
, ftCreate
, ftWrite
;
1580 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1582 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1584 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1586 if ( ::SetFileTime(fh
,
1587 dtCreate
? &ftCreate
: NULL
,
1588 dtAccess
? &ftAccess
: NULL
,
1589 dtMod
? &ftWrite
: NULL
) )
1594 #else // other platform
1597 wxLogSysError(_("Failed to modify file times for '%s'"),
1598 GetFullPath().c_str());
1603 bool wxFileName::Touch()
1605 #if defined(__UNIX_LIKE__)
1606 // under Unix touching file is simple: just pass NULL to utime()
1607 if ( utime(GetFullPath(), NULL
) == 0 )
1612 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1615 #else // other platform
1616 wxDateTime dtNow
= wxDateTime::Now();
1618 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1622 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1624 wxDateTime
*dtChange
) const
1626 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1628 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1631 dtAccess
->Set(stBuf
.st_atime
);
1633 dtMod
->Set(stBuf
.st_mtime
);
1635 dtChange
->Set(stBuf
.st_ctime
);
1639 #elif defined(__WIN32__)
1640 wxFileHandle
fh(GetFullPath());
1643 FILETIME ftAccess
, ftCreate
, ftWrite
;
1645 if ( ::GetFileTime(fh
,
1646 dtMod
? &ftCreate
: NULL
,
1647 dtAccess
? &ftAccess
: NULL
,
1648 dtChange
? &ftWrite
: NULL
) )
1651 ConvertFileTimeToWx(dtMod
, ftCreate
);
1653 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1655 ConvertFileTimeToWx(dtChange
, ftWrite
);
1660 #else // other platform
1663 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1664 GetFullPath().c_str());