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 SetPath( path
, format
);
242 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
244 wxPathFormat my_format
= GetFormat( format
);
245 wxString my_path
= path
;
249 if (!my_path
.empty())
251 // 1) Determine if the path is relative or absolute.
256 m_relative
= ( my_path
[0u] == wxT(':') );
257 // We then remove a leading ":". The reason is in our
258 // storage form for relative paths:
259 // ":dir:file.txt" actually means "./dir/file.txt" in
260 // DOS notation and should get stored as
261 // (relative) (dir) (file.txt)
262 // "::dir:file.txt" actually means "../dir/file.txt"
263 // stored as (relative) (..) (dir) (file.txt)
264 // This is important only for the Mac as an empty dir
265 // actually means <UP>, whereas under DOS, double
266 // slashes can be ignored: "\\\\" is the same as "\\".
268 my_path
.Remove( 0, 1 );
271 // TODO: what is the relative path format here?
275 m_relative
= ( my_path
[0u] != wxT('/') );
278 m_relative
= ( (my_path
[0u] != wxT('/')) && (my_path
[0u] != wxT('\\')) );
281 wxFAIL_MSG( wxT("error") );
285 // 2) Break up the path into its members. If the original path
286 // was just "/" or "\\", m_dirs will be empty. We know from
287 // the m_relative field, if this means "nothing" or "root dir".
289 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
291 while ( tn
.HasMoreTokens() )
293 wxString token
= tn
.GetNextToken();
295 // Remove empty token under DOS and Unix, interpret them
299 if (my_format
== wxPATH_MAC
)
300 m_dirs
.Add( wxT("..") );
315 void wxFileName::Assign(const wxString
& fullpath
,
318 wxString volume
, path
, name
, ext
;
319 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
321 Assign(volume
, path
, name
, ext
, format
);
324 void wxFileName::Assign(const wxString
& fullpathOrig
,
325 const wxString
& fullname
,
328 // always recognize fullpath as directory, even if it doesn't end with a
330 wxString fullpath
= fullpathOrig
;
331 if ( !wxEndsWithPathSeparator(fullpath
) )
333 fullpath
+= GetPathSeparators(format
)[0u];
336 wxString volume
, path
, name
, ext
;
338 // do some consistency checks in debug mode: the name should be really just
339 // the filename and the path should be really just a path
341 wxString pathDummy
, nameDummy
, extDummy
;
343 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
345 wxASSERT_MSG( pathDummy
.empty(),
346 _T("the file name shouldn't contain the path") );
348 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
350 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
351 _T("the path shouldn't contain file name nor extension") );
353 #else // !__WXDEBUG__
354 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
355 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
356 #endif // __WXDEBUG__/!__WXDEBUG__
358 Assign(volume
, path
, name
, ext
, format
);
361 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
363 Assign(dir
, _T(""), format
);
366 void wxFileName::Clear()
372 m_ext
= wxEmptyString
;
376 wxFileName
wxFileName::FileName(const wxString
& file
)
378 return wxFileName(file
);
382 wxFileName
wxFileName::DirName(const wxString
& dir
)
389 // ----------------------------------------------------------------------------
391 // ----------------------------------------------------------------------------
393 bool wxFileName::FileExists()
395 return wxFileName::FileExists( GetFullPath() );
398 bool wxFileName::FileExists( const wxString
&file
)
400 return ::wxFileExists( file
);
403 bool wxFileName::DirExists()
405 return wxFileName::DirExists( GetFullPath() );
408 bool wxFileName::DirExists( const wxString
&dir
)
410 return ::wxDirExists( dir
);
413 // ----------------------------------------------------------------------------
414 // CWD and HOME stuff
415 // ----------------------------------------------------------------------------
417 void wxFileName::AssignCwd(const wxString
& volume
)
419 AssignDir(wxFileName::GetCwd(volume
));
423 wxString
wxFileName::GetCwd(const wxString
& volume
)
425 // if we have the volume, we must get the current directory on this drive
426 // and to do this we have to chdir to this volume - at least under Windows,
427 // I don't know how to get the current drive on another volume elsewhere
430 if ( !volume
.empty() )
433 SetCwd(volume
+ GetVolumeSeparator());
436 wxString cwd
= ::wxGetCwd();
438 if ( !volume
.empty() )
446 bool wxFileName::SetCwd()
448 return wxFileName::SetCwd( GetFullPath() );
451 bool wxFileName::SetCwd( const wxString
&cwd
)
453 return ::wxSetWorkingDirectory( cwd
);
456 void wxFileName::AssignHomeDir()
458 AssignDir(wxFileName::GetHomeDir());
461 wxString
wxFileName::GetHomeDir()
463 return ::wxGetHomeDir();
466 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
468 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
469 if ( tempname
.empty() )
471 // error, failed to get temp file name
482 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
484 wxString path
, dir
, name
;
486 // use the directory specified by the prefix
487 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
489 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
494 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
496 wxLogLastError(_T("GetTempPath"));
501 // GetTempFileName() fails if we pass it an empty string
506 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
508 wxLogLastError(_T("GetTempFileName"));
513 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
519 #elif defined(__WXPM__)
520 // for now just create a file
522 // future enhancements can be to set some extended attributes for file
523 // systems OS/2 supports that have them (HPFS, FAT32) and security
525 static const wxChar
*szMktempSuffix
= wxT("XXX");
526 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
528 // Temporarily remove - MN
530 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
533 #else // !Windows, !OS/2
536 dir
= wxGetenv(_T("TMP"));
539 dir
= wxGetenv(_T("TEMP"));
555 if ( !wxEndsWithPathSeparator(dir
) &&
556 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
558 path
+= wxFILE_SEP_PATH
;
563 #if defined(HAVE_MKSTEMP)
564 // scratch space for mkstemp()
565 path
+= _T("XXXXXX");
567 // can use the cast here because the length doesn't change and the string
569 int fdTemp
= mkstemp((char *)path
.mb_str());
572 // this might be not necessary as mkstemp() on most systems should have
573 // already done it but it doesn't hurt neither...
576 else // mkstemp() succeeded
578 // avoid leaking the fd
581 fileTemp
->Attach(fdTemp
);
588 #else // !HAVE_MKSTEMP
592 path
+= _T("XXXXXX");
594 if ( !mktemp((char *)path
.mb_str()) )
598 #else // !HAVE_MKTEMP (includes __DOS__)
599 // generate the unique file name ourselves
601 path
<< (unsigned int)getpid();
606 static const size_t numTries
= 1000;
607 for ( size_t n
= 0; n
< numTries
; n
++ )
609 // 3 hex digits is enough for numTries == 1000 < 4096
610 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
611 if ( !wxFile::Exists(pathTry
) )
620 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
625 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
627 #endif // Windows/!Windows
631 wxLogSysError(_("Failed to create a temporary file name"));
633 else if ( fileTemp
&& !fileTemp
->IsOpened() )
635 // open the file - of course, there is a race condition here, this is
636 // why we always prefer using mkstemp()...
638 // NB: GetTempFileName() under Windows creates the file, so using
639 // write_excl there would fail
640 if ( !fileTemp
->Open(path
,
641 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
646 wxS_IRUSR
| wxS_IWUSR
) )
648 // FIXME: If !ok here should we loop and try again with another
649 // file name? That is the standard recourse if open(O_EXCL)
650 // fails, though of course it should be protected against
651 // possible infinite looping too.
653 wxLogError(_("Failed to open temporary file."));
662 // ----------------------------------------------------------------------------
663 // directory operations
664 // ----------------------------------------------------------------------------
666 bool wxFileName::Mkdir( int perm
, bool full
)
668 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
671 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
675 wxFileName
filename(dir
);
676 wxArrayString dirs
= filename
.GetDirs();
677 dirs
.Add(filename
.GetName());
679 size_t count
= dirs
.GetCount();
683 for ( i
= 0; i
< count
; i
++ )
687 if (currPath
.Last() == wxT(':'))
689 // Can't create a root directory so continue to next dir
690 currPath
+= wxFILE_SEP_PATH
;
694 if (!DirExists(currPath
))
695 if (!wxMkdir(currPath
, perm
))
698 if ( (i
< (count
-1)) )
699 currPath
+= wxFILE_SEP_PATH
;
702 return (noErrors
== 0);
706 return ::wxMkdir( dir
, perm
);
709 bool wxFileName::Rmdir()
711 return wxFileName::Rmdir( GetFullPath() );
714 bool wxFileName::Rmdir( const wxString
&dir
)
716 return ::wxRmdir( dir
);
719 // ----------------------------------------------------------------------------
720 // path normalization
721 // ----------------------------------------------------------------------------
723 bool wxFileName::Normalize(wxPathNormalize flags
,
727 // the existing path components
728 wxArrayString dirs
= GetDirs();
730 // the path to prepend in front to make the path absolute
733 format
= GetFormat(format
);
735 // make the path absolute
736 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
740 curDir
.AssignCwd(GetVolume());
744 curDir
.AssignDir(cwd
);
748 // the path may be not absolute because it doesn't have the volume name
749 // but in this case we shouldn't modify the directory components of it
750 // but just set the current volume
751 if ( !HasVolume() && curDir
.HasVolume() )
753 SetVolume(curDir
.GetVolume());
757 // yes, it was the case - we don't need curDir then
765 // handle ~ stuff under Unix only
766 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
768 if ( !dirs
.IsEmpty() )
770 wxString dir
= dirs
[0u];
771 if ( !dir
.empty() && dir
[0u] == _T('~') )
773 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
780 // transform relative path into abs one
783 wxArrayString dirsNew
= curDir
.GetDirs();
784 size_t count
= dirs
.GetCount();
785 for ( size_t n
= 0; n
< count
; n
++ )
787 dirsNew
.Add(dirs
[n
]);
793 // now deal with ".", ".." and the rest
795 size_t count
= dirs
.GetCount();
796 for ( size_t n
= 0; n
< count
; n
++ )
798 wxString dir
= dirs
[n
];
800 if ( flags
& wxPATH_NORM_DOTS
)
802 if ( dir
== wxT(".") )
808 if ( dir
== wxT("..") )
810 if ( m_dirs
.IsEmpty() )
812 wxLogError(_("The path '%s' contains too many \"..\"!"),
813 GetFullPath().c_str());
817 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
822 if ( flags
& wxPATH_NORM_ENV_VARS
)
824 dir
= wxExpandEnvVars(dir
);
827 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
835 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
837 // VZ: expand env vars here too?
843 #if defined(__WIN32__)
844 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
846 Assign(GetLongPath());
853 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
855 wxFileName
fnBase(pathBase
, format
);
857 // get cwd only once - small time saving
858 wxString cwd
= wxGetCwd();
859 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
860 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
862 bool withCase
= IsCaseSensitive(format
);
864 // we can't do anything if the files live on different volumes
865 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
871 // same drive, so we don't need our volume
874 // remove common directories starting at the top
875 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
876 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
879 fnBase
.m_dirs
.RemoveAt(0);
882 // add as many ".." as needed
883 size_t count
= fnBase
.m_dirs
.GetCount();
884 for ( size_t i
= 0; i
< count
; i
++ )
886 m_dirs
.Insert(wxT(".."), 0u);
895 // ----------------------------------------------------------------------------
896 // filename kind tests
897 // ----------------------------------------------------------------------------
899 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
901 wxFileName fn1
= *this,
904 // get cwd only once - small time saving
905 wxString cwd
= wxGetCwd();
906 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
907 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
909 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
912 // TODO: compare inodes for Unix, this works even when filenames are
913 // different but files are the same (symlinks) (VZ)
919 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
921 // only Unix filenames are truely case-sensitive
922 return GetFormat(format
) == wxPATH_UNIX
;
926 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
930 if ( (GetFormat(format
) == wxPATH_DOS
) ||
931 (GetFormat(format
) == wxPATH_VMS
) )
933 sepVol
= wxFILE_SEP_DSK
;
941 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
944 switch ( GetFormat(format
) )
947 // accept both as native APIs do but put the native one first as
948 // this is the one we use in GetFullPath()
949 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
953 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
957 seps
= wxFILE_SEP_PATH_UNIX
;
961 seps
= wxFILE_SEP_PATH_MAC
;
965 seps
= wxFILE_SEP_PATH_VMS
;
973 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
975 // wxString::Find() doesn't work as expected with NUL - it will always find
976 // it, so it is almost surely a bug if this function is called with NUL arg
977 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
979 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
982 bool wxFileName::IsWild( wxPathFormat format
)
984 // FIXME: this is probably false for Mac and this is surely wrong for most
985 // of Unix shells (think about "[...]")
987 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
990 // ----------------------------------------------------------------------------
991 // path components manipulation
992 // ----------------------------------------------------------------------------
994 void wxFileName::AppendDir( const wxString
&dir
)
999 void wxFileName::PrependDir( const wxString
&dir
)
1001 m_dirs
.Insert( dir
, 0 );
1004 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1006 m_dirs
.Insert( dir
, before
);
1009 void wxFileName::RemoveDir( int pos
)
1011 m_dirs
.Remove( (size_t)pos
);
1014 // ----------------------------------------------------------------------------
1016 // ----------------------------------------------------------------------------
1018 void wxFileName::SetFullName(const wxString
& fullname
)
1020 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1023 wxString
wxFileName::GetFullName() const
1025 wxString fullname
= m_name
;
1026 if ( !m_ext
.empty() )
1028 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1034 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1036 format
= GetFormat( format
);
1040 // the leading character
1041 if ( format
== wxPATH_MAC
&& m_relative
)
1043 fullpath
+= wxFILE_SEP_PATH_MAC
;
1045 else if ( format
== wxPATH_DOS
)
1048 fullpath
+= wxFILE_SEP_PATH_DOS
;
1050 else if ( format
== wxPATH_UNIX
)
1053 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1056 // then concatenate all the path components using the path separator
1057 size_t dirCount
= m_dirs
.GetCount();
1060 if ( format
== wxPATH_VMS
)
1062 fullpath
+= wxT('[');
1066 for ( size_t i
= 0; i
< dirCount
; i
++ )
1068 // TODO: What to do with ".." under VMS
1074 if (m_dirs
[i
] == wxT("."))
1076 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1077 fullpath
+= m_dirs
[i
];
1078 fullpath
+= wxT(':');
1083 fullpath
+= m_dirs
[i
];
1084 fullpath
+= wxT('\\');
1089 fullpath
+= m_dirs
[i
];
1090 fullpath
+= wxT('/');
1095 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1096 fullpath
+= m_dirs
[i
];
1097 if (i
== dirCount
-1)
1098 fullpath
+= wxT(']');
1100 fullpath
+= wxT('.');
1105 wxFAIL_MSG( wxT("error") );
1116 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1118 format
= GetFormat(format
);
1122 // first put the volume
1123 if ( !m_volume
.empty() )
1126 // Special Windows UNC paths hack, part 2: undo what we did in
1127 // SplitPath() and make an UNC path if we have a drive which is not a
1128 // single letter (hopefully the network shares can't be one letter only
1129 // although I didn't find any authoritative docs on this)
1130 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1132 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1134 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1136 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1142 // the leading character
1143 if ( format
== wxPATH_MAC
&& m_relative
)
1145 fullpath
+= wxFILE_SEP_PATH_MAC
;
1147 else if ( format
== wxPATH_DOS
)
1150 fullpath
+= wxFILE_SEP_PATH_DOS
;
1152 else if ( format
== wxPATH_UNIX
)
1155 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1158 // then concatenate all the path components using the path separator
1159 size_t dirCount
= m_dirs
.GetCount();
1162 if ( format
== wxPATH_VMS
)
1164 fullpath
+= wxT('[');
1168 for ( size_t i
= 0; i
< dirCount
; i
++ )
1170 // TODO: What to do with ".." under VMS
1176 if (m_dirs
[i
] == wxT("."))
1178 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1179 fullpath
+= m_dirs
[i
];
1180 fullpath
+= wxT(':');
1185 fullpath
+= m_dirs
[i
];
1186 fullpath
+= wxT('\\');
1191 fullpath
+= m_dirs
[i
];
1192 fullpath
+= wxT('/');
1197 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1198 fullpath
+= m_dirs
[i
];
1199 if (i
== dirCount
-1)
1200 fullpath
+= wxT(']');
1202 fullpath
+= wxT('.');
1207 wxFAIL_MSG( wxT("error") );
1213 // finally add the file name and extension
1214 fullpath
+= GetFullName();
1219 // Return the short form of the path (returns identity on non-Windows platforms)
1220 wxString
wxFileName::GetShortPath() const
1222 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1223 wxString
path(GetFullPath());
1225 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1229 ok
= ::GetShortPathName
1232 pathOut
.GetWriteBuf(sz
),
1235 pathOut
.UngetWriteBuf();
1242 return GetFullPath();
1246 // Return the long form of the path (returns identity on non-Windows platforms)
1247 wxString
wxFileName::GetLongPath() const
1250 path
= GetFullPath();
1252 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1253 bool success
= FALSE
;
1255 // VZ: this code was disabled, why?
1256 #if 0 // wxUSE_DYNAMIC_LOADER
1257 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1259 static bool s_triedToLoad
= FALSE
;
1261 if ( !s_triedToLoad
)
1263 s_triedToLoad
= TRUE
;
1264 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1267 // may succeed or fail depending on the Windows version
1268 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1270 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1272 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1275 wxDllLoader::UnloadLibrary(dllKernel
);
1277 if ( s_pfnGetLongPathName
)
1279 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1280 bool ok
= dwSize
> 0;
1284 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1288 ok
= (*s_pfnGetLongPathName
)
1291 pathOut
.GetWriteBuf(sz
),
1294 pathOut
.UngetWriteBuf();
1304 #endif // wxUSE_DYNAMIC_LOADER
1308 // The OS didn't support GetLongPathName, or some other error.
1309 // We need to call FindFirstFile on each component in turn.
1311 WIN32_FIND_DATA findFileData
;
1313 pathOut
= wxEmptyString
;
1315 wxArrayString dirs
= GetDirs();
1316 dirs
.Add(GetFullName());
1320 size_t count
= dirs
.GetCount();
1321 for ( size_t i
= 0; i
< count
; i
++ )
1323 // We're using pathOut to collect the long-name path, but using a
1324 // temporary for appending the last path component which may be
1326 tmpPath
= pathOut
+ dirs
[i
];
1328 if ( tmpPath
.empty() )
1331 if ( tmpPath
.Last() == wxT(':') )
1333 // Can't pass a drive and root dir to FindFirstFile,
1334 // so continue to next dir
1335 tmpPath
+= wxFILE_SEP_PATH
;
1340 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1341 if (hFind
== INVALID_HANDLE_VALUE
)
1343 // Error: return immediately with the original path
1347 pathOut
+= findFileData
.cFileName
;
1348 if ( (i
< (count
-1)) )
1349 pathOut
+= wxFILE_SEP_PATH
;
1356 #endif // Win32/!Win32
1361 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1363 if (format
== wxPATH_NATIVE
)
1365 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1366 format
= wxPATH_DOS
;
1367 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1368 format
= wxPATH_MAC
;
1369 #elif defined(__VMS)
1370 format
= wxPATH_VMS
;
1372 format
= wxPATH_UNIX
;
1378 // ----------------------------------------------------------------------------
1379 // path splitting function
1380 // ----------------------------------------------------------------------------
1383 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1384 wxString
*pstrVolume
,
1388 wxPathFormat format
)
1390 format
= GetFormat(format
);
1392 wxString fullpath
= fullpathWithVolume
;
1394 // under VMS the end of the path is ']', not the path separator used to
1395 // separate the components
1396 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1397 : GetPathSeparators(format
);
1399 // special Windows UNC paths hack: transform \\share\path into share:path
1400 if ( format
== wxPATH_DOS
)
1402 if ( fullpath
.length() >= 4 &&
1403 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1404 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1406 fullpath
.erase(0, 2);
1408 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1409 if ( posFirstSlash
!= wxString::npos
)
1411 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1413 // UNC paths are always absolute, right? (FIXME)
1414 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1419 // We separate the volume here
1420 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1422 wxString sepVol
= GetVolumeSeparator(format
);
1424 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1425 if ( posFirstColon
!= wxString::npos
)
1429 *pstrVolume
= fullpath
.Left(posFirstColon
);
1432 // remove the volume name and the separator from the full path
1433 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1437 // find the positions of the last dot and last path separator in the path
1438 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1439 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1441 if ( (posLastDot
!= wxString::npos
) &&
1442 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1444 if ( (posLastDot
== 0) ||
1445 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1447 // under Unix and VMS, dot may be (and commonly is) the first
1448 // character of the filename, don't treat the entire filename as
1449 // extension in this case
1450 posLastDot
= wxString::npos
;
1454 // if we do have a dot and a slash, check that the dot is in the name part
1455 if ( (posLastDot
!= wxString::npos
) &&
1456 (posLastSlash
!= wxString::npos
) &&
1457 (posLastDot
< posLastSlash
) )
1459 // the dot is part of the path, not the start of the extension
1460 posLastDot
= wxString::npos
;
1463 // now fill in the variables provided by user
1466 if ( posLastSlash
== wxString::npos
)
1473 // take everything up to the path separator but take care to make
1474 // the path equal to something like '/', not empty, for the files
1475 // immediately under root directory
1476 size_t len
= posLastSlash
;
1480 *pstrPath
= fullpath
.Left(len
);
1482 // special VMS hack: remove the initial bracket
1483 if ( format
== wxPATH_VMS
)
1485 if ( (*pstrPath
)[0u] == _T('[') )
1486 pstrPath
->erase(0, 1);
1493 // take all characters starting from the one after the last slash and
1494 // up to, but excluding, the last dot
1495 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1497 if ( posLastDot
== wxString::npos
)
1499 // take all until the end
1500 count
= wxString::npos
;
1502 else if ( posLastSlash
== wxString::npos
)
1506 else // have both dot and slash
1508 count
= posLastDot
- posLastSlash
- 1;
1511 *pstrName
= fullpath
.Mid(nStart
, count
);
1516 if ( posLastDot
== wxString::npos
)
1523 // take everything after the dot
1524 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1530 void wxFileName::SplitPath(const wxString
& fullpath
,
1534 wxPathFormat format
)
1537 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1539 if ( path
&& !volume
.empty() )
1541 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1545 // ----------------------------------------------------------------------------
1547 // ----------------------------------------------------------------------------
1549 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1550 const wxDateTime
*dtAccess
,
1551 const wxDateTime
*dtMod
)
1553 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1554 if ( !dtAccess
&& !dtMod
)
1556 // can't modify the creation time anyhow, don't try
1560 // if dtAccess or dtMod is not specified, use the other one (which must be
1561 // non NULL because of the test above) for both times
1563 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1564 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1565 if ( utime(GetFullPath(), &utm
) == 0 )
1569 #elif defined(__WIN32__)
1570 wxFileHandle
fh(GetFullPath());
1573 FILETIME ftAccess
, ftCreate
, ftWrite
;
1576 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1578 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1580 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1582 if ( ::SetFileTime(fh
,
1583 dtCreate
? &ftCreate
: NULL
,
1584 dtAccess
? &ftAccess
: NULL
,
1585 dtMod
? &ftWrite
: NULL
) )
1590 #else // other platform
1593 wxLogSysError(_("Failed to modify file times for '%s'"),
1594 GetFullPath().c_str());
1599 bool wxFileName::Touch()
1601 #if defined(__UNIX_LIKE__)
1602 // under Unix touching file is simple: just pass NULL to utime()
1603 if ( utime(GetFullPath(), NULL
) == 0 )
1608 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1611 #else // other platform
1612 wxDateTime dtNow
= wxDateTime::Now();
1614 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1618 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1620 wxDateTime
*dtChange
) const
1622 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1624 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1627 dtAccess
->Set(stBuf
.st_atime
);
1629 dtMod
->Set(stBuf
.st_mtime
);
1631 dtChange
->Set(stBuf
.st_ctime
);
1635 #elif defined(__WIN32__)
1636 wxFileHandle
fh(GetFullPath());
1639 FILETIME ftAccess
, ftCreate
, ftWrite
;
1641 if ( ::GetFileTime(fh
,
1642 dtMod
? &ftCreate
: NULL
,
1643 dtAccess
? &ftAccess
: NULL
,
1644 dtChange
? &ftWrite
: NULL
) )
1647 ConvertFileTimeToWx(dtMod
, ftCreate
);
1649 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1651 ConvertFileTimeToWx(dtChange
, ftWrite
);
1656 #else // other platform
1659 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1660 GetFullPath().c_str());