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"
79 #include "wx/filename.h"
80 #include "wx/tokenzr.h"
81 #include "wx/config.h" // for wxExpandEnvVars
84 #if wxUSE_DYNLIB_CLASS
85 #include "wx/dynlib.h"
88 // For GetShort/LongPathName
92 #include "wx/msw/winundef.h"
95 // utime() is POSIX so should normally be available on all Unices
97 #include <sys/types.h>
111 #include <sys/utime.h>
112 #include <sys/stat.h>
121 // ----------------------------------------------------------------------------
123 // ----------------------------------------------------------------------------
125 // small helper class which opens and closes the file - we use it just to get
126 // a file handle for the given file name to pass it to some Win32 API function
127 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
132 wxFileHandle(const wxString
& filename
)
134 m_hFile
= ::CreateFile
137 GENERIC_READ
, // access mask
139 NULL
, // no secutity attr
140 OPEN_EXISTING
, // creation disposition
142 NULL
// no template file
145 if ( m_hFile
== INVALID_HANDLE_VALUE
)
147 wxLogSysError(_("Failed to open '%s' for reading"),
154 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
156 if ( !::CloseHandle(m_hFile
) )
158 wxLogSysError(_("Failed to close file handle"));
163 // return TRUE only if the file could be opened successfully
164 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
167 operator HANDLE() const { return m_hFile
; }
175 // ----------------------------------------------------------------------------
177 // ----------------------------------------------------------------------------
179 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
181 // convert between wxDateTime and FILETIME which is a 64-bit value representing
182 // the number of 100-nanosecond intervals since January 1, 1601.
184 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
185 // FILETIME reference point (January 1, 1601)
186 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
188 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
190 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
192 // convert 100ns to ms
195 // move it to our Epoch
196 ll
-= FILETIME_EPOCH_OFFSET
;
198 *dt
= wxDateTime(ll
);
201 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
203 // do the reverse of ConvertFileTimeToWx()
204 wxLongLong ll
= dt
.GetValue();
206 ll
+= FILETIME_EPOCH_OFFSET
;
208 ft
->dwHighDateTime
= ll
.GetHi();
209 ft
->dwLowDateTime
= ll
.GetLo();
214 // ============================================================================
216 // ============================================================================
218 // ----------------------------------------------------------------------------
219 // wxFileName construction
220 // ----------------------------------------------------------------------------
222 void wxFileName::Assign( const wxFileName
&filepath
)
224 m_volume
= filepath
.GetVolume();
225 m_dirs
= filepath
.GetDirs();
226 m_name
= filepath
.GetName();
227 m_ext
= filepath
.GetExt();
228 m_relative
= filepath
.IsRelative();
231 void wxFileName::Assign(const wxString
& volume
,
232 const wxString
& path
,
233 const wxString
& name
,
235 wxPathFormat format
)
237 wxPathFormat my_format
= GetFormat( format
);
238 wxString my_path
= path
;
242 if (!my_path
.empty())
244 // 1) Determine if the path is relative or absolute.
249 m_relative
= ( my_path
[0u] == wxT(':') );
250 // We then remove a leading ":". The reason is in our
251 // storage form for relative paths:
252 // ":dir:file.txt" actually means "./dir/file.txt" in
253 // DOS notation and should get stored as
254 // (relative) (dir) (file.txt)
255 // "::dir:file.txt" actually means "../dir/file.txt"
256 // stored as (relative) (..) (dir) (file.txt)
257 // This is important only for the Mac as an empty dir
258 // actually means <UP>, whereas under DOS, double
259 // slashes can be ignored: "\\\\" is the same as "\\".
261 my_path
.Remove( 0, 1 );
264 // TODO: what is the relative path format here?
268 m_relative
= ( my_path
[0u] != wxT('/') );
271 m_relative
= ( (my_path
[0u] != wxT('/')) && (my_path
[0u] != wxT('\\')) );
274 wxFAIL_MSG( wxT("error") );
278 // 2) Break up the path into its members. If the original path
279 // was just "/" or "\\", m_dirs will be empty. We know from
280 // the m_relative field, if this means "nothing" or "root dir".
282 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
284 while ( tn
.HasMoreTokens() )
286 wxString token
= tn
.GetNextToken();
288 // Remove empty token under DOS and Unix, interpret them
292 if (my_format
== wxPATH_MAC
)
293 m_dirs
.Add( wxT("..") );
308 void wxFileName::Assign(const wxString
& fullpath
,
311 wxString volume
, path
, name
, ext
;
312 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
314 Assign(volume
, path
, name
, ext
, format
);
317 void wxFileName::Assign(const wxString
& fullpathOrig
,
318 const wxString
& fullname
,
321 // always recognize fullpath as directory, even if it doesn't end with a
323 wxString fullpath
= fullpathOrig
;
324 if ( !wxEndsWithPathSeparator(fullpath
) )
326 fullpath
+= GetPathSeparators(format
)[0u];
329 wxString volume
, path
, name
, ext
;
331 // do some consistency checks in debug mode: the name should be really just
332 // the filename and the path should be really just a path
334 wxString pathDummy
, nameDummy
, extDummy
;
336 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
338 wxASSERT_MSG( pathDummy
.empty(),
339 _T("the file name shouldn't contain the path") );
341 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
343 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
344 _T("the path shouldn't contain file name nor extension") );
346 #else // !__WXDEBUG__
347 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
348 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
349 #endif // __WXDEBUG__/!__WXDEBUG__
351 Assign(volume
, path
, name
, ext
, format
);
354 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
356 Assign(dir
, _T(""), format
);
359 void wxFileName::Clear()
365 m_ext
= wxEmptyString
;
369 wxFileName
wxFileName::FileName(const wxString
& file
)
371 return wxFileName(file
);
375 wxFileName
wxFileName::DirName(const wxString
& dir
)
382 // ----------------------------------------------------------------------------
384 // ----------------------------------------------------------------------------
386 bool wxFileName::FileExists()
388 return wxFileName::FileExists( GetFullPath() );
391 bool wxFileName::FileExists( const wxString
&file
)
393 return ::wxFileExists( file
);
396 bool wxFileName::DirExists()
398 return wxFileName::DirExists( GetFullPath() );
401 bool wxFileName::DirExists( const wxString
&dir
)
403 return ::wxDirExists( dir
);
406 // ----------------------------------------------------------------------------
407 // CWD and HOME stuff
408 // ----------------------------------------------------------------------------
410 void wxFileName::AssignCwd(const wxString
& volume
)
412 AssignDir(wxFileName::GetCwd(volume
));
416 wxString
wxFileName::GetCwd(const wxString
& volume
)
418 // if we have the volume, we must get the current directory on this drive
419 // and to do this we have to chdir to this volume - at least under Windows,
420 // I don't know how to get the current drive on another volume elsewhere
423 if ( !volume
.empty() )
426 SetCwd(volume
+ GetVolumeSeparator());
429 wxString cwd
= ::wxGetCwd();
431 if ( !volume
.empty() )
439 bool wxFileName::SetCwd()
441 return wxFileName::SetCwd( GetFullPath() );
444 bool wxFileName::SetCwd( const wxString
&cwd
)
446 return ::wxSetWorkingDirectory( cwd
);
449 void wxFileName::AssignHomeDir()
451 AssignDir(wxFileName::GetHomeDir());
454 wxString
wxFileName::GetHomeDir()
456 return ::wxGetHomeDir();
459 void wxFileName::AssignTempFileName( const wxString
& prefix
)
461 wxString tempname
= CreateTempFileName(prefix
);
462 if ( tempname
.empty() )
464 // error, failed to get temp file name
474 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
476 wxString path
, dir
, name
;
478 // use the directory specified by the prefix
479 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
481 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
486 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
488 wxLogLastError(_T("GetTempPath"));
493 // GetTempFileName() fails if we pass it an empty string
498 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
500 wxLogLastError(_T("GetTempFileName"));
505 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
511 #elif defined(__WXPM__)
512 // for now just create a file
514 // future enhancements can be to set some extended attributes for file
515 // systems OS/2 supports that have them (HPFS, FAT32) and security
517 static const wxChar
*szMktempSuffix
= wxT("XXX");
518 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
520 // Temporarily remove - MN
522 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
525 #else // !Windows, !OS/2
528 dir
= wxGetenv(_T("TMP"));
531 dir
= wxGetenv(_T("TEMP"));
547 if ( !wxEndsWithPathSeparator(dir
) &&
548 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
550 path
+= wxFILE_SEP_PATH
;
555 #if defined(HAVE_MKSTEMP)
556 // scratch space for mkstemp()
557 path
+= _T("XXXXXX");
559 // can use the cast here because the length doesn't change and the string
561 if ( mkstemp((char *)path
.mb_str()) == -1 )
563 // this might be not necessary as mkstemp() on most systems should have
564 // already done it but it doesn't hurt neither...
567 //else: file already created
568 #else // !HAVE_MKSTEMP
572 path
+= _T("XXXXXX");
574 if ( !mktemp((char *)path
.mb_str()) )
578 #else // !HAVE_MKTEMP (includes __DOS__)
579 // generate the unique file name ourselves
581 path
<< (unsigned int)getpid();
586 static const size_t numTries
= 1000;
587 for ( size_t n
= 0; n
< numTries
; n
++ )
589 // 3 hex digits is enough for numTries == 1000 < 4096
590 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
591 if ( !wxFile::Exists(pathTry
) )
600 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
604 // create the file - of course, there is a race condition here, this is
605 // why we always prefer using mkstemp()...
607 if ( !file
.Open(path
, wxFile::write_excl
, wxS_IRUSR
| wxS_IWUSR
) )
609 // FIXME: If !ok here should we loop and try again with another
610 // file name? That is the standard recourse if open(O_EXCL)
611 // fails, though of course it should be protected against
612 // possible infinite looping too.
614 wxLogError(_("Failed to open temporary file."));
619 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
621 #endif // Windows/!Windows
625 wxLogSysError(_("Failed to create a temporary file name"));
631 // ----------------------------------------------------------------------------
632 // directory operations
633 // ----------------------------------------------------------------------------
635 bool wxFileName::Mkdir( int perm
, bool full
)
637 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
640 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
644 wxFileName
filename(dir
);
645 wxArrayString dirs
= filename
.GetDirs();
646 dirs
.Add(filename
.GetName());
648 size_t count
= dirs
.GetCount();
652 for ( i
= 0; i
< count
; i
++ )
656 if (currPath
.Last() == wxT(':'))
658 // Can't create a root directory so continue to next dir
659 currPath
+= wxFILE_SEP_PATH
;
663 if (!DirExists(currPath
))
664 if (!wxMkdir(currPath
, perm
))
667 if ( (i
< (count
-1)) )
668 currPath
+= wxFILE_SEP_PATH
;
671 return (noErrors
== 0);
675 return ::wxMkdir( dir
, perm
);
678 bool wxFileName::Rmdir()
680 return wxFileName::Rmdir( GetFullPath() );
683 bool wxFileName::Rmdir( const wxString
&dir
)
685 return ::wxRmdir( dir
);
688 // ----------------------------------------------------------------------------
689 // path normalization
690 // ----------------------------------------------------------------------------
692 bool wxFileName::Normalize(wxPathNormalize flags
,
696 // the existing path components
697 wxArrayString dirs
= GetDirs();
699 // the path to prepend in front to make the path absolute
702 format
= GetFormat(format
);
704 // make the path absolute
705 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
709 curDir
.AssignCwd(GetVolume());
713 curDir
.AssignDir(cwd
);
717 // the path may be not absolute because it doesn't have the volume name
718 // but in this case we shouldn't modify the directory components of it
719 // but just set the current volume
720 if ( !HasVolume() && curDir
.HasVolume() )
722 SetVolume(curDir
.GetVolume());
726 // yes, it was the case - we don't need curDir then
734 // handle ~ stuff under Unix only
735 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
737 if ( !dirs
.IsEmpty() )
739 wxString dir
= dirs
[0u];
740 if ( !dir
.empty() && dir
[0u] == _T('~') )
742 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
749 // transform relative path into abs one
752 wxArrayString dirsNew
= curDir
.GetDirs();
753 size_t count
= dirs
.GetCount();
754 for ( size_t n
= 0; n
< count
; n
++ )
756 dirsNew
.Add(dirs
[n
]);
762 // now deal with ".", ".." and the rest
764 size_t count
= dirs
.GetCount();
765 for ( size_t n
= 0; n
< count
; n
++ )
767 wxString dir
= dirs
[n
];
769 if ( flags
& wxPATH_NORM_DOTS
)
771 if ( dir
== wxT(".") )
777 if ( dir
== wxT("..") )
779 if ( m_dirs
.IsEmpty() )
781 wxLogError(_("The path '%s' contains too many \"..\"!"),
782 GetFullPath().c_str());
786 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
791 if ( flags
& wxPATH_NORM_ENV_VARS
)
793 dir
= wxExpandEnvVars(dir
);
796 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
804 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
806 // VZ: expand env vars here too?
812 #if defined(__WIN32__)
813 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
815 Assign(GetLongPath());
822 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
824 wxFileName
fnBase(pathBase
, format
);
826 // get cwd only once - small time saving
827 wxString cwd
= wxGetCwd();
828 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
829 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
831 bool withCase
= IsCaseSensitive(format
);
833 // we can't do anything if the files live on different volumes
834 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
840 // same drive, so we don't need our volume
843 // remove common directories starting at the top
844 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
845 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
848 fnBase
.m_dirs
.RemoveAt(0);
851 // add as many ".." as needed
852 size_t count
= fnBase
.m_dirs
.GetCount();
853 for ( size_t i
= 0; i
< count
; i
++ )
855 m_dirs
.Insert(wxT(".."), 0u);
864 // ----------------------------------------------------------------------------
865 // filename kind tests
866 // ----------------------------------------------------------------------------
868 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
870 wxFileName fn1
= *this,
873 // get cwd only once - small time saving
874 wxString cwd
= wxGetCwd();
875 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
876 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
878 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
881 // TODO: compare inodes for Unix, this works even when filenames are
882 // different but files are the same (symlinks) (VZ)
888 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
890 // only Unix filenames are truely case-sensitive
891 return GetFormat(format
) == wxPATH_UNIX
;
895 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
899 if ( (GetFormat(format
) == wxPATH_DOS
) ||
900 (GetFormat(format
) == wxPATH_VMS
) )
902 sepVol
= wxFILE_SEP_DSK
;
910 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
913 switch ( GetFormat(format
) )
916 // accept both as native APIs do but put the native one first as
917 // this is the one we use in GetFullPath()
918 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
922 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
926 seps
= wxFILE_SEP_PATH_UNIX
;
930 seps
= wxFILE_SEP_PATH_MAC
;
934 seps
= wxFILE_SEP_PATH_VMS
;
942 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
944 // wxString::Find() doesn't work as expected with NUL - it will always find
945 // it, so it is almost surely a bug if this function is called with NUL arg
946 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
948 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
951 bool wxFileName::IsWild( wxPathFormat format
)
953 // FIXME: this is probably false for Mac and this is surely wrong for most
954 // of Unix shells (think about "[...]")
956 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
959 // ----------------------------------------------------------------------------
960 // path components manipulation
961 // ----------------------------------------------------------------------------
963 void wxFileName::AppendDir( const wxString
&dir
)
968 void wxFileName::PrependDir( const wxString
&dir
)
970 m_dirs
.Insert( dir
, 0 );
973 void wxFileName::InsertDir( int before
, const wxString
&dir
)
975 m_dirs
.Insert( dir
, before
);
978 void wxFileName::RemoveDir( int pos
)
980 m_dirs
.Remove( (size_t)pos
);
983 // ----------------------------------------------------------------------------
985 // ----------------------------------------------------------------------------
987 void wxFileName::SetFullName(const wxString
& fullname
)
989 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
992 wxString
wxFileName::GetFullName() const
994 wxString fullname
= m_name
;
995 if ( !m_ext
.empty() )
997 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1003 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1005 format
= GetFormat( format
);
1009 // the leading character
1010 if ( format
== wxPATH_MAC
&& m_relative
)
1012 fullpath
+= wxFILE_SEP_PATH_MAC
;
1014 else if ( format
== wxPATH_DOS
)
1017 fullpath
+= wxFILE_SEP_PATH_DOS
;
1019 else if ( format
== wxPATH_UNIX
)
1022 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1025 // then concatenate all the path components using the path separator
1026 size_t dirCount
= m_dirs
.GetCount();
1029 if ( format
== wxPATH_VMS
)
1031 fullpath
+= wxT('[');
1035 for ( size_t i
= 0; i
< dirCount
; i
++ )
1037 // TODO: What to do with ".." under VMS
1043 if (m_dirs
[i
] == wxT("."))
1045 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1046 fullpath
+= m_dirs
[i
];
1047 fullpath
+= wxT(':');
1052 fullpath
+= m_dirs
[i
];
1053 fullpath
+= wxT('\\');
1058 fullpath
+= m_dirs
[i
];
1059 fullpath
+= wxT('/');
1064 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1065 fullpath
+= m_dirs
[i
];
1066 if (i
== dirCount
-1)
1067 fullpath
+= wxT(']');
1069 fullpath
+= wxT('.');
1074 wxFAIL_MSG( wxT("error") );
1085 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1087 format
= GetFormat(format
);
1091 // first put the volume
1092 if ( !m_volume
.empty() )
1095 // Special Windows UNC paths hack, part 2: undo what we did in
1096 // SplitPath() and make an UNC path if we have a drive which is not a
1097 // single letter (hopefully the network shares can't be one letter only
1098 // although I didn't find any authoritative docs on this)
1099 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1101 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1103 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1105 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1111 // the leading character
1112 if ( format
== wxPATH_MAC
&& m_relative
)
1114 fullpath
+= wxFILE_SEP_PATH_MAC
;
1116 else if ( format
== wxPATH_DOS
)
1119 fullpath
+= wxFILE_SEP_PATH_DOS
;
1121 else if ( format
== wxPATH_UNIX
)
1124 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1127 // then concatenate all the path components using the path separator
1128 size_t dirCount
= m_dirs
.GetCount();
1131 if ( format
== wxPATH_VMS
)
1133 fullpath
+= wxT('[');
1137 for ( size_t i
= 0; i
< dirCount
; i
++ )
1139 // TODO: What to do with ".." under VMS
1145 if (m_dirs
[i
] == wxT("."))
1147 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1148 fullpath
+= m_dirs
[i
];
1149 fullpath
+= wxT(':');
1154 fullpath
+= m_dirs
[i
];
1155 fullpath
+= wxT('\\');
1160 fullpath
+= m_dirs
[i
];
1161 fullpath
+= wxT('/');
1166 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1167 fullpath
+= m_dirs
[i
];
1168 if (i
== dirCount
-1)
1169 fullpath
+= wxT(']');
1171 fullpath
+= wxT('.');
1176 wxFAIL_MSG( wxT("error") );
1182 // finally add the file name and extension
1183 fullpath
+= GetFullName();
1188 // Return the short form of the path (returns identity on non-Windows platforms)
1189 wxString
wxFileName::GetShortPath() const
1191 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1192 wxString
path(GetFullPath());
1194 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1198 ok
= ::GetShortPathName
1201 pathOut
.GetWriteBuf(sz
),
1204 pathOut
.UngetWriteBuf();
1211 return GetFullPath();
1215 // Return the long form of the path (returns identity on non-Windows platforms)
1216 wxString
wxFileName::GetLongPath() const
1219 path
= GetFullPath();
1221 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1222 bool success
= FALSE
;
1224 // VZ: this code was disabled, why?
1225 #if 0 // wxUSE_DYNLIB_CLASS
1226 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1228 static bool s_triedToLoad
= FALSE
;
1230 if ( !s_triedToLoad
)
1232 s_triedToLoad
= TRUE
;
1233 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1236 // may succeed or fail depending on the Windows version
1237 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1239 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1241 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1244 wxDllLoader::UnloadLibrary(dllKernel
);
1246 if ( s_pfnGetLongPathName
)
1248 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1249 bool ok
= dwSize
> 0;
1253 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1257 ok
= (*s_pfnGetLongPathName
)
1260 pathOut
.GetWriteBuf(sz
),
1263 pathOut
.UngetWriteBuf();
1273 #endif // wxUSE_DYNLIB_CLASS
1277 // The OS didn't support GetLongPathName, or some other error.
1278 // We need to call FindFirstFile on each component in turn.
1280 WIN32_FIND_DATA findFileData
;
1282 pathOut
= wxEmptyString
;
1284 wxArrayString dirs
= GetDirs();
1285 dirs
.Add(GetFullName());
1289 size_t count
= dirs
.GetCount();
1290 for ( size_t i
= 0; i
< count
; i
++ )
1292 // We're using pathOut to collect the long-name path, but using a
1293 // temporary for appending the last path component which may be
1295 tmpPath
= pathOut
+ dirs
[i
];
1297 if ( tmpPath
.empty() )
1300 if ( tmpPath
.Last() == wxT(':') )
1302 // Can't pass a drive and root dir to FindFirstFile,
1303 // so continue to next dir
1304 tmpPath
+= wxFILE_SEP_PATH
;
1309 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1310 if (hFind
== INVALID_HANDLE_VALUE
)
1312 // Error: return immediately with the original path
1316 pathOut
+= findFileData
.cFileName
;
1317 if ( (i
< (count
-1)) )
1318 pathOut
+= wxFILE_SEP_PATH
;
1325 #endif // Win32/!Win32
1330 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1332 if (format
== wxPATH_NATIVE
)
1334 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1335 format
= wxPATH_DOS
;
1336 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1337 format
= wxPATH_MAC
;
1338 #elif defined(__VMS)
1339 format
= wxPATH_VMS
;
1341 format
= wxPATH_UNIX
;
1347 // ----------------------------------------------------------------------------
1348 // path splitting function
1349 // ----------------------------------------------------------------------------
1352 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1353 wxString
*pstrVolume
,
1357 wxPathFormat format
)
1359 format
= GetFormat(format
);
1361 wxString fullpath
= fullpathWithVolume
;
1363 // under VMS the end of the path is ']', not the path separator used to
1364 // separate the components
1365 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1366 : GetPathSeparators(format
);
1368 // special Windows UNC paths hack: transform \\share\path into share:path
1369 if ( format
== wxPATH_DOS
)
1371 if ( fullpath
.length() >= 4 &&
1372 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1373 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1375 fullpath
.erase(0, 2);
1377 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1378 if ( posFirstSlash
!= wxString::npos
)
1380 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1382 // UNC paths are always absolute, right? (FIXME)
1383 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1388 // We separate the volume here
1389 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1391 wxString sepVol
= GetVolumeSeparator(format
);
1393 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1394 if ( posFirstColon
!= wxString::npos
)
1398 *pstrVolume
= fullpath
.Left(posFirstColon
);
1401 // remove the volume name and the separator from the full path
1402 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1406 // find the positions of the last dot and last path separator in the path
1407 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1408 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1410 if ( (posLastDot
!= wxString::npos
) &&
1411 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1413 if ( (posLastDot
== 0) ||
1414 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1416 // under Unix and VMS, dot may be (and commonly is) the first
1417 // character of the filename, don't treat the entire filename as
1418 // extension in this case
1419 posLastDot
= wxString::npos
;
1423 // if we do have a dot and a slash, check that the dot is in the name part
1424 if ( (posLastDot
!= wxString::npos
) &&
1425 (posLastSlash
!= wxString::npos
) &&
1426 (posLastDot
< posLastSlash
) )
1428 // the dot is part of the path, not the start of the extension
1429 posLastDot
= wxString::npos
;
1432 // now fill in the variables provided by user
1435 if ( posLastSlash
== wxString::npos
)
1442 // take everything up to the path separator but take care to make
1443 // the path equal to something like '/', not empty, for the files
1444 // immediately under root directory
1445 size_t len
= posLastSlash
;
1449 *pstrPath
= fullpath
.Left(len
);
1451 // special VMS hack: remove the initial bracket
1452 if ( format
== wxPATH_VMS
)
1454 if ( (*pstrPath
)[0u] == _T('[') )
1455 pstrPath
->erase(0, 1);
1462 // take all characters starting from the one after the last slash and
1463 // up to, but excluding, the last dot
1464 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1466 if ( posLastDot
== wxString::npos
)
1468 // take all until the end
1469 count
= wxString::npos
;
1471 else if ( posLastSlash
== wxString::npos
)
1475 else // have both dot and slash
1477 count
= posLastDot
- posLastSlash
- 1;
1480 *pstrName
= fullpath
.Mid(nStart
, count
);
1485 if ( posLastDot
== wxString::npos
)
1492 // take everything after the dot
1493 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1499 void wxFileName::SplitPath(const wxString
& fullpath
,
1503 wxPathFormat format
)
1506 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1508 if ( path
&& !volume
.empty() )
1510 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1514 // ----------------------------------------------------------------------------
1516 // ----------------------------------------------------------------------------
1518 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1519 const wxDateTime
*dtAccess
,
1520 const wxDateTime
*dtMod
)
1522 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1523 if ( !dtAccess
&& !dtMod
)
1525 // can't modify the creation time anyhow, don't try
1529 // if dtAccess or dtMod is not specified, use the other one (which must be
1530 // non NULL because of the test above) for both times
1532 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1533 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1534 if ( utime(GetFullPath(), &utm
) == 0 )
1538 #elif defined(__WIN32__)
1539 wxFileHandle
fh(GetFullPath());
1542 FILETIME ftAccess
, ftCreate
, ftWrite
;
1545 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1547 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1549 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1551 if ( ::SetFileTime(fh
,
1552 dtCreate
? &ftCreate
: NULL
,
1553 dtAccess
? &ftAccess
: NULL
,
1554 dtMod
? &ftWrite
: NULL
) )
1559 #else // other platform
1562 wxLogSysError(_("Failed to modify file times for '%s'"),
1563 GetFullPath().c_str());
1568 bool wxFileName::Touch()
1570 #if defined(__UNIX_LIKE__)
1571 // under Unix touching file is simple: just pass NULL to utime()
1572 if ( utime(GetFullPath(), NULL
) == 0 )
1577 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1580 #else // other platform
1581 wxDateTime dtNow
= wxDateTime::Now();
1583 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1587 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1589 wxDateTime
*dtChange
) const
1591 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1593 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1596 dtAccess
->Set(stBuf
.st_atime
);
1598 dtMod
->Set(stBuf
.st_mtime
);
1600 dtChange
->Set(stBuf
.st_ctime
);
1604 #elif defined(__WIN32__)
1605 wxFileHandle
fh(GetFullPath());
1608 FILETIME ftAccess
, ftCreate
, ftWrite
;
1610 if ( ::GetFileTime(fh
,
1611 dtMod
? &ftCreate
: NULL
,
1612 dtAccess
? &ftAccess
: NULL
,
1613 dtChange
? &ftWrite
: NULL
) )
1616 ConvertFileTimeToWx(dtMod
, ftCreate
);
1618 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1620 ConvertFileTimeToWx(dtChange
, ftWrite
);
1625 #else // other platform
1628 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1629 GetFullPath().c_str());