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
, wxFile
*fileTemp
)
461 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
462 if ( tempname
.empty() )
464 // error, failed to get temp file name
475 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
477 wxString path
, dir
, name
;
479 // use the directory specified by the prefix
480 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
482 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
487 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
489 wxLogLastError(_T("GetTempPath"));
494 // GetTempFileName() fails if we pass it an empty string
499 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
501 wxLogLastError(_T("GetTempFileName"));
506 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
512 #elif defined(__WXPM__)
513 // for now just create a file
515 // future enhancements can be to set some extended attributes for file
516 // systems OS/2 supports that have them (HPFS, FAT32) and security
518 static const wxChar
*szMktempSuffix
= wxT("XXX");
519 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
521 // Temporarily remove - MN
523 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
526 #else // !Windows, !OS/2
529 dir
= wxGetenv(_T("TMP"));
532 dir
= wxGetenv(_T("TEMP"));
548 if ( !wxEndsWithPathSeparator(dir
) &&
549 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
551 path
+= wxFILE_SEP_PATH
;
556 #if defined(HAVE_MKSTEMP)
557 // scratch space for mkstemp()
558 path
+= _T("XXXXXX");
560 // can use the cast here because the length doesn't change and the string
562 int fdTemp
= mkstemp((char *)path
.mb_str());
565 // this might be not necessary as mkstemp() on most systems should have
566 // already done it but it doesn't hurt neither...
569 else // mkstemp() succeeded
571 // avoid leaking the fd
574 fileTemp
->Attach(fdTemp
);
581 #else // !HAVE_MKSTEMP
585 path
+= _T("XXXXXX");
587 if ( !mktemp((char *)path
.mb_str()) )
591 #else // !HAVE_MKTEMP (includes __DOS__)
592 // generate the unique file name ourselves
594 path
<< (unsigned int)getpid();
599 static const size_t numTries
= 1000;
600 for ( size_t n
= 0; n
< numTries
; n
++ )
602 // 3 hex digits is enough for numTries == 1000 < 4096
603 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
604 if ( !wxFile::Exists(pathTry
) )
613 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
618 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
620 #endif // Windows/!Windows
624 wxLogSysError(_("Failed to create a temporary file name"));
626 else if ( fileTemp
&& !fileTemp
->IsOpened() )
628 // open the file - of course, there is a race condition here, this is
629 // why we always prefer using mkstemp()...
630 if ( !fileTemp
->Open(path
, wxFile::write_excl
, wxS_IRUSR
| wxS_IWUSR
) )
632 // FIXME: If !ok here should we loop and try again with another
633 // file name? That is the standard recourse if open(O_EXCL)
634 // fails, though of course it should be protected against
635 // possible infinite looping too.
637 wxLogError(_("Failed to open temporary file."));
646 // ----------------------------------------------------------------------------
647 // directory operations
648 // ----------------------------------------------------------------------------
650 bool wxFileName::Mkdir( int perm
, bool full
)
652 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
655 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
659 wxFileName
filename(dir
);
660 wxArrayString dirs
= filename
.GetDirs();
661 dirs
.Add(filename
.GetName());
663 size_t count
= dirs
.GetCount();
667 for ( i
= 0; i
< count
; i
++ )
671 if (currPath
.Last() == wxT(':'))
673 // Can't create a root directory so continue to next dir
674 currPath
+= wxFILE_SEP_PATH
;
678 if (!DirExists(currPath
))
679 if (!wxMkdir(currPath
, perm
))
682 if ( (i
< (count
-1)) )
683 currPath
+= wxFILE_SEP_PATH
;
686 return (noErrors
== 0);
690 return ::wxMkdir( dir
, perm
);
693 bool wxFileName::Rmdir()
695 return wxFileName::Rmdir( GetFullPath() );
698 bool wxFileName::Rmdir( const wxString
&dir
)
700 return ::wxRmdir( dir
);
703 // ----------------------------------------------------------------------------
704 // path normalization
705 // ----------------------------------------------------------------------------
707 bool wxFileName::Normalize(wxPathNormalize flags
,
711 // the existing path components
712 wxArrayString dirs
= GetDirs();
714 // the path to prepend in front to make the path absolute
717 format
= GetFormat(format
);
719 // make the path absolute
720 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
724 curDir
.AssignCwd(GetVolume());
728 curDir
.AssignDir(cwd
);
732 // the path may be not absolute because it doesn't have the volume name
733 // but in this case we shouldn't modify the directory components of it
734 // but just set the current volume
735 if ( !HasVolume() && curDir
.HasVolume() )
737 SetVolume(curDir
.GetVolume());
741 // yes, it was the case - we don't need curDir then
749 // handle ~ stuff under Unix only
750 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
752 if ( !dirs
.IsEmpty() )
754 wxString dir
= dirs
[0u];
755 if ( !dir
.empty() && dir
[0u] == _T('~') )
757 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
764 // transform relative path into abs one
767 wxArrayString dirsNew
= curDir
.GetDirs();
768 size_t count
= dirs
.GetCount();
769 for ( size_t n
= 0; n
< count
; n
++ )
771 dirsNew
.Add(dirs
[n
]);
777 // now deal with ".", ".." and the rest
779 size_t count
= dirs
.GetCount();
780 for ( size_t n
= 0; n
< count
; n
++ )
782 wxString dir
= dirs
[n
];
784 if ( flags
& wxPATH_NORM_DOTS
)
786 if ( dir
== wxT(".") )
792 if ( dir
== wxT("..") )
794 if ( m_dirs
.IsEmpty() )
796 wxLogError(_("The path '%s' contains too many \"..\"!"),
797 GetFullPath().c_str());
801 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
806 if ( flags
& wxPATH_NORM_ENV_VARS
)
808 dir
= wxExpandEnvVars(dir
);
811 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
819 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
821 // VZ: expand env vars here too?
827 #if defined(__WIN32__)
828 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
830 Assign(GetLongPath());
837 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
839 wxFileName
fnBase(pathBase
, format
);
841 // get cwd only once - small time saving
842 wxString cwd
= wxGetCwd();
843 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
844 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
846 bool withCase
= IsCaseSensitive(format
);
848 // we can't do anything if the files live on different volumes
849 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
855 // same drive, so we don't need our volume
858 // remove common directories starting at the top
859 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
860 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
863 fnBase
.m_dirs
.RemoveAt(0);
866 // add as many ".." as needed
867 size_t count
= fnBase
.m_dirs
.GetCount();
868 for ( size_t i
= 0; i
< count
; i
++ )
870 m_dirs
.Insert(wxT(".."), 0u);
879 // ----------------------------------------------------------------------------
880 // filename kind tests
881 // ----------------------------------------------------------------------------
883 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
885 wxFileName fn1
= *this,
888 // get cwd only once - small time saving
889 wxString cwd
= wxGetCwd();
890 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
891 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
893 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
896 // TODO: compare inodes for Unix, this works even when filenames are
897 // different but files are the same (symlinks) (VZ)
903 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
905 // only Unix filenames are truely case-sensitive
906 return GetFormat(format
) == wxPATH_UNIX
;
910 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
914 if ( (GetFormat(format
) == wxPATH_DOS
) ||
915 (GetFormat(format
) == wxPATH_VMS
) )
917 sepVol
= wxFILE_SEP_DSK
;
925 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
928 switch ( GetFormat(format
) )
931 // accept both as native APIs do but put the native one first as
932 // this is the one we use in GetFullPath()
933 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
937 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
941 seps
= wxFILE_SEP_PATH_UNIX
;
945 seps
= wxFILE_SEP_PATH_MAC
;
949 seps
= wxFILE_SEP_PATH_VMS
;
957 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
959 // wxString::Find() doesn't work as expected with NUL - it will always find
960 // it, so it is almost surely a bug if this function is called with NUL arg
961 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
963 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
966 bool wxFileName::IsWild( wxPathFormat format
)
968 // FIXME: this is probably false for Mac and this is surely wrong for most
969 // of Unix shells (think about "[...]")
971 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
974 // ----------------------------------------------------------------------------
975 // path components manipulation
976 // ----------------------------------------------------------------------------
978 void wxFileName::AppendDir( const wxString
&dir
)
983 void wxFileName::PrependDir( const wxString
&dir
)
985 m_dirs
.Insert( dir
, 0 );
988 void wxFileName::InsertDir( int before
, const wxString
&dir
)
990 m_dirs
.Insert( dir
, before
);
993 void wxFileName::RemoveDir( int pos
)
995 m_dirs
.Remove( (size_t)pos
);
998 // ----------------------------------------------------------------------------
1000 // ----------------------------------------------------------------------------
1002 void wxFileName::SetFullName(const wxString
& fullname
)
1004 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1007 wxString
wxFileName::GetFullName() const
1009 wxString fullname
= m_name
;
1010 if ( !m_ext
.empty() )
1012 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1018 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1020 format
= GetFormat( format
);
1024 // the leading character
1025 if ( format
== wxPATH_MAC
&& m_relative
)
1027 fullpath
+= wxFILE_SEP_PATH_MAC
;
1029 else if ( format
== wxPATH_DOS
)
1032 fullpath
+= wxFILE_SEP_PATH_DOS
;
1034 else if ( format
== wxPATH_UNIX
)
1037 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1040 // then concatenate all the path components using the path separator
1041 size_t dirCount
= m_dirs
.GetCount();
1044 if ( format
== wxPATH_VMS
)
1046 fullpath
+= wxT('[');
1050 for ( size_t i
= 0; i
< dirCount
; i
++ )
1052 // TODO: What to do with ".." under VMS
1058 if (m_dirs
[i
] == wxT("."))
1060 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1061 fullpath
+= m_dirs
[i
];
1062 fullpath
+= wxT(':');
1067 fullpath
+= m_dirs
[i
];
1068 fullpath
+= wxT('\\');
1073 fullpath
+= m_dirs
[i
];
1074 fullpath
+= wxT('/');
1079 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1080 fullpath
+= m_dirs
[i
];
1081 if (i
== dirCount
-1)
1082 fullpath
+= wxT(']');
1084 fullpath
+= wxT('.');
1089 wxFAIL_MSG( wxT("error") );
1100 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1102 format
= GetFormat(format
);
1106 // first put the volume
1107 if ( !m_volume
.empty() )
1110 // Special Windows UNC paths hack, part 2: undo what we did in
1111 // SplitPath() and make an UNC path if we have a drive which is not a
1112 // single letter (hopefully the network shares can't be one letter only
1113 // although I didn't find any authoritative docs on this)
1114 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1116 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1118 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1120 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1126 // the leading character
1127 if ( format
== wxPATH_MAC
&& m_relative
)
1129 fullpath
+= wxFILE_SEP_PATH_MAC
;
1131 else if ( format
== wxPATH_DOS
)
1134 fullpath
+= wxFILE_SEP_PATH_DOS
;
1136 else if ( format
== wxPATH_UNIX
)
1139 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1142 // then concatenate all the path components using the path separator
1143 size_t dirCount
= m_dirs
.GetCount();
1146 if ( format
== wxPATH_VMS
)
1148 fullpath
+= wxT('[');
1152 for ( size_t i
= 0; i
< dirCount
; i
++ )
1154 // TODO: What to do with ".." under VMS
1160 if (m_dirs
[i
] == wxT("."))
1162 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1163 fullpath
+= m_dirs
[i
];
1164 fullpath
+= wxT(':');
1169 fullpath
+= m_dirs
[i
];
1170 fullpath
+= wxT('\\');
1175 fullpath
+= m_dirs
[i
];
1176 fullpath
+= wxT('/');
1181 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1182 fullpath
+= m_dirs
[i
];
1183 if (i
== dirCount
-1)
1184 fullpath
+= wxT(']');
1186 fullpath
+= wxT('.');
1191 wxFAIL_MSG( wxT("error") );
1197 // finally add the file name and extension
1198 fullpath
+= GetFullName();
1203 // Return the short form of the path (returns identity on non-Windows platforms)
1204 wxString
wxFileName::GetShortPath() const
1206 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1207 wxString
path(GetFullPath());
1209 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1213 ok
= ::GetShortPathName
1216 pathOut
.GetWriteBuf(sz
),
1219 pathOut
.UngetWriteBuf();
1226 return GetFullPath();
1230 // Return the long form of the path (returns identity on non-Windows platforms)
1231 wxString
wxFileName::GetLongPath() const
1234 path
= GetFullPath();
1236 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1237 bool success
= FALSE
;
1239 // VZ: this code was disabled, why?
1240 #if 0 // wxUSE_DYNLIB_CLASS
1241 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1243 static bool s_triedToLoad
= FALSE
;
1245 if ( !s_triedToLoad
)
1247 s_triedToLoad
= TRUE
;
1248 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1251 // may succeed or fail depending on the Windows version
1252 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1254 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1256 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1259 wxDllLoader::UnloadLibrary(dllKernel
);
1261 if ( s_pfnGetLongPathName
)
1263 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1264 bool ok
= dwSize
> 0;
1268 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1272 ok
= (*s_pfnGetLongPathName
)
1275 pathOut
.GetWriteBuf(sz
),
1278 pathOut
.UngetWriteBuf();
1288 #endif // wxUSE_DYNLIB_CLASS
1292 // The OS didn't support GetLongPathName, or some other error.
1293 // We need to call FindFirstFile on each component in turn.
1295 WIN32_FIND_DATA findFileData
;
1297 pathOut
= wxEmptyString
;
1299 wxArrayString dirs
= GetDirs();
1300 dirs
.Add(GetFullName());
1304 size_t count
= dirs
.GetCount();
1305 for ( size_t i
= 0; i
< count
; i
++ )
1307 // We're using pathOut to collect the long-name path, but using a
1308 // temporary for appending the last path component which may be
1310 tmpPath
= pathOut
+ dirs
[i
];
1312 if ( tmpPath
.empty() )
1315 if ( tmpPath
.Last() == wxT(':') )
1317 // Can't pass a drive and root dir to FindFirstFile,
1318 // so continue to next dir
1319 tmpPath
+= wxFILE_SEP_PATH
;
1324 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1325 if (hFind
== INVALID_HANDLE_VALUE
)
1327 // Error: return immediately with the original path
1331 pathOut
+= findFileData
.cFileName
;
1332 if ( (i
< (count
-1)) )
1333 pathOut
+= wxFILE_SEP_PATH
;
1340 #endif // Win32/!Win32
1345 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1347 if (format
== wxPATH_NATIVE
)
1349 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1350 format
= wxPATH_DOS
;
1351 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1352 format
= wxPATH_MAC
;
1353 #elif defined(__VMS)
1354 format
= wxPATH_VMS
;
1356 format
= wxPATH_UNIX
;
1362 // ----------------------------------------------------------------------------
1363 // path splitting function
1364 // ----------------------------------------------------------------------------
1367 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1368 wxString
*pstrVolume
,
1372 wxPathFormat format
)
1374 format
= GetFormat(format
);
1376 wxString fullpath
= fullpathWithVolume
;
1378 // under VMS the end of the path is ']', not the path separator used to
1379 // separate the components
1380 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1381 : GetPathSeparators(format
);
1383 // special Windows UNC paths hack: transform \\share\path into share:path
1384 if ( format
== wxPATH_DOS
)
1386 if ( fullpath
.length() >= 4 &&
1387 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1388 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1390 fullpath
.erase(0, 2);
1392 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1393 if ( posFirstSlash
!= wxString::npos
)
1395 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1397 // UNC paths are always absolute, right? (FIXME)
1398 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1403 // We separate the volume here
1404 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1406 wxString sepVol
= GetVolumeSeparator(format
);
1408 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1409 if ( posFirstColon
!= wxString::npos
)
1413 *pstrVolume
= fullpath
.Left(posFirstColon
);
1416 // remove the volume name and the separator from the full path
1417 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1421 // find the positions of the last dot and last path separator in the path
1422 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1423 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1425 if ( (posLastDot
!= wxString::npos
) &&
1426 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1428 if ( (posLastDot
== 0) ||
1429 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1431 // under Unix and VMS, dot may be (and commonly is) the first
1432 // character of the filename, don't treat the entire filename as
1433 // extension in this case
1434 posLastDot
= wxString::npos
;
1438 // if we do have a dot and a slash, check that the dot is in the name part
1439 if ( (posLastDot
!= wxString::npos
) &&
1440 (posLastSlash
!= wxString::npos
) &&
1441 (posLastDot
< posLastSlash
) )
1443 // the dot is part of the path, not the start of the extension
1444 posLastDot
= wxString::npos
;
1447 // now fill in the variables provided by user
1450 if ( posLastSlash
== wxString::npos
)
1457 // take everything up to the path separator but take care to make
1458 // the path equal to something like '/', not empty, for the files
1459 // immediately under root directory
1460 size_t len
= posLastSlash
;
1464 *pstrPath
= fullpath
.Left(len
);
1466 // special VMS hack: remove the initial bracket
1467 if ( format
== wxPATH_VMS
)
1469 if ( (*pstrPath
)[0u] == _T('[') )
1470 pstrPath
->erase(0, 1);
1477 // take all characters starting from the one after the last slash and
1478 // up to, but excluding, the last dot
1479 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1481 if ( posLastDot
== wxString::npos
)
1483 // take all until the end
1484 count
= wxString::npos
;
1486 else if ( posLastSlash
== wxString::npos
)
1490 else // have both dot and slash
1492 count
= posLastDot
- posLastSlash
- 1;
1495 *pstrName
= fullpath
.Mid(nStart
, count
);
1500 if ( posLastDot
== wxString::npos
)
1507 // take everything after the dot
1508 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1514 void wxFileName::SplitPath(const wxString
& fullpath
,
1518 wxPathFormat format
)
1521 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1523 if ( path
&& !volume
.empty() )
1525 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1529 // ----------------------------------------------------------------------------
1531 // ----------------------------------------------------------------------------
1533 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1534 const wxDateTime
*dtAccess
,
1535 const wxDateTime
*dtMod
)
1537 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1538 if ( !dtAccess
&& !dtMod
)
1540 // can't modify the creation time anyhow, don't try
1544 // if dtAccess or dtMod is not specified, use the other one (which must be
1545 // non NULL because of the test above) for both times
1547 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1548 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1549 if ( utime(GetFullPath(), &utm
) == 0 )
1553 #elif defined(__WIN32__)
1554 wxFileHandle
fh(GetFullPath());
1557 FILETIME ftAccess
, ftCreate
, ftWrite
;
1560 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1562 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1564 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1566 if ( ::SetFileTime(fh
,
1567 dtCreate
? &ftCreate
: NULL
,
1568 dtAccess
? &ftAccess
: NULL
,
1569 dtMod
? &ftWrite
: NULL
) )
1574 #else // other platform
1577 wxLogSysError(_("Failed to modify file times for '%s'"),
1578 GetFullPath().c_str());
1583 bool wxFileName::Touch()
1585 #if defined(__UNIX_LIKE__)
1586 // under Unix touching file is simple: just pass NULL to utime()
1587 if ( utime(GetFullPath(), NULL
) == 0 )
1592 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1595 #else // other platform
1596 wxDateTime dtNow
= wxDateTime::Now();
1598 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1602 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1604 wxDateTime
*dtChange
) const
1606 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1608 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1611 dtAccess
->Set(stBuf
.st_atime
);
1613 dtMod
->Set(stBuf
.st_mtime
);
1615 dtChange
->Set(stBuf
.st_ctime
);
1619 #elif defined(__WIN32__)
1620 wxFileHandle
fh(GetFullPath());
1623 FILETIME ftAccess
, ftCreate
, ftWrite
;
1625 if ( ::GetFileTime(fh
,
1626 dtMod
? &ftCreate
: NULL
,
1627 dtAccess
? &ftAccess
: NULL
,
1628 dtChange
? &ftWrite
: NULL
) )
1631 ConvertFileTimeToWx(dtMod
, ftCreate
);
1633 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1635 ConvertFileTimeToWx(dtChange
, ftWrite
);
1640 #else // other platform
1643 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1644 GetFullPath().c_str());