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 // ----------------------------------------------------------------------------
747 // filename kind tests
748 // ----------------------------------------------------------------------------
750 bool wxFileName::SameAs( const wxFileName
&filepath
, wxPathFormat format
)
752 wxFileName fn1
= *this,
755 // get cwd only once - small time saving
756 wxString cwd
= wxGetCwd();
757 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
758 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
760 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
763 // TODO: compare inodes for Unix, this works even when filenames are
764 // different but files are the same (symlinks) (VZ)
770 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
772 // only Unix filenames are truely case-sensitive
773 return GetFormat(format
) == wxPATH_UNIX
;
776 bool wxFileName::IsAbsolute( wxPathFormat format
)
778 // if we have no path, we can't be an abs filename
779 if ( m_dirs
.IsEmpty() )
784 format
= GetFormat(format
);
786 if ( format
== wxPATH_UNIX
)
788 const wxString
& str
= m_dirs
[0u];
791 // the path started with '/', it's an absolute one
795 // the path is absolute if it starts with a path separator or
796 // with "~" or "~user"
799 return IsPathSeparator(ch
, format
) || ch
== _T('~');
803 // must have the drive
804 if ( m_volume
.empty() )
810 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
814 return m_dirs
[0u].empty();
817 // TODO: what is the relative path format here?
821 return !m_dirs
[0u].empty();
827 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
831 if ( GetFormat(format
) != wxPATH_UNIX
)
833 // so far it is the same for all systems which have it
834 sepVol
= wxFILE_SEP_DSK
;
836 //else: leave empty, no volume separators under Unix
842 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
845 switch ( GetFormat(format
) )
848 // accept both as native APIs do but put the native one first as
849 // this is the one we use in GetFullPath()
850 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
854 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
858 seps
= wxFILE_SEP_PATH_UNIX
;
862 seps
= wxFILE_SEP_PATH_MAC
;
866 seps
= wxFILE_SEP_PATH_VMS
;
874 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
876 // wxString::Find() doesn't work as expected with NUL - it will always find
877 // it, so it is almost surely a bug if this function is called with NUL arg
878 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
880 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
883 bool wxFileName::IsWild( wxPathFormat format
)
885 // FIXME: this is probably false for Mac and this is surely wrong for most
886 // of Unix shells (think about "[...]")
888 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
891 // ----------------------------------------------------------------------------
892 // path components manipulation
893 // ----------------------------------------------------------------------------
895 void wxFileName::AppendDir( const wxString
&dir
)
900 void wxFileName::PrependDir( const wxString
&dir
)
902 m_dirs
.Insert( dir
, 0 );
905 void wxFileName::InsertDir( int before
, const wxString
&dir
)
907 m_dirs
.Insert( dir
, before
);
910 void wxFileName::RemoveDir( int pos
)
912 m_dirs
.Remove( (size_t)pos
);
915 // ----------------------------------------------------------------------------
917 // ----------------------------------------------------------------------------
919 void wxFileName::SetFullName(const wxString
& fullname
)
921 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
924 wxString
wxFileName::GetFullName() const
926 wxString fullname
= m_name
;
927 if ( !m_ext
.empty() )
929 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
935 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
937 format
= GetFormat( format
);
940 size_t count
= m_dirs
.GetCount();
941 for ( size_t i
= 0; i
< count
; i
++ )
944 if ( add_separator
|| (i
< count
) )
945 ret
+= wxFILE_SEP_PATH
;
951 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
953 format
= GetFormat(format
);
957 // first put the volume
958 if ( !m_volume
.empty() )
960 // special Windows UNC paths hack, part 2: undo what we did in
961 // SplitPath() and make an UNC path if we have a drive which is not a
962 // single letter (hopefully the network shares can't be one letter only
963 // although I didn't find any authoritative docs on this)
964 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
966 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
970 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
974 // then concatenate all the path components using the path separator
975 size_t dirCount
= m_dirs
.GetCount();
978 // under Mac, we must have a path separator in the beginning of the
979 // relative path - otherwise it would be parsed as an absolute one
980 if ( format
== wxPATH_MAC
&& m_volume
.empty() && !m_dirs
[0].empty() )
982 fullpath
+= wxFILE_SEP_PATH_MAC
;
985 wxChar chPathSep
= GetPathSeparators(format
)[0u];
986 if ( format
== wxPATH_VMS
)
991 for ( size_t i
= 0; i
< dirCount
; i
++ )
993 // under VMS, we shouldn't have a leading dot
994 if ( i
&& (format
!= wxPATH_VMS
|| !m_dirs
[i
- 1].empty()) )
995 fullpath
+= chPathSep
;
997 fullpath
+= m_dirs
[i
];
1000 if ( format
== wxPATH_VMS
)
1002 fullpath
+= _T(']');
1006 // separate the file name from the last directory, notice that we
1007 // intentionally do it even if the name and extension are empty as
1008 // this allows us to distinguish the directories from the file
1009 // names (the directories have the trailing slash)
1010 fullpath
+= chPathSep
;
1014 // finally add the file name and extension
1015 fullpath
+= GetFullName();
1020 // Return the short form of the path (returns identity on non-Windows platforms)
1021 wxString
wxFileName::GetShortPath() const
1023 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1024 wxString
path(GetFullPath());
1026 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1030 ok
= ::GetShortPathName
1033 pathOut
.GetWriteBuf(sz
),
1036 pathOut
.UngetWriteBuf();
1043 return GetFullPath();
1047 // Return the long form of the path (returns identity on non-Windows platforms)
1048 wxString
wxFileName::GetLongPath() const
1051 path
= GetFullPath();
1053 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1054 bool success
= FALSE
;
1056 // VZ: this code was disabled, why?
1057 #if 0 // wxUSE_DYNLIB_CLASS
1058 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1060 static bool s_triedToLoad
= FALSE
;
1062 if ( !s_triedToLoad
)
1064 s_triedToLoad
= TRUE
;
1065 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1068 // may succeed or fail depending on the Windows version
1069 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1071 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1073 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1076 wxDllLoader::UnloadLibrary(dllKernel
);
1078 if ( s_pfnGetLongPathName
)
1080 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1081 bool ok
= dwSize
> 0;
1085 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1089 ok
= (*s_pfnGetLongPathName
)
1092 pathOut
.GetWriteBuf(sz
),
1095 pathOut
.UngetWriteBuf();
1105 #endif // wxUSE_DYNLIB_CLASS
1109 // The OS didn't support GetLongPathName, or some other error.
1110 // We need to call FindFirstFile on each component in turn.
1112 WIN32_FIND_DATA findFileData
;
1114 pathOut
= wxEmptyString
;
1116 wxArrayString dirs
= GetDirs();
1117 dirs
.Add(GetFullName());
1121 size_t count
= dirs
.GetCount();
1122 for ( size_t i
= 0; i
< count
; i
++ )
1124 // We're using pathOut to collect the long-name path, but using a
1125 // temporary for appending the last path component which may be
1127 tmpPath
= pathOut
+ dirs
[i
];
1129 if ( tmpPath
.empty() )
1132 if ( tmpPath
.Last() == wxT(':') )
1134 // Can't pass a drive and root dir to FindFirstFile,
1135 // so continue to next dir
1136 tmpPath
+= wxFILE_SEP_PATH
;
1141 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1142 if (hFind
== INVALID_HANDLE_VALUE
)
1144 // Error: return immediately with the original path
1148 pathOut
+= findFileData
.cFileName
;
1149 if ( (i
< (count
-1)) )
1150 pathOut
+= wxFILE_SEP_PATH
;
1157 #endif // Win32/!Win32
1162 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1164 if (format
== wxPATH_NATIVE
)
1166 #if defined(__WXMSW__) || defined(__WXPM__)
1167 format
= wxPATH_DOS
;
1168 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1169 format
= wxPATH_MAC
;
1170 #elif defined(__VMS)
1171 format
= wxPATH_VMS
;
1173 format
= wxPATH_UNIX
;
1179 // ----------------------------------------------------------------------------
1180 // path splitting function
1181 // ----------------------------------------------------------------------------
1184 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1185 wxString
*pstrVolume
,
1189 wxPathFormat format
)
1191 format
= GetFormat(format
);
1193 wxString fullpath
= fullpathWithVolume
;
1195 // under VMS the end of the path is ']', not the path separator used to
1196 // separate the components
1197 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1198 : GetPathSeparators(format
);
1200 // special Windows UNC paths hack: transform \\share\path into share:path
1201 if ( format
== wxPATH_DOS
)
1203 if ( fullpath
.length() >= 4 &&
1204 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1205 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1207 fullpath
.erase(0, 2);
1209 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1210 if ( posFirstSlash
!= wxString::npos
)
1212 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1214 // UNC paths are always absolute, right? (FIXME)
1215 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1220 // do we have the volume name in the beginning?
1221 wxString sepVol
= GetVolumeSeparator(format
);
1222 if ( !sepVol
.empty() )
1224 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1225 if ( posFirstColon
!= wxString::npos
)
1229 *pstrVolume
= fullpath
.Left(posFirstColon
);
1232 // remove the volume name and the separator from the full path
1233 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1237 // find the positions of the last dot and last path separator in the path
1238 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1239 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1241 if ( (posLastDot
!= wxString::npos
) &&
1242 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1244 if ( (posLastDot
== 0) ||
1245 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1247 // under Unix and VMS, dot may be (and commonly is) the first
1248 // character of the filename, don't treat the entire filename as
1249 // extension in this case
1250 posLastDot
= wxString::npos
;
1254 // if we do have a dot and a slash, check that the dot is in the name part
1255 if ( (posLastDot
!= wxString::npos
) &&
1256 (posLastSlash
!= wxString::npos
) &&
1257 (posLastDot
< posLastSlash
) )
1259 // the dot is part of the path, not the start of the extension
1260 posLastDot
= wxString::npos
;
1263 // now fill in the variables provided by user
1266 if ( posLastSlash
== wxString::npos
)
1273 // take everything up to the path separator but take care to make
1274 // tha path equal to something like '/', not empty, for the files
1275 // immediately under root directory
1276 size_t len
= posLastSlash
;
1280 *pstrPath
= fullpath
.Left(len
);
1282 // special VMS hack: remove the initial bracket
1283 if ( format
== wxPATH_VMS
)
1285 if ( (*pstrPath
)[0u] == _T('[') )
1286 pstrPath
->erase(0, 1);
1293 // take all characters starting from the one after the last slash and
1294 // up to, but excluding, the last dot
1295 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1297 if ( posLastDot
== wxString::npos
)
1299 // take all until the end
1300 count
= wxString::npos
;
1302 else if ( posLastSlash
== wxString::npos
)
1306 else // have both dot and slash
1308 count
= posLastDot
- posLastSlash
- 1;
1311 *pstrName
= fullpath
.Mid(nStart
, count
);
1316 if ( posLastDot
== wxString::npos
)
1323 // take everything after the dot
1324 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1330 void wxFileName::SplitPath(const wxString
& fullpath
,
1334 wxPathFormat format
)
1337 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1339 if ( path
&& !volume
.empty() )
1341 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1345 // ----------------------------------------------------------------------------
1347 // ----------------------------------------------------------------------------
1349 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1350 const wxDateTime
*dtAccess
,
1351 const wxDateTime
*dtMod
)
1353 #if defined(__UNIX_LIKE__)
1354 if ( !dtAccess
&& !dtMod
)
1356 // can't modify the creation time anyhow, don't try
1360 // if dtAccess or dtMod is not specified, use the other one (which must be
1361 // non NULL because of the test above) for both times
1363 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1364 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1365 if ( utime(GetFullPath(), &utm
) == 0 )
1369 #elif defined(__WIN32__)
1370 wxFileHandle
fh(GetFullPath());
1373 FILETIME ftAccess
, ftCreate
, ftWrite
;
1376 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1378 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1380 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1382 if ( ::SetFileTime(fh
,
1383 dtCreate
? &ftCreate
: NULL
,
1384 dtAccess
? &ftAccess
: NULL
,
1385 dtMod
? &ftWrite
: NULL
) )
1390 #else // other platform
1393 wxLogSysError(_("Failed to modify file times for '%s'"),
1394 GetFullPath().c_str());
1399 bool wxFileName::Touch()
1401 #if defined(__UNIX_LIKE__)
1402 // under Unix touching file is simple: just pass NULL to utime()
1403 if ( utime(GetFullPath(), NULL
) == 0 )
1408 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1411 #else // other platform
1412 wxDateTime dtNow
= wxDateTime::Now();
1414 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1418 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1420 wxDateTime
*dtChange
) const
1422 #if defined(__UNIX_LIKE__)
1424 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1427 dtAccess
->Set(stBuf
.st_atime
);
1429 dtMod
->Set(stBuf
.st_mtime
);
1431 dtChange
->Set(stBuf
.st_ctime
);
1435 #elif defined(__WXMAC__)
1437 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1440 dtAccess
->Set(stBuf
.st_atime
);
1442 dtMod
->Set(stBuf
.st_mtime
);
1444 dtChange
->Set(stBuf
.st_ctime
);
1448 #elif defined(__WIN32__)
1449 wxFileHandle
fh(GetFullPath());
1452 FILETIME ftAccess
, ftCreate
, ftWrite
;
1454 if ( ::GetFileTime(fh
,
1455 dtMod
? &ftCreate
: NULL
,
1456 dtAccess
? &ftAccess
: NULL
,
1457 dtChange
? &ftWrite
: NULL
) )
1460 ConvertFileTimeToWx(dtMod
, ftCreate
);
1462 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1464 ConvertFileTimeToWx(dtChange
, ftWrite
);
1469 #else // other platform
1472 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1473 GetFullPath().c_str());