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 :::file is not yet supported. TODO.
37 wxPATH_VMS: VMS native format, absolute file names have the form
38 <device>:[dir1.dir2.dir3]file.txt
40 <device>:[000000.dir1.dir2.dir3]file.txt
42 the <device> is the physical device (i.e. disk). 000000 is the
43 root directory on the device which can be omitted.
45 Note that VMS uses different separators unlike Unix:
46 : always after the device. If the path does not contain : than
47 the default (the device of the current directory) is assumed.
48 [ start of directory specyfication
49 . separator between directory and subdirectory
50 ] between directory and file
53 // ============================================================================
55 // ============================================================================
57 // ----------------------------------------------------------------------------
59 // ----------------------------------------------------------------------------
62 #pragma implementation "filename.h"
65 // For compilers that support precompilation, includes "wx.h".
66 #include "wx/wxprec.h"
77 #include "wx/filename.h"
78 #include "wx/tokenzr.h"
79 #include "wx/config.h" // for wxExpandEnvVars
82 #if wxUSE_DYNLIB_CLASS
83 #include "wx/dynlib.h"
86 // For GetShort/LongPathName
90 #include "wx/msw/winundef.h"
93 // utime() is POSIX so should normally be available on all Unices
95 #include <sys/types.h>
107 // ----------------------------------------------------------------------------
109 // ----------------------------------------------------------------------------
111 // small helper class which opens and closes the file - we use it just to get
112 // a file handle for the given file name to pass it to some Win32 API function
113 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
118 wxFileHandle(const wxString
& filename
)
120 m_hFile
= ::CreateFile
123 GENERIC_READ
, // access mask
125 NULL
, // no secutity attr
126 OPEN_EXISTING
, // creation disposition
128 NULL
// no template file
131 if ( m_hFile
== INVALID_HANDLE_VALUE
)
133 wxLogSysError(_("Failed to open '%s' for reading"),
140 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
142 if ( !::CloseHandle(m_hFile
) )
144 wxLogSysError(_("Failed to close file handle"));
149 // return TRUE only if the file could be opened successfully
150 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
153 operator HANDLE() const { return m_hFile
; }
161 // ----------------------------------------------------------------------------
163 // ----------------------------------------------------------------------------
165 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
167 // convert between wxDateTime and FILETIME which is a 64-bit value representing
168 // the number of 100-nanosecond intervals since January 1, 1601.
170 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
171 // FILETIME reference point (January 1, 1601)
172 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
174 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
176 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
178 // convert 100ns to ms
181 // move it to our Epoch
182 ll
-= FILETIME_EPOCH_OFFSET
;
184 *dt
= wxDateTime(ll
);
187 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
189 // do the reverse of ConvertFileTimeToWx()
190 wxLongLong ll
= dt
.GetValue();
192 ll
+= FILETIME_EPOCH_OFFSET
;
194 ft
->dwHighDateTime
= ll
.GetHi();
195 ft
->dwLowDateTime
= ll
.GetLo();
200 // ============================================================================
202 // ============================================================================
204 // ----------------------------------------------------------------------------
205 // wxFileName construction
206 // ----------------------------------------------------------------------------
208 void wxFileName::Assign( const wxFileName
&filepath
)
210 m_volume
= filepath
.GetVolume();
211 m_dirs
= filepath
.GetDirs();
212 m_name
= filepath
.GetName();
213 m_ext
= filepath
.GetExt();
216 void wxFileName::Assign(const wxString
& volume
,
217 const wxString
& path
,
218 const wxString
& name
,
220 wxPathFormat format
)
222 wxStringTokenizer
tn(path
, GetPathSeparators(format
));
225 while ( tn
.HasMoreTokens() )
227 wxString token
= tn
.GetNextToken();
229 // if the path starts with a slash, we do need the first empty dir
230 // entry to be able to tell later that it was an absolute path, but
231 // otherwise ignore the double slashes
232 if ( m_dirs
.IsEmpty() || !token
.IsEmpty() )
241 void wxFileName::Assign(const wxString
& fullpath
,
244 wxString volume
, path
, name
, ext
;
245 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
247 Assign(volume
, path
, name
, ext
, format
);
250 void wxFileName::Assign(const wxString
& fullpathOrig
,
251 const wxString
& fullname
,
254 // always recognize fullpath as directory, even if it doesn't end with a
256 wxString fullpath
= fullpathOrig
;
257 if ( !wxEndsWithPathSeparator(fullpath
) )
259 fullpath
+= GetPathSeparators(format
)[0u];
262 wxString volume
, path
, name
, ext
;
264 // do some consistency checks in debug mode: the name should be really just
265 // the filename and the path should be realyl just a path
267 wxString pathDummy
, nameDummy
, extDummy
;
269 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
271 wxASSERT_MSG( pathDummy
.empty(),
272 _T("the file name shouldn't contain the path") );
274 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
276 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
277 _T("the path shouldn't contain file name nor extension") );
279 #else // !__WXDEBUG__
280 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
281 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
282 #endif // __WXDEBUG__/!__WXDEBUG__
284 Assign(volume
, path
, name
, ext
, format
);
287 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
289 Assign(dir
, _T(""), format
);
292 void wxFileName::Clear()
298 m_ext
= wxEmptyString
;
302 wxFileName
wxFileName::FileName(const wxString
& file
)
304 return wxFileName(file
);
308 wxFileName
wxFileName::DirName(const wxString
& dir
)
315 // ----------------------------------------------------------------------------
317 // ----------------------------------------------------------------------------
319 bool wxFileName::FileExists()
321 return wxFileName::FileExists( GetFullPath() );
324 bool wxFileName::FileExists( const wxString
&file
)
326 return ::wxFileExists( file
);
329 bool wxFileName::DirExists()
331 return wxFileName::DirExists( GetFullPath() );
334 bool wxFileName::DirExists( const wxString
&dir
)
336 return ::wxDirExists( dir
);
339 // ----------------------------------------------------------------------------
340 // CWD and HOME stuff
341 // ----------------------------------------------------------------------------
343 void wxFileName::AssignCwd(const wxString
& volume
)
345 AssignDir(wxFileName::GetCwd(volume
));
349 wxString
wxFileName::GetCwd(const wxString
& volume
)
351 // if we have the volume, we must get the current directory on this drive
352 // and to do this we have to chdir to this volume - at least under Windows,
353 // I don't know how to get the current drive on another volume elsewhere
356 if ( !volume
.empty() )
359 SetCwd(volume
+ GetVolumeSeparator());
362 wxString cwd
= ::wxGetCwd();
364 if ( !volume
.empty() )
372 bool wxFileName::SetCwd()
374 return wxFileName::SetCwd( GetFullPath() );
377 bool wxFileName::SetCwd( const wxString
&cwd
)
379 return ::wxSetWorkingDirectory( cwd
);
382 void wxFileName::AssignHomeDir()
384 AssignDir(wxFileName::GetHomeDir());
387 wxString
wxFileName::GetHomeDir()
389 return ::wxGetHomeDir();
392 void wxFileName::AssignTempFileName( const wxString
& prefix
)
394 wxString tempname
= CreateTempFileName(prefix
);
395 if ( tempname
.empty() )
397 // error, failed to get temp file name
407 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
409 wxString path
, dir
, name
;
411 // use the directory specified by the prefix
412 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
414 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
419 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
421 wxLogLastError(_T("GetTempPath"));
426 // GetTempFileName() fails if we pass it an empty string
431 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
433 wxLogLastError(_T("GetTempFileName"));
438 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
444 #elif defined(__WXPM__)
445 // for now just create a file
447 // future enhancements can be to set some extended attributes for file
448 // systems OS/2 supports that have them (HPFS, FAT32) and security
450 static const wxChar
*szMktempSuffix
= wxT("XXX");
451 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
453 // Temporarily remove - MN
455 ::DosCreateDir(wxStringBuffer(MAX_PATH
), NULL
);
458 #else // !Windows, !OS/2
461 dir
= wxGetenv(_T("TMP"));
464 dir
= wxGetenv(_T("TEMP"));
476 if ( !wxEndsWithPathSeparator(dir
) &&
477 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
485 // scratch space for mkstemp()
486 path
+= _T("XXXXXX");
488 // can use the cast here because the length doesn't change and the string
490 if ( mkstemp((char *)path
.mb_str()) == -1 )
492 // this might be not necessary as mkstemp() on most systems should have
493 // already done it but it doesn't hurt neither...
496 //else: file already created
497 #else // !HAVE_MKSTEMP
501 path
+= _T("XXXXXX");
503 if ( !mktemp((char *)path
.mb_str()) )
507 #else // !HAVE_MKTEMP
508 // generate the unique file name ourselves
509 path
<< (unsigned int)getpid();
513 static const size_t numTries
= 1000;
514 for ( size_t n
= 0; n
< numTries
; n
++ )
516 // 3 hex digits is enough for numTries == 1000 < 4096
517 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
518 if ( !wxFile::Exists(pathTry
) )
527 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
531 // create the file - of course, there is a race condition here, this is
532 // why we always prefer using mkstemp()...
534 if ( !file
.Open(path
, wxFile::write_excl
, wxS_IRUSR
| wxS_IWUSR
) )
536 // FIXME: If !ok here should we loop and try again with another
537 // file name? That is the standard recourse if open(O_EXCL)
538 // fails, though of course it should be protected against
539 // possible infinite looping too.
541 wxLogError(_("Failed to open temporary file."));
546 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
548 #endif // Windows/!Windows
552 wxLogSysError(_("Failed to create a temporary file name"));
558 // ----------------------------------------------------------------------------
559 // directory operations
560 // ----------------------------------------------------------------------------
562 bool wxFileName::Mkdir( int perm
, bool full
)
564 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
567 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
571 wxFileName
filename(dir
);
572 wxArrayString dirs
= filename
.GetDirs();
573 dirs
.Add(filename
.GetName());
575 size_t count
= dirs
.GetCount();
579 for ( i
= 0; i
< count
; i
++ )
583 if (currPath
.Last() == wxT(':'))
585 // Can't create a root directory so continue to next dir
586 currPath
+= wxFILE_SEP_PATH
;
590 if (!DirExists(currPath
))
591 if (!wxMkdir(currPath
, perm
))
594 if ( (i
< (count
-1)) )
595 currPath
+= wxFILE_SEP_PATH
;
598 return (noErrors
== 0);
602 return ::wxMkdir( dir
, perm
);
605 bool wxFileName::Rmdir()
607 return wxFileName::Rmdir( GetFullPath() );
610 bool wxFileName::Rmdir( const wxString
&dir
)
612 return ::wxRmdir( dir
);
615 // ----------------------------------------------------------------------------
616 // path normalization
617 // ----------------------------------------------------------------------------
619 bool wxFileName::Normalize(wxPathNormalize flags
,
623 // the existing path components
624 wxArrayString dirs
= GetDirs();
626 // the path to prepend in front to make the path absolute
629 format
= GetFormat(format
);
631 // make the path absolute
632 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute() )
636 curDir
.AssignCwd(GetVolume());
640 curDir
.AssignDir(cwd
);
643 // the path may be not absolute because it doesn't have the volume name
644 // but in this case we shouldn't modify the directory components of it
645 // but just set the current volume
646 if ( !HasVolume() && curDir
.HasVolume() )
648 SetVolume(curDir
.GetVolume());
652 // yes, it was the case - we don't need curDir then
658 // handle ~ stuff under Unix only
659 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
661 if ( !dirs
.IsEmpty() )
663 wxString dir
= dirs
[0u];
664 if ( !dir
.empty() && dir
[0u] == _T('~') )
666 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
673 // transform relative path into abs one
676 wxArrayString dirsNew
= curDir
.GetDirs();
677 size_t count
= dirs
.GetCount();
678 for ( size_t n
= 0; n
< count
; n
++ )
680 dirsNew
.Add(dirs
[n
]);
686 // now deal with ".", ".." and the rest
688 size_t count
= dirs
.GetCount();
689 for ( size_t n
= 0; n
< count
; n
++ )
691 wxString dir
= dirs
[n
];
693 if ( flags
& wxPATH_NORM_DOTS
)
695 if ( dir
== wxT(".") )
701 if ( dir
== wxT("..") )
703 if ( m_dirs
.IsEmpty() )
705 wxLogError(_("The path '%s' contains too many \"..\"!"),
706 GetFullPath().c_str());
710 m_dirs
.Remove(m_dirs
.GetCount() - 1);
715 if ( flags
& wxPATH_NORM_ENV_VARS
)
717 dir
= wxExpandEnvVars(dir
);
720 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
728 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
730 // VZ: expand env vars here too?
736 #if defined(__WIN32__)
737 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
739 Assign(GetLongPath());
746 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
748 wxFileName
fnBase(pathBase
, format
);
750 // get cwd only once - small time saving
751 wxString cwd
= wxGetCwd();
752 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
753 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
755 bool withCase
= IsCaseSensitive(format
);
757 // we can't do anything if the files live on different volumes
758 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
764 // same drive, so we don't need our volume
767 // remove common directories starting at the top
768 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
769 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
772 fnBase
.m_dirs
.Remove(0u);
775 // add as many ".." as needed
776 size_t count
= fnBase
.m_dirs
.GetCount();
777 for ( size_t i
= 0; i
< count
; i
++ )
779 m_dirs
.Insert(wxT(".."), 0u);
786 // ----------------------------------------------------------------------------
787 // filename kind tests
788 // ----------------------------------------------------------------------------
790 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
792 wxFileName fn1
= *this,
795 // get cwd only once - small time saving
796 wxString cwd
= wxGetCwd();
797 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
798 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
800 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
803 // TODO: compare inodes for Unix, this works even when filenames are
804 // different but files are the same (symlinks) (VZ)
810 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
812 // only Unix filenames are truely case-sensitive
813 return GetFormat(format
) == wxPATH_UNIX
;
816 bool wxFileName::IsAbsolute( wxPathFormat format
)
818 // if we have no path, we can't be an abs filename
819 if ( m_dirs
.IsEmpty() )
824 format
= GetFormat(format
);
826 if ( format
== wxPATH_UNIX
)
828 const wxString
& str
= m_dirs
[0u];
831 // the path started with '/', it's an absolute one
835 // the path is absolute if it starts with a path separator or
836 // with "~" or "~user"
839 return IsPathSeparator(ch
, format
) || ch
== _T('~');
843 // must have the drive
844 if ( m_volume
.empty() )
850 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
854 return m_dirs
[0u].empty();
857 // TODO: what is the relative path format here?
861 return !m_dirs
[0u].empty();
867 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
871 if ( GetFormat(format
) != wxPATH_UNIX
)
873 // so far it is the same for all systems which have it
874 sepVol
= wxFILE_SEP_DSK
;
876 //else: leave empty, no volume separators under Unix
882 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
885 switch ( GetFormat(format
) )
888 // accept both as native APIs do but put the native one first as
889 // this is the one we use in GetFullPath()
890 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
894 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
898 seps
= wxFILE_SEP_PATH_UNIX
;
902 seps
= wxFILE_SEP_PATH_MAC
;
906 seps
= wxFILE_SEP_PATH_VMS
;
914 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
916 // wxString::Find() doesn't work as expected with NUL - it will always find
917 // it, so it is almost surely a bug if this function is called with NUL arg
918 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
920 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
923 bool wxFileName::IsWild( wxPathFormat format
)
925 // FIXME: this is probably false for Mac and this is surely wrong for most
926 // of Unix shells (think about "[...]")
928 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
931 // ----------------------------------------------------------------------------
932 // path components manipulation
933 // ----------------------------------------------------------------------------
935 void wxFileName::AppendDir( const wxString
&dir
)
940 void wxFileName::PrependDir( const wxString
&dir
)
942 m_dirs
.Insert( dir
, 0 );
945 void wxFileName::InsertDir( int before
, const wxString
&dir
)
947 m_dirs
.Insert( dir
, before
);
950 void wxFileName::RemoveDir( int pos
)
952 m_dirs
.Remove( (size_t)pos
);
955 // ----------------------------------------------------------------------------
957 // ----------------------------------------------------------------------------
959 void wxFileName::SetFullName(const wxString
& fullname
)
961 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
964 wxString
wxFileName::GetFullName() const
966 wxString fullname
= m_name
;
967 if ( !m_ext
.empty() )
969 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
975 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
977 format
= GetFormat( format
);
980 size_t count
= m_dirs
.GetCount();
981 for ( size_t i
= 0; i
< count
; i
++ )
984 if ( add_separator
|| (i
< count
) )
985 ret
+= wxFILE_SEP_PATH
;
991 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
993 format
= GetFormat(format
);
997 // first put the volume
998 if ( !m_volume
.empty() )
1000 // special Windows UNC paths hack, part 2: undo what we did in
1001 // SplitPath() and make an UNC path if we have a drive which is not a
1002 // single letter (hopefully the network shares can't be one letter only
1003 // although I didn't find any authoritative docs on this)
1004 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1006 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1010 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1014 // then concatenate all the path components using the path separator
1015 size_t dirCount
= m_dirs
.GetCount();
1018 // under Mac, we must have a path separator in the beginning of the
1019 // relative path - otherwise it would be parsed as an absolute one
1020 if ( format
== wxPATH_MAC
&& m_volume
.empty() && !m_dirs
[0].empty() )
1022 fullpath
+= wxFILE_SEP_PATH_MAC
;
1025 wxChar chPathSep
= GetPathSeparators(format
)[0u];
1026 if ( format
== wxPATH_VMS
)
1028 fullpath
+= _T('[');
1031 for ( size_t i
= 0; i
< dirCount
; i
++ )
1033 // under VMS, we shouldn't have a leading dot
1034 if ( i
&& (format
!= wxPATH_VMS
|| !m_dirs
[i
- 1].empty()) )
1035 fullpath
+= chPathSep
;
1037 fullpath
+= m_dirs
[i
];
1040 if ( format
== wxPATH_VMS
)
1042 fullpath
+= _T(']');
1046 // separate the file name from the last directory, notice that we
1047 // intentionally do it even if the name and extension are empty as
1048 // this allows us to distinguish the directories from the file
1049 // names (the directories have the trailing slash)
1050 fullpath
+= chPathSep
;
1054 // finally add the file name and extension
1055 fullpath
+= GetFullName();
1060 // Return the short form of the path (returns identity on non-Windows platforms)
1061 wxString
wxFileName::GetShortPath() const
1063 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1064 wxString
path(GetFullPath());
1066 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1070 ok
= ::GetShortPathName
1073 pathOut
.GetWriteBuf(sz
),
1076 pathOut
.UngetWriteBuf();
1083 return GetFullPath();
1087 // Return the long form of the path (returns identity on non-Windows platforms)
1088 wxString
wxFileName::GetLongPath() const
1091 path
= GetFullPath();
1093 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1094 bool success
= FALSE
;
1096 // VZ: this code was disabled, why?
1097 #if 0 // wxUSE_DYNLIB_CLASS
1098 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1100 static bool s_triedToLoad
= FALSE
;
1102 if ( !s_triedToLoad
)
1104 s_triedToLoad
= TRUE
;
1105 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1108 // may succeed or fail depending on the Windows version
1109 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1111 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1113 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1116 wxDllLoader::UnloadLibrary(dllKernel
);
1118 if ( s_pfnGetLongPathName
)
1120 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1121 bool ok
= dwSize
> 0;
1125 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1129 ok
= (*s_pfnGetLongPathName
)
1132 pathOut
.GetWriteBuf(sz
),
1135 pathOut
.UngetWriteBuf();
1145 #endif // wxUSE_DYNLIB_CLASS
1149 // The OS didn't support GetLongPathName, or some other error.
1150 // We need to call FindFirstFile on each component in turn.
1152 WIN32_FIND_DATA findFileData
;
1154 pathOut
= wxEmptyString
;
1156 wxArrayString dirs
= GetDirs();
1157 dirs
.Add(GetFullName());
1161 size_t count
= dirs
.GetCount();
1162 for ( size_t i
= 0; i
< count
; i
++ )
1164 // We're using pathOut to collect the long-name path, but using a
1165 // temporary for appending the last path component which may be
1167 tmpPath
= pathOut
+ dirs
[i
];
1169 if ( tmpPath
.empty() )
1172 if ( tmpPath
.Last() == wxT(':') )
1174 // Can't pass a drive and root dir to FindFirstFile,
1175 // so continue to next dir
1176 tmpPath
+= wxFILE_SEP_PATH
;
1181 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1182 if (hFind
== INVALID_HANDLE_VALUE
)
1184 // Error: return immediately with the original path
1188 pathOut
+= findFileData
.cFileName
;
1189 if ( (i
< (count
-1)) )
1190 pathOut
+= wxFILE_SEP_PATH
;
1197 #endif // Win32/!Win32
1202 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1204 if (format
== wxPATH_NATIVE
)
1206 #if defined(__WXMSW__) || defined(__WXPM__)
1207 format
= wxPATH_DOS
;
1208 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1209 format
= wxPATH_MAC
;
1210 #elif defined(__VMS)
1211 format
= wxPATH_VMS
;
1213 format
= wxPATH_UNIX
;
1219 // ----------------------------------------------------------------------------
1220 // path splitting function
1221 // ----------------------------------------------------------------------------
1224 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1225 wxString
*pstrVolume
,
1229 wxPathFormat format
)
1231 format
= GetFormat(format
);
1233 wxString fullpath
= fullpathWithVolume
;
1235 // under VMS the end of the path is ']', not the path separator used to
1236 // separate the components
1237 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1238 : GetPathSeparators(format
);
1240 // special Windows UNC paths hack: transform \\share\path into share:path
1241 if ( format
== wxPATH_DOS
)
1243 if ( fullpath
.length() >= 4 &&
1244 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1245 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1247 fullpath
.erase(0, 2);
1249 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1250 if ( posFirstSlash
!= wxString::npos
)
1252 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1254 // UNC paths are always absolute, right? (FIXME)
1255 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1260 // do we have the volume name in the beginning?
1261 wxString sepVol
= GetVolumeSeparator(format
);
1262 if ( !sepVol
.empty() )
1264 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1265 if ( posFirstColon
!= wxString::npos
)
1269 *pstrVolume
= fullpath
.Left(posFirstColon
);
1272 // remove the volume name and the separator from the full path
1273 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1277 // find the positions of the last dot and last path separator in the path
1278 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1279 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1281 if ( (posLastDot
!= wxString::npos
) &&
1282 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1284 if ( (posLastDot
== 0) ||
1285 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1287 // under Unix and VMS, dot may be (and commonly is) the first
1288 // character of the filename, don't treat the entire filename as
1289 // extension in this case
1290 posLastDot
= wxString::npos
;
1294 // if we do have a dot and a slash, check that the dot is in the name part
1295 if ( (posLastDot
!= wxString::npos
) &&
1296 (posLastSlash
!= wxString::npos
) &&
1297 (posLastDot
< posLastSlash
) )
1299 // the dot is part of the path, not the start of the extension
1300 posLastDot
= wxString::npos
;
1303 // now fill in the variables provided by user
1306 if ( posLastSlash
== wxString::npos
)
1313 // take everything up to the path separator but take care to make
1314 // tha path equal to something like '/', not empty, for the files
1315 // immediately under root directory
1316 size_t len
= posLastSlash
;
1320 *pstrPath
= fullpath
.Left(len
);
1322 // special VMS hack: remove the initial bracket
1323 if ( format
== wxPATH_VMS
)
1325 if ( (*pstrPath
)[0u] == _T('[') )
1326 pstrPath
->erase(0, 1);
1333 // take all characters starting from the one after the last slash and
1334 // up to, but excluding, the last dot
1335 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1337 if ( posLastDot
== wxString::npos
)
1339 // take all until the end
1340 count
= wxString::npos
;
1342 else if ( posLastSlash
== wxString::npos
)
1346 else // have both dot and slash
1348 count
= posLastDot
- posLastSlash
- 1;
1351 *pstrName
= fullpath
.Mid(nStart
, count
);
1356 if ( posLastDot
== wxString::npos
)
1363 // take everything after the dot
1364 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1370 void wxFileName::SplitPath(const wxString
& fullpath
,
1374 wxPathFormat format
)
1377 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1379 if ( path
&& !volume
.empty() )
1381 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1385 // ----------------------------------------------------------------------------
1387 // ----------------------------------------------------------------------------
1389 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1390 const wxDateTime
*dtAccess
,
1391 const wxDateTime
*dtMod
)
1393 #if defined(__UNIX_LIKE__)
1394 if ( !dtAccess
&& !dtMod
)
1396 // can't modify the creation time anyhow, don't try
1400 // if dtAccess or dtMod is not specified, use the other one (which must be
1401 // non NULL because of the test above) for both times
1403 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1404 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1405 if ( utime(GetFullPath(), &utm
) == 0 )
1409 #elif defined(__WIN32__)
1410 wxFileHandle
fh(GetFullPath());
1413 FILETIME ftAccess
, ftCreate
, ftWrite
;
1416 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1418 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1420 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1422 if ( ::SetFileTime(fh
,
1423 dtCreate
? &ftCreate
: NULL
,
1424 dtAccess
? &ftAccess
: NULL
,
1425 dtMod
? &ftWrite
: NULL
) )
1430 #else // other platform
1433 wxLogSysError(_("Failed to modify file times for '%s'"),
1434 GetFullPath().c_str());
1439 bool wxFileName::Touch()
1441 #if defined(__UNIX_LIKE__)
1442 // under Unix touching file is simple: just pass NULL to utime()
1443 if ( utime(GetFullPath(), NULL
) == 0 )
1448 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1451 #else // other platform
1452 wxDateTime dtNow
= wxDateTime::Now();
1454 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1458 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1460 wxDateTime
*dtChange
) const
1462 #if defined(__UNIX_LIKE__)
1464 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1467 dtAccess
->Set(stBuf
.st_atime
);
1469 dtMod
->Set(stBuf
.st_mtime
);
1471 dtChange
->Set(stBuf
.st_ctime
);
1475 #elif defined(__WXMAC__)
1477 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1480 dtAccess
->Set(stBuf
.st_atime
);
1482 dtMod
->Set(stBuf
.st_mtime
);
1484 dtChange
->Set(stBuf
.st_ctime
);
1488 #elif defined(__WIN32__)
1489 wxFileHandle
fh(GetFullPath());
1492 FILETIME ftAccess
, ftCreate
, ftWrite
;
1494 if ( ::GetFileTime(fh
,
1495 dtMod
? &ftCreate
: NULL
,
1496 dtAccess
? &ftAccess
: NULL
,
1497 dtChange
? &ftWrite
: NULL
) )
1500 ConvertFileTimeToWx(dtMod
, ftCreate
);
1502 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1504 ConvertFileTimeToWx(dtChange
, ftWrite
);
1509 #else // other platform
1512 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1513 GetFullPath().c_str());