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>
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();
230 void wxFileName::Assign(const wxString
& volume
,
231 const wxString
& path
,
232 const wxString
& name
,
234 wxPathFormat format
)
236 wxStringTokenizer
tn(path
, GetPathSeparators(format
));
239 while ( tn
.HasMoreTokens() )
241 wxString token
= tn
.GetNextToken();
243 // if the path starts with a slash, we do need the first empty dir
244 // entry to be able to tell later that it was an absolute path, but
245 // otherwise ignore the double slashes
246 if ( m_dirs
.IsEmpty() || !token
.IsEmpty() )
255 void wxFileName::Assign(const wxString
& fullpath
,
258 wxString volume
, path
, name
, ext
;
259 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
261 Assign(volume
, path
, name
, ext
, format
);
264 void wxFileName::Assign(const wxString
& fullpathOrig
,
265 const wxString
& fullname
,
268 // always recognize fullpath as directory, even if it doesn't end with a
270 wxString fullpath
= fullpathOrig
;
271 if ( !wxEndsWithPathSeparator(fullpath
) )
273 fullpath
+= GetPathSeparators(format
)[0u];
276 wxString volume
, path
, name
, ext
;
278 // do some consistency checks in debug mode: the name should be really just
279 // the filename and the path should be realyl just a path
281 wxString pathDummy
, nameDummy
, extDummy
;
283 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
285 wxASSERT_MSG( pathDummy
.empty(),
286 _T("the file name shouldn't contain the path") );
288 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
290 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
291 _T("the path shouldn't contain file name nor extension") );
293 #else // !__WXDEBUG__
294 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
295 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
296 #endif // __WXDEBUG__/!__WXDEBUG__
298 Assign(volume
, path
, name
, ext
, format
);
301 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
303 Assign(dir
, _T(""), format
);
306 void wxFileName::Clear()
312 m_ext
= wxEmptyString
;
316 wxFileName
wxFileName::FileName(const wxString
& file
)
318 return wxFileName(file
);
322 wxFileName
wxFileName::DirName(const wxString
& dir
)
329 // ----------------------------------------------------------------------------
331 // ----------------------------------------------------------------------------
333 bool wxFileName::FileExists()
335 return wxFileName::FileExists( GetFullPath() );
338 bool wxFileName::FileExists( const wxString
&file
)
340 return ::wxFileExists( file
);
343 bool wxFileName::DirExists()
345 return wxFileName::DirExists( GetFullPath() );
348 bool wxFileName::DirExists( const wxString
&dir
)
350 return ::wxDirExists( dir
);
353 // ----------------------------------------------------------------------------
354 // CWD and HOME stuff
355 // ----------------------------------------------------------------------------
357 void wxFileName::AssignCwd(const wxString
& volume
)
359 AssignDir(wxFileName::GetCwd(volume
));
363 wxString
wxFileName::GetCwd(const wxString
& volume
)
365 // if we have the volume, we must get the current directory on this drive
366 // and to do this we have to chdir to this volume - at least under Windows,
367 // I don't know how to get the current drive on another volume elsewhere
370 if ( !volume
.empty() )
373 SetCwd(volume
+ GetVolumeSeparator());
376 wxString cwd
= ::wxGetCwd();
378 if ( !volume
.empty() )
386 bool wxFileName::SetCwd()
388 return wxFileName::SetCwd( GetFullPath() );
391 bool wxFileName::SetCwd( const wxString
&cwd
)
393 return ::wxSetWorkingDirectory( cwd
);
396 void wxFileName::AssignHomeDir()
398 AssignDir(wxFileName::GetHomeDir());
401 wxString
wxFileName::GetHomeDir()
403 return ::wxGetHomeDir();
406 void wxFileName::AssignTempFileName( const wxString
& prefix
)
408 wxString tempname
= CreateTempFileName(prefix
);
409 if ( tempname
.empty() )
411 // error, failed to get temp file name
421 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
423 wxString path
, dir
, name
;
425 // use the directory specified by the prefix
426 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
428 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
433 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
435 wxLogLastError(_T("GetTempPath"));
440 // GetTempFileName() fails if we pass it an empty string
445 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
447 wxLogLastError(_T("GetTempFileName"));
452 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
458 #elif defined(__WXPM__)
459 // for now just create a file
461 // future enhancements can be to set some extended attributes for file
462 // systems OS/2 supports that have them (HPFS, FAT32) and security
464 static const wxChar
*szMktempSuffix
= wxT("XXX");
465 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
467 // Temporarily remove - MN
469 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
472 #else // !Windows, !OS/2
475 dir
= wxGetenv(_T("TMP"));
478 dir
= wxGetenv(_T("TEMP"));
494 if ( !wxEndsWithPathSeparator(dir
) &&
495 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
497 path
+= wxFILE_SEP_PATH
;
502 #if defined(HAVE_MKSTEMP)
503 // scratch space for mkstemp()
504 path
+= _T("XXXXXX");
506 // can use the cast here because the length doesn't change and the string
508 if ( mkstemp((char *)path
.mb_str()) == -1 )
510 // this might be not necessary as mkstemp() on most systems should have
511 // already done it but it doesn't hurt neither...
514 //else: file already created
515 #else // !HAVE_MKSTEMP
519 path
+= _T("XXXXXX");
521 if ( !mktemp((char *)path
.mb_str()) )
525 #else // !HAVE_MKTEMP (includes __DOS__)
526 // generate the unique file name ourselves
528 path
<< (unsigned int)getpid();
533 static const size_t numTries
= 1000;
534 for ( size_t n
= 0; n
< numTries
; n
++ )
536 // 3 hex digits is enough for numTries == 1000 < 4096
537 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
538 if ( !wxFile::Exists(pathTry
) )
547 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
551 // create the file - of course, there is a race condition here, this is
552 // why we always prefer using mkstemp()...
554 if ( !file
.Open(path
, wxFile::write_excl
, wxS_IRUSR
| wxS_IWUSR
) )
556 // FIXME: If !ok here should we loop and try again with another
557 // file name? That is the standard recourse if open(O_EXCL)
558 // fails, though of course it should be protected against
559 // possible infinite looping too.
561 wxLogError(_("Failed to open temporary file."));
566 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
568 #endif // Windows/!Windows
572 wxLogSysError(_("Failed to create a temporary file name"));
578 // ----------------------------------------------------------------------------
579 // directory operations
580 // ----------------------------------------------------------------------------
582 bool wxFileName::Mkdir( int perm
, bool full
)
584 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
587 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
591 wxFileName
filename(dir
);
592 wxArrayString dirs
= filename
.GetDirs();
593 dirs
.Add(filename
.GetName());
595 size_t count
= dirs
.GetCount();
599 for ( i
= 0; i
< count
; i
++ )
603 if (currPath
.Last() == wxT(':'))
605 // Can't create a root directory so continue to next dir
606 currPath
+= wxFILE_SEP_PATH
;
610 if (!DirExists(currPath
))
611 if (!wxMkdir(currPath
, perm
))
614 if ( (i
< (count
-1)) )
615 currPath
+= wxFILE_SEP_PATH
;
618 return (noErrors
== 0);
622 return ::wxMkdir( dir
, perm
);
625 bool wxFileName::Rmdir()
627 return wxFileName::Rmdir( GetFullPath() );
630 bool wxFileName::Rmdir( const wxString
&dir
)
632 return ::wxRmdir( dir
);
635 // ----------------------------------------------------------------------------
636 // path normalization
637 // ----------------------------------------------------------------------------
639 bool wxFileName::Normalize(wxPathNormalize flags
,
643 // the existing path components
644 wxArrayString dirs
= GetDirs();
646 // the path to prepend in front to make the path absolute
649 format
= GetFormat(format
);
651 // make the path absolute
652 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute() )
656 curDir
.AssignCwd(GetVolume());
660 curDir
.AssignDir(cwd
);
663 // the path may be not absolute because it doesn't have the volume name
664 // but in this case we shouldn't modify the directory components of it
665 // but just set the current volume
666 if ( !HasVolume() && curDir
.HasVolume() )
668 SetVolume(curDir
.GetVolume());
672 // yes, it was the case - we don't need curDir then
678 // handle ~ stuff under Unix only
679 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
681 if ( !dirs
.IsEmpty() )
683 wxString dir
= dirs
[0u];
684 if ( !dir
.empty() && dir
[0u] == _T('~') )
686 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
693 // transform relative path into abs one
696 wxArrayString dirsNew
= curDir
.GetDirs();
697 size_t count
= dirs
.GetCount();
698 for ( size_t n
= 0; n
< count
; n
++ )
700 dirsNew
.Add(dirs
[n
]);
706 // now deal with ".", ".." and the rest
708 size_t count
= dirs
.GetCount();
709 for ( size_t n
= 0; n
< count
; n
++ )
711 wxString dir
= dirs
[n
];
713 if ( flags
& wxPATH_NORM_DOTS
)
715 if ( dir
== wxT(".") )
721 if ( dir
== wxT("..") )
723 if ( m_dirs
.IsEmpty() )
725 wxLogError(_("The path '%s' contains too many \"..\"!"),
726 GetFullPath().c_str());
730 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
735 if ( flags
& wxPATH_NORM_ENV_VARS
)
737 dir
= wxExpandEnvVars(dir
);
740 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
748 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
750 // VZ: expand env vars here too?
756 #if defined(__WIN32__)
757 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
759 Assign(GetLongPath());
766 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
768 wxFileName
fnBase(pathBase
, format
);
770 // get cwd only once - small time saving
771 wxString cwd
= wxGetCwd();
772 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
773 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
775 bool withCase
= IsCaseSensitive(format
);
777 // we can't do anything if the files live on different volumes
778 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
784 // same drive, so we don't need our volume
787 // remove common directories starting at the top
788 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
789 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
792 fnBase
.m_dirs
.RemoveAt(0);
795 // add as many ".." as needed
796 size_t count
= fnBase
.m_dirs
.GetCount();
797 for ( size_t i
= 0; i
< count
; i
++ )
799 m_dirs
.Insert(wxT(".."), 0u);
806 // ----------------------------------------------------------------------------
807 // filename kind tests
808 // ----------------------------------------------------------------------------
810 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
812 wxFileName fn1
= *this,
815 // get cwd only once - small time saving
816 wxString cwd
= wxGetCwd();
817 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
818 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
820 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
823 // TODO: compare inodes for Unix, this works even when filenames are
824 // different but files are the same (symlinks) (VZ)
830 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
832 // only Unix filenames are truely case-sensitive
833 return GetFormat(format
) == wxPATH_UNIX
;
836 bool wxFileName::IsAbsolute( wxPathFormat format
)
838 // if we have no path, we can't be an abs filename
839 if ( m_dirs
.IsEmpty() )
844 format
= GetFormat(format
);
846 if ( format
== wxPATH_UNIX
)
848 const wxString
& str
= m_dirs
[0u];
851 // the path started with '/', it's an absolute one
855 // the path is absolute if it starts with a path separator or
856 // with "~" or "~user"
859 return IsPathSeparator(ch
, format
) || ch
== _T('~');
863 // must have the drive
864 if ( m_volume
.empty() )
870 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
874 return m_dirs
[0u].empty();
877 // TODO: what is the relative path format here?
881 return !m_dirs
[0u].empty();
887 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
891 if ( (GetFormat(format
) == wxPATH_DOS
) ||
892 (GetFormat(format
) == wxPATH_VMS
) )
894 sepVol
= wxFILE_SEP_DSK
;
902 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
905 switch ( GetFormat(format
) )
908 // accept both as native APIs do but put the native one first as
909 // this is the one we use in GetFullPath()
910 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
914 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
918 seps
= wxFILE_SEP_PATH_UNIX
;
922 seps
= wxFILE_SEP_PATH_MAC
;
926 seps
= wxFILE_SEP_PATH_VMS
;
934 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
936 // wxString::Find() doesn't work as expected with NUL - it will always find
937 // it, so it is almost surely a bug if this function is called with NUL arg
938 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
940 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
943 bool wxFileName::IsWild( wxPathFormat format
)
945 // FIXME: this is probably false for Mac and this is surely wrong for most
946 // of Unix shells (think about "[...]")
948 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
951 // ----------------------------------------------------------------------------
952 // path components manipulation
953 // ----------------------------------------------------------------------------
955 void wxFileName::AppendDir( const wxString
&dir
)
960 void wxFileName::PrependDir( const wxString
&dir
)
962 m_dirs
.Insert( dir
, 0 );
965 void wxFileName::InsertDir( int before
, const wxString
&dir
)
967 m_dirs
.Insert( dir
, before
);
970 void wxFileName::RemoveDir( int pos
)
972 m_dirs
.Remove( (size_t)pos
);
975 // ----------------------------------------------------------------------------
977 // ----------------------------------------------------------------------------
979 void wxFileName::SetFullName(const wxString
& fullname
)
981 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
984 wxString
wxFileName::GetFullName() const
986 wxString fullname
= m_name
;
987 if ( !m_ext
.empty() )
989 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
995 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
997 format
= GetFormat( format
);
1000 size_t count
= m_dirs
.GetCount();
1001 for ( size_t i
= 0; i
< count
; i
++ )
1004 if ( add_separator
|| (i
< count
) )
1005 ret
+= wxFILE_SEP_PATH
;
1011 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1013 format
= GetFormat(format
);
1017 // first put the volume
1018 if ( !m_volume
.empty() )
1021 // Special Windows UNC paths hack, part 2: undo what we did in
1022 // SplitPath() and make an UNC path if we have a drive which is not a
1023 // single letter (hopefully the network shares can't be one letter only
1024 // although I didn't find any authoritative docs on this)
1025 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1027 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1031 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1036 // then concatenate all the path components using the path separator
1037 size_t dirCount
= m_dirs
.GetCount();
1040 // under Mac, we must have a path separator in the beginning of the
1041 // relative path - otherwise it would be parsed as an absolute one
1042 if ( format
== wxPATH_MAC
&& m_dirs
[0].empty() )
1044 fullpath
+= wxFILE_SEP_PATH_MAC
;
1047 wxChar chPathSep
= GetPathSeparators(format
)[0u];
1048 if ( format
== wxPATH_VMS
)
1050 fullpath
+= _T('[');
1053 for ( size_t i
= 0; i
< dirCount
; i
++ )
1055 // under VMS, we shouldn't have a leading dot
1056 if ( i
&& (format
!= wxPATH_VMS
|| !m_dirs
[i
- 1].empty()) )
1057 fullpath
+= chPathSep
;
1059 fullpath
+= m_dirs
[i
];
1062 if ( format
== wxPATH_VMS
)
1064 fullpath
+= _T(']');
1068 // separate the file name from the last directory, notice that we
1069 // intentionally do it even if the name and extension are empty as
1070 // this allows us to distinguish the directories from the file
1071 // names (the directories have the trailing slash)
1072 fullpath
+= chPathSep
;
1076 // finally add the file name and extension
1077 fullpath
+= GetFullName();
1082 // Return the short form of the path (returns identity on non-Windows platforms)
1083 wxString
wxFileName::GetShortPath() const
1085 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1086 wxString
path(GetFullPath());
1088 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1092 ok
= ::GetShortPathName
1095 pathOut
.GetWriteBuf(sz
),
1098 pathOut
.UngetWriteBuf();
1105 return GetFullPath();
1109 // Return the long form of the path (returns identity on non-Windows platforms)
1110 wxString
wxFileName::GetLongPath() const
1113 path
= GetFullPath();
1115 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1116 bool success
= FALSE
;
1118 // VZ: this code was disabled, why?
1119 #if 0 // wxUSE_DYNLIB_CLASS
1120 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1122 static bool s_triedToLoad
= FALSE
;
1124 if ( !s_triedToLoad
)
1126 s_triedToLoad
= TRUE
;
1127 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1130 // may succeed or fail depending on the Windows version
1131 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1133 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1135 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1138 wxDllLoader::UnloadLibrary(dllKernel
);
1140 if ( s_pfnGetLongPathName
)
1142 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1143 bool ok
= dwSize
> 0;
1147 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1151 ok
= (*s_pfnGetLongPathName
)
1154 pathOut
.GetWriteBuf(sz
),
1157 pathOut
.UngetWriteBuf();
1167 #endif // wxUSE_DYNLIB_CLASS
1171 // The OS didn't support GetLongPathName, or some other error.
1172 // We need to call FindFirstFile on each component in turn.
1174 WIN32_FIND_DATA findFileData
;
1176 pathOut
= wxEmptyString
;
1178 wxArrayString dirs
= GetDirs();
1179 dirs
.Add(GetFullName());
1183 size_t count
= dirs
.GetCount();
1184 for ( size_t i
= 0; i
< count
; i
++ )
1186 // We're using pathOut to collect the long-name path, but using a
1187 // temporary for appending the last path component which may be
1189 tmpPath
= pathOut
+ dirs
[i
];
1191 if ( tmpPath
.empty() )
1194 if ( tmpPath
.Last() == wxT(':') )
1196 // Can't pass a drive and root dir to FindFirstFile,
1197 // so continue to next dir
1198 tmpPath
+= wxFILE_SEP_PATH
;
1203 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1204 if (hFind
== INVALID_HANDLE_VALUE
)
1206 // Error: return immediately with the original path
1210 pathOut
+= findFileData
.cFileName
;
1211 if ( (i
< (count
-1)) )
1212 pathOut
+= wxFILE_SEP_PATH
;
1219 #endif // Win32/!Win32
1224 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1226 if (format
== wxPATH_NATIVE
)
1228 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1229 format
= wxPATH_DOS
;
1230 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1231 format
= wxPATH_MAC
;
1232 #elif defined(__VMS)
1233 format
= wxPATH_VMS
;
1235 format
= wxPATH_UNIX
;
1241 // ----------------------------------------------------------------------------
1242 // path splitting function
1243 // ----------------------------------------------------------------------------
1246 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1247 wxString
*pstrVolume
,
1251 wxPathFormat format
)
1253 format
= GetFormat(format
);
1255 wxString fullpath
= fullpathWithVolume
;
1257 // under VMS the end of the path is ']', not the path separator used to
1258 // separate the components
1259 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1260 : GetPathSeparators(format
);
1262 // special Windows UNC paths hack: transform \\share\path into share:path
1263 if ( format
== wxPATH_DOS
)
1265 if ( fullpath
.length() >= 4 &&
1266 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1267 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1269 fullpath
.erase(0, 2);
1271 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1272 if ( posFirstSlash
!= wxString::npos
)
1274 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1276 // UNC paths are always absolute, right? (FIXME)
1277 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1282 // We separate the volume here
1283 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1285 wxString sepVol
= GetVolumeSeparator(format
);
1287 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1288 if ( posFirstColon
!= wxString::npos
)
1292 *pstrVolume
= fullpath
.Left(posFirstColon
);
1295 // remove the volume name and the separator from the full path
1296 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1300 // find the positions of the last dot and last path separator in the path
1301 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1302 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1304 if ( (posLastDot
!= wxString::npos
) &&
1305 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1307 if ( (posLastDot
== 0) ||
1308 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1310 // under Unix and VMS, dot may be (and commonly is) the first
1311 // character of the filename, don't treat the entire filename as
1312 // extension in this case
1313 posLastDot
= wxString::npos
;
1317 // if we do have a dot and a slash, check that the dot is in the name part
1318 if ( (posLastDot
!= wxString::npos
) &&
1319 (posLastSlash
!= wxString::npos
) &&
1320 (posLastDot
< posLastSlash
) )
1322 // the dot is part of the path, not the start of the extension
1323 posLastDot
= wxString::npos
;
1326 // now fill in the variables provided by user
1329 if ( posLastSlash
== wxString::npos
)
1336 // take everything up to the path separator but take care to make
1337 // tha path equal to something like '/', not empty, for the files
1338 // immediately under root directory
1339 size_t len
= posLastSlash
;
1343 *pstrPath
= fullpath
.Left(len
);
1345 // special VMS hack: remove the initial bracket
1346 if ( format
== wxPATH_VMS
)
1348 if ( (*pstrPath
)[0u] == _T('[') )
1349 pstrPath
->erase(0, 1);
1356 // take all characters starting from the one after the last slash and
1357 // up to, but excluding, the last dot
1358 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1360 if ( posLastDot
== wxString::npos
)
1362 // take all until the end
1363 count
= wxString::npos
;
1365 else if ( posLastSlash
== wxString::npos
)
1369 else // have both dot and slash
1371 count
= posLastDot
- posLastSlash
- 1;
1374 *pstrName
= fullpath
.Mid(nStart
, count
);
1379 if ( posLastDot
== wxString::npos
)
1386 // take everything after the dot
1387 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1393 void wxFileName::SplitPath(const wxString
& fullpath
,
1397 wxPathFormat format
)
1400 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1402 if ( path
&& !volume
.empty() )
1404 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1408 // ----------------------------------------------------------------------------
1410 // ----------------------------------------------------------------------------
1412 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1413 const wxDateTime
*dtAccess
,
1414 const wxDateTime
*dtMod
)
1416 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1417 if ( !dtAccess
&& !dtMod
)
1419 // can't modify the creation time anyhow, don't try
1423 // if dtAccess or dtMod is not specified, use the other one (which must be
1424 // non NULL because of the test above) for both times
1426 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1427 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1428 if ( utime(GetFullPath(), &utm
) == 0 )
1432 #elif defined(__WIN32__)
1433 wxFileHandle
fh(GetFullPath());
1436 FILETIME ftAccess
, ftCreate
, ftWrite
;
1439 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1441 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1443 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1445 if ( ::SetFileTime(fh
,
1446 dtCreate
? &ftCreate
: NULL
,
1447 dtAccess
? &ftAccess
: NULL
,
1448 dtMod
? &ftWrite
: NULL
) )
1453 #else // other platform
1456 wxLogSysError(_("Failed to modify file times for '%s'"),
1457 GetFullPath().c_str());
1462 bool wxFileName::Touch()
1464 #if defined(__UNIX_LIKE__)
1465 // under Unix touching file is simple: just pass NULL to utime()
1466 if ( utime(GetFullPath(), NULL
) == 0 )
1471 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1474 #else // other platform
1475 wxDateTime dtNow
= wxDateTime::Now();
1477 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1481 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1483 wxDateTime
*dtChange
) const
1485 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1487 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1490 dtAccess
->Set(stBuf
.st_atime
);
1492 dtMod
->Set(stBuf
.st_mtime
);
1494 dtChange
->Set(stBuf
.st_ctime
);
1498 #elif defined(__WIN32__)
1499 wxFileHandle
fh(GetFullPath());
1502 FILETIME ftAccess
, ftCreate
, ftWrite
;
1504 if ( ::GetFileTime(fh
,
1505 dtMod
? &ftCreate
: NULL
,
1506 dtAccess
? &ftAccess
: NULL
,
1507 dtChange
? &ftWrite
: NULL
) )
1510 ConvertFileTimeToWx(dtMod
, ftCreate
);
1512 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1514 ConvertFileTimeToWx(dtChange
, ftWrite
);
1519 #else // other platform
1522 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1523 GetFullPath().c_str());