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 :::filename.ext is not yet supported. TODO.
36 Since the volume is just part of the file path, it is not
37 treated like a separate entity as it is done under DOS.
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>
115 // ----------------------------------------------------------------------------
117 // ----------------------------------------------------------------------------
119 // small helper class which opens and closes the file - we use it just to get
120 // a file handle for the given file name to pass it to some Win32 API function
121 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
126 wxFileHandle(const wxString
& filename
)
128 m_hFile
= ::CreateFile
131 GENERIC_READ
, // access mask
133 NULL
, // no secutity attr
134 OPEN_EXISTING
, // creation disposition
136 NULL
// no template file
139 if ( m_hFile
== INVALID_HANDLE_VALUE
)
141 wxLogSysError(_("Failed to open '%s' for reading"),
148 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
150 if ( !::CloseHandle(m_hFile
) )
152 wxLogSysError(_("Failed to close file handle"));
157 // return TRUE only if the file could be opened successfully
158 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
161 operator HANDLE() const { return m_hFile
; }
169 // ----------------------------------------------------------------------------
171 // ----------------------------------------------------------------------------
173 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
175 // convert between wxDateTime and FILETIME which is a 64-bit value representing
176 // the number of 100-nanosecond intervals since January 1, 1601.
178 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
179 // FILETIME reference point (January 1, 1601)
180 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
182 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
184 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
186 // convert 100ns to ms
189 // move it to our Epoch
190 ll
-= FILETIME_EPOCH_OFFSET
;
192 *dt
= wxDateTime(ll
);
195 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
197 // do the reverse of ConvertFileTimeToWx()
198 wxLongLong ll
= dt
.GetValue();
200 ll
+= FILETIME_EPOCH_OFFSET
;
202 ft
->dwHighDateTime
= ll
.GetHi();
203 ft
->dwLowDateTime
= ll
.GetLo();
208 // ============================================================================
210 // ============================================================================
212 // ----------------------------------------------------------------------------
213 // wxFileName construction
214 // ----------------------------------------------------------------------------
216 void wxFileName::Assign( const wxFileName
&filepath
)
218 m_volume
= filepath
.GetVolume();
219 m_dirs
= filepath
.GetDirs();
220 m_name
= filepath
.GetName();
221 m_ext
= filepath
.GetExt();
224 void wxFileName::Assign(const wxString
& volume
,
225 const wxString
& path
,
226 const wxString
& name
,
228 wxPathFormat format
)
230 wxStringTokenizer
tn(path
, GetPathSeparators(format
));
233 while ( tn
.HasMoreTokens() )
235 wxString token
= tn
.GetNextToken();
237 // if the path starts with a slash, we do need the first empty dir
238 // entry to be able to tell later that it was an absolute path, but
239 // otherwise ignore the double slashes
240 if ( m_dirs
.IsEmpty() || !token
.IsEmpty() )
249 void wxFileName::Assign(const wxString
& fullpath
,
252 wxString volume
, path
, name
, ext
;
253 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
255 Assign(volume
, path
, name
, ext
, format
);
258 void wxFileName::Assign(const wxString
& fullpathOrig
,
259 const wxString
& fullname
,
262 // always recognize fullpath as directory, even if it doesn't end with a
264 wxString fullpath
= fullpathOrig
;
265 if ( !wxEndsWithPathSeparator(fullpath
) )
267 fullpath
+= GetPathSeparators(format
)[0u];
270 wxString volume
, path
, name
, ext
;
272 // do some consistency checks in debug mode: the name should be really just
273 // the filename and the path should be realyl just a path
275 wxString pathDummy
, nameDummy
, extDummy
;
277 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
279 wxASSERT_MSG( pathDummy
.empty(),
280 _T("the file name shouldn't contain the path") );
282 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
284 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
285 _T("the path shouldn't contain file name nor extension") );
287 #else // !__WXDEBUG__
288 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
289 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
290 #endif // __WXDEBUG__/!__WXDEBUG__
292 Assign(volume
, path
, name
, ext
, format
);
295 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
297 Assign(dir
, _T(""), format
);
300 void wxFileName::Clear()
306 m_ext
= wxEmptyString
;
310 wxFileName
wxFileName::FileName(const wxString
& file
)
312 return wxFileName(file
);
316 wxFileName
wxFileName::DirName(const wxString
& dir
)
323 // ----------------------------------------------------------------------------
325 // ----------------------------------------------------------------------------
327 bool wxFileName::FileExists()
329 return wxFileName::FileExists( GetFullPath() );
332 bool wxFileName::FileExists( const wxString
&file
)
334 return ::wxFileExists( file
);
337 bool wxFileName::DirExists()
339 return wxFileName::DirExists( GetFullPath() );
342 bool wxFileName::DirExists( const wxString
&dir
)
344 return ::wxDirExists( dir
);
347 // ----------------------------------------------------------------------------
348 // CWD and HOME stuff
349 // ----------------------------------------------------------------------------
351 void wxFileName::AssignCwd(const wxString
& volume
)
353 AssignDir(wxFileName::GetCwd(volume
));
357 wxString
wxFileName::GetCwd(const wxString
& volume
)
359 // if we have the volume, we must get the current directory on this drive
360 // and to do this we have to chdir to this volume - at least under Windows,
361 // I don't know how to get the current drive on another volume elsewhere
364 if ( !volume
.empty() )
367 SetCwd(volume
+ GetVolumeSeparator());
370 wxString cwd
= ::wxGetCwd();
372 if ( !volume
.empty() )
380 bool wxFileName::SetCwd()
382 return wxFileName::SetCwd( GetFullPath() );
385 bool wxFileName::SetCwd( const wxString
&cwd
)
387 return ::wxSetWorkingDirectory( cwd
);
390 void wxFileName::AssignHomeDir()
392 AssignDir(wxFileName::GetHomeDir());
395 wxString
wxFileName::GetHomeDir()
397 return ::wxGetHomeDir();
400 void wxFileName::AssignTempFileName( const wxString
& prefix
)
402 wxString tempname
= CreateTempFileName(prefix
);
403 if ( tempname
.empty() )
405 // error, failed to get temp file name
415 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
417 wxString path
, dir
, name
;
419 // use the directory specified by the prefix
420 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
422 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
427 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
429 wxLogLastError(_T("GetTempPath"));
434 // GetTempFileName() fails if we pass it an empty string
439 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
441 wxLogLastError(_T("GetTempFileName"));
446 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
452 #elif defined(__WXPM__)
453 // for now just create a file
455 // future enhancements can be to set some extended attributes for file
456 // systems OS/2 supports that have them (HPFS, FAT32) and security
458 static const wxChar
*szMktempSuffix
= wxT("XXX");
459 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
461 // Temporarily remove - MN
463 ::DosCreateDir(wxStringBuffer(MAX_PATH
), NULL
);
466 #else // !Windows, !OS/2, !DOS
469 dir
= wxGetenv(_T("TMP"));
472 dir
= wxGetenv(_T("TEMP"));
488 if ( !wxEndsWithPathSeparator(dir
) &&
489 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
491 path
+= wxFILE_SEP_PATH
;
496 #if defined(__DOS__) && defined(__WATCOMC__)
497 // scratch space for mkstemp()
498 path
+= _T("XXXXXX");
500 // can use the cast here because the length doesn't change and the string
502 if ( !_mktemp((char *)path
.mb_str()) )
504 // this might be not necessary as mkstemp() on most systems should have
505 // already done it but it doesn't hurt neither...
508 #elif defined(HAVE_MKSTEMP)
509 // scratch space for mkstemp()
510 path
+= _T("XXXXXX");
512 // can use the cast here because the length doesn't change and the string
514 if ( mkstemp((char *)path
.mb_str()) == -1 )
516 // this might be not necessary as mkstemp() on most systems should have
517 // already done it but it doesn't hurt neither...
520 //else: file already created
521 #else // !HAVE_MKSTEMP
525 path
+= _T("XXXXXX");
527 if ( !mktemp((char *)path
.mb_str()) )
531 #else // !HAVE_MKTEMP
532 // generate the unique file name ourselves
533 path
<< (unsigned int)getpid();
537 static const size_t numTries
= 1000;
538 for ( size_t n
= 0; n
< numTries
; n
++ )
540 // 3 hex digits is enough for numTries == 1000 < 4096
541 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
542 if ( !wxFile::Exists(pathTry
) )
551 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
555 // create the file - of course, there is a race condition here, this is
556 // why we always prefer using mkstemp()...
558 if ( !file
.Open(path
, wxFile::write_excl
, wxS_IRUSR
| wxS_IWUSR
) )
560 // FIXME: If !ok here should we loop and try again with another
561 // file name? That is the standard recourse if open(O_EXCL)
562 // fails, though of course it should be protected against
563 // possible infinite looping too.
565 wxLogError(_("Failed to open temporary file."));
570 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
572 #endif // Windows/!Windows
576 wxLogSysError(_("Failed to create a temporary file name"));
582 // ----------------------------------------------------------------------------
583 // directory operations
584 // ----------------------------------------------------------------------------
586 bool wxFileName::Mkdir( int perm
, bool full
)
588 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
591 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
595 wxFileName
filename(dir
);
596 wxArrayString dirs
= filename
.GetDirs();
597 dirs
.Add(filename
.GetName());
599 size_t count
= dirs
.GetCount();
603 for ( i
= 0; i
< count
; i
++ )
607 if (currPath
.Last() == wxT(':'))
609 // Can't create a root directory so continue to next dir
610 currPath
+= wxFILE_SEP_PATH
;
614 if (!DirExists(currPath
))
615 if (!wxMkdir(currPath
, perm
))
618 if ( (i
< (count
-1)) )
619 currPath
+= wxFILE_SEP_PATH
;
622 return (noErrors
== 0);
626 return ::wxMkdir( dir
, perm
);
629 bool wxFileName::Rmdir()
631 return wxFileName::Rmdir( GetFullPath() );
634 bool wxFileName::Rmdir( const wxString
&dir
)
636 return ::wxRmdir( dir
);
639 // ----------------------------------------------------------------------------
640 // path normalization
641 // ----------------------------------------------------------------------------
643 bool wxFileName::Normalize(wxPathNormalize flags
,
647 // the existing path components
648 wxArrayString dirs
= GetDirs();
650 // the path to prepend in front to make the path absolute
653 format
= GetFormat(format
);
655 // make the path absolute
656 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute() )
660 curDir
.AssignCwd(GetVolume());
664 curDir
.AssignDir(cwd
);
667 // the path may be not absolute because it doesn't have the volume name
668 // but in this case we shouldn't modify the directory components of it
669 // but just set the current volume
670 if ( !HasVolume() && curDir
.HasVolume() )
672 SetVolume(curDir
.GetVolume());
676 // yes, it was the case - we don't need curDir then
682 // handle ~ stuff under Unix only
683 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
685 if ( !dirs
.IsEmpty() )
687 wxString dir
= dirs
[0u];
688 if ( !dir
.empty() && dir
[0u] == _T('~') )
690 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
697 // transform relative path into abs one
700 wxArrayString dirsNew
= curDir
.GetDirs();
701 size_t count
= dirs
.GetCount();
702 for ( size_t n
= 0; n
< count
; n
++ )
704 dirsNew
.Add(dirs
[n
]);
710 // now deal with ".", ".." and the rest
712 size_t count
= dirs
.GetCount();
713 for ( size_t n
= 0; n
< count
; n
++ )
715 wxString dir
= dirs
[n
];
717 if ( flags
& wxPATH_NORM_DOTS
)
719 if ( dir
== wxT(".") )
725 if ( dir
== wxT("..") )
727 if ( m_dirs
.IsEmpty() )
729 wxLogError(_("The path '%s' contains too many \"..\"!"),
730 GetFullPath().c_str());
734 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
739 if ( flags
& wxPATH_NORM_ENV_VARS
)
741 dir
= wxExpandEnvVars(dir
);
744 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
752 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
754 // VZ: expand env vars here too?
760 #if defined(__WIN32__)
761 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
763 Assign(GetLongPath());
770 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
772 wxFileName
fnBase(pathBase
, format
);
774 // get cwd only once - small time saving
775 wxString cwd
= wxGetCwd();
776 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
777 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
779 bool withCase
= IsCaseSensitive(format
);
781 // we can't do anything if the files live on different volumes
782 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
788 // same drive, so we don't need our volume
791 // remove common directories starting at the top
792 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
793 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
796 fnBase
.m_dirs
.RemoveAt(0);
799 // add as many ".." as needed
800 size_t count
= fnBase
.m_dirs
.GetCount();
801 for ( size_t i
= 0; i
< count
; i
++ )
803 m_dirs
.Insert(wxT(".."), 0u);
810 // ----------------------------------------------------------------------------
811 // filename kind tests
812 // ----------------------------------------------------------------------------
814 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
816 wxFileName fn1
= *this,
819 // get cwd only once - small time saving
820 wxString cwd
= wxGetCwd();
821 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
822 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
824 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
827 // TODO: compare inodes for Unix, this works even when filenames are
828 // different but files are the same (symlinks) (VZ)
834 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
836 // only Unix filenames are truely case-sensitive
837 return GetFormat(format
) == wxPATH_UNIX
;
840 bool wxFileName::IsAbsolute( wxPathFormat format
)
842 // if we have no path, we can't be an abs filename
843 if ( m_dirs
.IsEmpty() )
848 format
= GetFormat(format
);
850 if ( format
== wxPATH_UNIX
)
852 const wxString
& str
= m_dirs
[0u];
855 // the path started with '/', it's an absolute one
859 // the path is absolute if it starts with a path separator or
860 // with "~" or "~user"
863 return IsPathSeparator(ch
, format
) || ch
== _T('~');
867 // must have the drive
868 if ( m_volume
.empty() )
874 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
878 return m_dirs
[0u].empty();
881 // TODO: what is the relative path format here?
885 return !m_dirs
[0u].empty();
891 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
895 if ( (GetFormat(format
) == wxPATH_DOS
) ||
896 (GetFormat(format
) == wxPATH_VMS
) )
898 sepVol
= wxFILE_SEP_DSK
;
906 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
909 switch ( GetFormat(format
) )
912 // accept both as native APIs do but put the native one first as
913 // this is the one we use in GetFullPath()
914 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
918 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
922 seps
= wxFILE_SEP_PATH_UNIX
;
926 seps
= wxFILE_SEP_PATH_MAC
;
930 seps
= wxFILE_SEP_PATH_VMS
;
938 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
940 // wxString::Find() doesn't work as expected with NUL - it will always find
941 // it, so it is almost surely a bug if this function is called with NUL arg
942 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
944 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
947 bool wxFileName::IsWild( wxPathFormat format
)
949 // FIXME: this is probably false for Mac and this is surely wrong for most
950 // of Unix shells (think about "[...]")
952 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
955 // ----------------------------------------------------------------------------
956 // path components manipulation
957 // ----------------------------------------------------------------------------
959 void wxFileName::AppendDir( const wxString
&dir
)
964 void wxFileName::PrependDir( const wxString
&dir
)
966 m_dirs
.Insert( dir
, 0 );
969 void wxFileName::InsertDir( int before
, const wxString
&dir
)
971 m_dirs
.Insert( dir
, before
);
974 void wxFileName::RemoveDir( int pos
)
976 m_dirs
.Remove( (size_t)pos
);
979 // ----------------------------------------------------------------------------
981 // ----------------------------------------------------------------------------
983 void wxFileName::SetFullName(const wxString
& fullname
)
985 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
988 wxString
wxFileName::GetFullName() const
990 wxString fullname
= m_name
;
991 if ( !m_ext
.empty() )
993 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
999 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1001 format
= GetFormat( format
);
1004 size_t count
= m_dirs
.GetCount();
1005 for ( size_t i
= 0; i
< count
; i
++ )
1008 if ( add_separator
|| (i
< count
) )
1009 ret
+= wxFILE_SEP_PATH
;
1015 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1017 format
= GetFormat(format
);
1021 // first put the volume
1022 if ( !m_volume
.empty() )
1025 // Special Windows UNC paths hack, part 2: undo what we did in
1026 // SplitPath() and make an UNC path if we have a drive which is not a
1027 // single letter (hopefully the network shares can't be one letter only
1028 // although I didn't find any authoritative docs on this)
1029 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1031 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1035 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1040 // then concatenate all the path components using the path separator
1041 size_t dirCount
= m_dirs
.GetCount();
1044 // under Mac, we must have a path separator in the beginning of the
1045 // relative path - otherwise it would be parsed as an absolute one
1046 if ( format
== wxPATH_MAC
&& m_dirs
[0].empty() )
1048 fullpath
+= wxFILE_SEP_PATH_MAC
;
1051 wxChar chPathSep
= GetPathSeparators(format
)[0u];
1052 if ( format
== wxPATH_VMS
)
1054 fullpath
+= _T('[');
1057 for ( size_t i
= 0; i
< dirCount
; i
++ )
1059 // under VMS, we shouldn't have a leading dot
1060 if ( i
&& (format
!= wxPATH_VMS
|| !m_dirs
[i
- 1].empty()) )
1061 fullpath
+= chPathSep
;
1063 fullpath
+= m_dirs
[i
];
1066 if ( format
== wxPATH_VMS
)
1068 fullpath
+= _T(']');
1072 // separate the file name from the last directory, notice that we
1073 // intentionally do it even if the name and extension are empty as
1074 // this allows us to distinguish the directories from the file
1075 // names (the directories have the trailing slash)
1076 fullpath
+= chPathSep
;
1080 // finally add the file name and extension
1081 fullpath
+= GetFullName();
1086 // Return the short form of the path (returns identity on non-Windows platforms)
1087 wxString
wxFileName::GetShortPath() const
1089 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1090 wxString
path(GetFullPath());
1092 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1096 ok
= ::GetShortPathName
1099 pathOut
.GetWriteBuf(sz
),
1102 pathOut
.UngetWriteBuf();
1109 return GetFullPath();
1113 // Return the long form of the path (returns identity on non-Windows platforms)
1114 wxString
wxFileName::GetLongPath() const
1117 path
= GetFullPath();
1119 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1120 bool success
= FALSE
;
1122 // VZ: this code was disabled, why?
1123 #if 0 // wxUSE_DYNLIB_CLASS
1124 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1126 static bool s_triedToLoad
= FALSE
;
1128 if ( !s_triedToLoad
)
1130 s_triedToLoad
= TRUE
;
1131 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1134 // may succeed or fail depending on the Windows version
1135 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1137 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1139 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1142 wxDllLoader::UnloadLibrary(dllKernel
);
1144 if ( s_pfnGetLongPathName
)
1146 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1147 bool ok
= dwSize
> 0;
1151 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1155 ok
= (*s_pfnGetLongPathName
)
1158 pathOut
.GetWriteBuf(sz
),
1161 pathOut
.UngetWriteBuf();
1171 #endif // wxUSE_DYNLIB_CLASS
1175 // The OS didn't support GetLongPathName, or some other error.
1176 // We need to call FindFirstFile on each component in turn.
1178 WIN32_FIND_DATA findFileData
;
1180 pathOut
= wxEmptyString
;
1182 wxArrayString dirs
= GetDirs();
1183 dirs
.Add(GetFullName());
1187 size_t count
= dirs
.GetCount();
1188 for ( size_t i
= 0; i
< count
; i
++ )
1190 // We're using pathOut to collect the long-name path, but using a
1191 // temporary for appending the last path component which may be
1193 tmpPath
= pathOut
+ dirs
[i
];
1195 if ( tmpPath
.empty() )
1198 if ( tmpPath
.Last() == wxT(':') )
1200 // Can't pass a drive and root dir to FindFirstFile,
1201 // so continue to next dir
1202 tmpPath
+= wxFILE_SEP_PATH
;
1207 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1208 if (hFind
== INVALID_HANDLE_VALUE
)
1210 // Error: return immediately with the original path
1214 pathOut
+= findFileData
.cFileName
;
1215 if ( (i
< (count
-1)) )
1216 pathOut
+= wxFILE_SEP_PATH
;
1223 #endif // Win32/!Win32
1228 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1230 if (format
== wxPATH_NATIVE
)
1232 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1233 format
= wxPATH_DOS
;
1234 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1235 format
= wxPATH_MAC
;
1236 #elif defined(__VMS)
1237 format
= wxPATH_VMS
;
1239 format
= wxPATH_UNIX
;
1245 // ----------------------------------------------------------------------------
1246 // path splitting function
1247 // ----------------------------------------------------------------------------
1250 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1251 wxString
*pstrVolume
,
1255 wxPathFormat format
)
1257 format
= GetFormat(format
);
1259 wxString fullpath
= fullpathWithVolume
;
1261 // under VMS the end of the path is ']', not the path separator used to
1262 // separate the components
1263 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1264 : GetPathSeparators(format
);
1266 // special Windows UNC paths hack: transform \\share\path into share:path
1267 if ( format
== wxPATH_DOS
)
1269 if ( fullpath
.length() >= 4 &&
1270 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1271 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1273 fullpath
.erase(0, 2);
1275 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1276 if ( posFirstSlash
!= wxString::npos
)
1278 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1280 // UNC paths are always absolute, right? (FIXME)
1281 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1286 // We separate the volume here
1287 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1289 wxString sepVol
= GetVolumeSeparator(format
);
1291 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1292 if ( posFirstColon
!= wxString::npos
)
1296 *pstrVolume
= fullpath
.Left(posFirstColon
);
1299 // remove the volume name and the separator from the full path
1300 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1304 // find the positions of the last dot and last path separator in the path
1305 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1306 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1308 if ( (posLastDot
!= wxString::npos
) &&
1309 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1311 if ( (posLastDot
== 0) ||
1312 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1314 // under Unix and VMS, dot may be (and commonly is) the first
1315 // character of the filename, don't treat the entire filename as
1316 // extension in this case
1317 posLastDot
= wxString::npos
;
1321 // if we do have a dot and a slash, check that the dot is in the name part
1322 if ( (posLastDot
!= wxString::npos
) &&
1323 (posLastSlash
!= wxString::npos
) &&
1324 (posLastDot
< posLastSlash
) )
1326 // the dot is part of the path, not the start of the extension
1327 posLastDot
= wxString::npos
;
1330 // now fill in the variables provided by user
1333 if ( posLastSlash
== wxString::npos
)
1340 // take everything up to the path separator but take care to make
1341 // tha path equal to something like '/', not empty, for the files
1342 // immediately under root directory
1343 size_t len
= posLastSlash
;
1347 *pstrPath
= fullpath
.Left(len
);
1349 // special VMS hack: remove the initial bracket
1350 if ( format
== wxPATH_VMS
)
1352 if ( (*pstrPath
)[0u] == _T('[') )
1353 pstrPath
->erase(0, 1);
1360 // take all characters starting from the one after the last slash and
1361 // up to, but excluding, the last dot
1362 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1364 if ( posLastDot
== wxString::npos
)
1366 // take all until the end
1367 count
= wxString::npos
;
1369 else if ( posLastSlash
== wxString::npos
)
1373 else // have both dot and slash
1375 count
= posLastDot
- posLastSlash
- 1;
1378 *pstrName
= fullpath
.Mid(nStart
, count
);
1383 if ( posLastDot
== wxString::npos
)
1390 // take everything after the dot
1391 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1397 void wxFileName::SplitPath(const wxString
& fullpath
,
1401 wxPathFormat format
)
1404 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1406 if ( path
&& !volume
.empty() )
1408 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1412 // ----------------------------------------------------------------------------
1414 // ----------------------------------------------------------------------------
1416 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1417 const wxDateTime
*dtAccess
,
1418 const wxDateTime
*dtMod
)
1420 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1421 if ( !dtAccess
&& !dtMod
)
1423 // can't modify the creation time anyhow, don't try
1427 // if dtAccess or dtMod is not specified, use the other one (which must be
1428 // non NULL because of the test above) for both times
1430 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1431 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1432 if ( utime(GetFullPath(), &utm
) == 0 )
1436 #elif defined(__WIN32__)
1437 wxFileHandle
fh(GetFullPath());
1440 FILETIME ftAccess
, ftCreate
, ftWrite
;
1443 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1445 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1447 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1449 if ( ::SetFileTime(fh
,
1450 dtCreate
? &ftCreate
: NULL
,
1451 dtAccess
? &ftAccess
: NULL
,
1452 dtMod
? &ftWrite
: NULL
) )
1457 #else // other platform
1460 wxLogSysError(_("Failed to modify file times for '%s'"),
1461 GetFullPath().c_str());
1466 bool wxFileName::Touch()
1468 #if defined(__UNIX_LIKE__)
1469 // under Unix touching file is simple: just pass NULL to utime()
1470 if ( utime(GetFullPath(), NULL
) == 0 )
1475 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1478 #else // other platform
1479 wxDateTime dtNow
= wxDateTime::Now();
1481 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1485 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1487 wxDateTime
*dtChange
) const
1489 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1491 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1494 dtAccess
->Set(stBuf
.st_atime
);
1496 dtMod
->Set(stBuf
.st_mtime
);
1498 dtChange
->Set(stBuf
.st_ctime
);
1502 #elif defined(__WIN32__)
1503 wxFileHandle
fh(GetFullPath());
1506 FILETIME ftAccess
, ftCreate
, ftWrite
;
1508 if ( ::GetFileTime(fh
,
1509 dtMod
? &ftCreate
: NULL
,
1510 dtAccess
? &ftAccess
: NULL
,
1511 dtChange
? &ftWrite
: NULL
) )
1514 ConvertFileTimeToWx(dtMod
, ftCreate
);
1516 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1518 ConvertFileTimeToWx(dtChange
, ftWrite
);
1523 #else // other platform
1526 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1527 GetFullPath().c_str());