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
& fullpath
,
251 const wxString
& fullname
,
254 wxString volume
, path
, name
, ext
;
255 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
256 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
258 Assign(volume
, path
, name
, ext
, format
);
261 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
263 // always recognize dir as directory, even if it doesn't end with a slash
264 wxString dirname
= dir
;
265 if ( !wxEndsWithPathSeparator(dirname
) )
267 dirname
+= GetPathSeparators(format
)[0u];
270 Assign(dirname
, _T(""), format
);
273 void wxFileName::Clear()
279 m_ext
= wxEmptyString
;
283 wxFileName
wxFileName::FileName(const wxString
& file
)
285 return wxFileName(file
);
289 wxFileName
wxFileName::DirName(const wxString
& dir
)
296 // ----------------------------------------------------------------------------
298 // ----------------------------------------------------------------------------
300 bool wxFileName::FileExists()
302 return wxFileName::FileExists( GetFullPath() );
305 bool wxFileName::FileExists( const wxString
&file
)
307 return ::wxFileExists( file
);
310 bool wxFileName::DirExists()
312 return wxFileName::DirExists( GetFullPath() );
315 bool wxFileName::DirExists( const wxString
&dir
)
317 return ::wxDirExists( dir
);
320 // ----------------------------------------------------------------------------
321 // CWD and HOME stuff
322 // ----------------------------------------------------------------------------
324 void wxFileName::AssignCwd(const wxString
& volume
)
326 AssignDir(wxFileName::GetCwd(volume
));
330 wxString
wxFileName::GetCwd(const wxString
& volume
)
332 // if we have the volume, we must get the current directory on this drive
333 // and to do this we have to chdir to this volume - at least under Windows,
334 // I don't know how to get the current drive on another volume elsewhere
337 if ( !volume
.empty() )
340 SetCwd(volume
+ GetVolumeSeparator());
343 wxString cwd
= ::wxGetCwd();
345 if ( !volume
.empty() )
353 bool wxFileName::SetCwd()
355 return wxFileName::SetCwd( GetFullPath() );
358 bool wxFileName::SetCwd( const wxString
&cwd
)
360 return ::wxSetWorkingDirectory( cwd
);
363 void wxFileName::AssignHomeDir()
365 AssignDir(wxFileName::GetHomeDir());
368 wxString
wxFileName::GetHomeDir()
370 return ::wxGetHomeDir();
373 void wxFileName::AssignTempFileName( const wxString
& prefix
)
375 wxString tempname
= CreateTempFileName(prefix
);
376 if ( tempname
.empty() )
378 // error, failed to get temp file name
388 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
390 wxString path
, dir
, name
;
392 // use the directory specified by the prefix
393 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
395 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
400 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
402 wxLogLastError(_T("GetTempPath"));
407 // GetTempFileName() fails if we pass it an empty string
412 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
414 wxLogLastError(_T("GetTempFileName"));
419 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
425 #elif defined(__WXPM__)
426 // for now just create a file
428 // future enhancements can be to set some extended attributes for file
429 // systems OS/2 supports that have them (HPFS, FAT32) and security
431 static const wxChar
*szMktempSuffix
= wxT("XXX");
432 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
434 // Temporarily remove - MN
436 ::DosCreateDir(wxStringBuffer(MAX_PATH
), NULL
);
439 #else // !Windows, !OS/2
442 dir
= wxGetenv(_T("TMP"));
445 dir
= wxGetenv(_T("TEMP"));
457 if ( !wxEndsWithPathSeparator(dir
) &&
458 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
466 // scratch space for mkstemp()
467 path
+= _T("XXXXXX");
469 // can use the cast here because the length doesn't change and the string
471 if ( mkstemp((char *)path
.mb_str()) == -1 )
473 // this might be not necessary as mkstemp() on most systems should have
474 // already done it but it doesn't hurt neither...
477 //else: file already created
478 #else // !HAVE_MKSTEMP
482 path
+= _T("XXXXXX");
484 if ( !mktemp((char *)path
.mb_str()) )
488 #else // !HAVE_MKTEMP
489 // generate the unique file name ourselves
490 path
<< (unsigned int)getpid();
494 static const size_t numTries
= 1000;
495 for ( size_t n
= 0; n
< numTries
; n
++ )
497 // 3 hex digits is enough for numTries == 1000 < 4096
498 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
499 if ( !wxFile::Exists(pathTry
) )
508 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
512 // create the file - of course, there is a race condition here, this is
513 // why we always prefer using mkstemp()...
515 if ( !file
.Open(path
, wxFile::write_excl
, wxS_IRUSR
| wxS_IWUSR
) )
517 // FIXME: If !ok here should we loop and try again with another
518 // file name? That is the standard recourse if open(O_EXCL)
519 // fails, though of course it should be protected against
520 // possible infinite looping too.
522 wxLogError(_("Failed to open temporary file."));
527 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
529 #endif // Windows/!Windows
533 wxLogSysError(_("Failed to create a temporary file name"));
539 // ----------------------------------------------------------------------------
540 // directory operations
541 // ----------------------------------------------------------------------------
543 bool wxFileName::Mkdir( int perm
, bool full
)
545 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
548 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
552 wxFileName
filename(dir
);
553 wxArrayString dirs
= filename
.GetDirs();
554 dirs
.Add(filename
.GetName());
556 size_t count
= dirs
.GetCount();
560 for ( i
= 0; i
< count
; i
++ )
564 if (currPath
.Last() == wxT(':'))
566 // Can't create a root directory so continue to next dir
567 currPath
+= wxFILE_SEP_PATH
;
571 if (!DirExists(currPath
))
572 if (!wxMkdir(currPath
, perm
))
575 if ( (i
< (count
-1)) )
576 currPath
+= wxFILE_SEP_PATH
;
579 return (noErrors
== 0);
583 return ::wxMkdir( dir
, perm
);
586 bool wxFileName::Rmdir()
588 return wxFileName::Rmdir( GetFullPath() );
591 bool wxFileName::Rmdir( const wxString
&dir
)
593 return ::wxRmdir( dir
);
596 // ----------------------------------------------------------------------------
597 // path normalization
598 // ----------------------------------------------------------------------------
600 bool wxFileName::Normalize(wxPathNormalize flags
,
604 // the existing path components
605 wxArrayString dirs
= GetDirs();
607 // the path to prepend in front to make the path absolute
610 format
= GetFormat(format
);
612 // make the path absolute
613 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute() )
617 curDir
.AssignCwd(GetVolume());
621 curDir
.AssignDir(cwd
);
624 // the path may be not absolute because it doesn't have the volume name
625 // but in this case we shouldn't modify the directory components of it
626 // but just set the current volume
627 if ( !HasVolume() && curDir
.HasVolume() )
629 SetVolume(curDir
.GetVolume());
633 // yes, it was the case - we don't need curDir then
639 // handle ~ stuff under Unix only
640 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
642 if ( !dirs
.IsEmpty() )
644 wxString dir
= dirs
[0u];
645 if ( !dir
.empty() && dir
[0u] == _T('~') )
647 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
654 // transform relative path into abs one
657 wxArrayString dirsNew
= curDir
.GetDirs();
658 size_t count
= dirs
.GetCount();
659 for ( size_t n
= 0; n
< count
; n
++ )
661 dirsNew
.Add(dirs
[n
]);
667 // now deal with ".", ".." and the rest
669 size_t count
= dirs
.GetCount();
670 for ( size_t n
= 0; n
< count
; n
++ )
672 wxString dir
= dirs
[n
];
674 if ( flags
& wxPATH_NORM_DOTS
)
676 if ( dir
== wxT(".") )
682 if ( dir
== wxT("..") )
684 if ( m_dirs
.IsEmpty() )
686 wxLogError(_("The path '%s' contains too many \"..\"!"),
687 GetFullPath().c_str());
691 m_dirs
.Remove(m_dirs
.GetCount() - 1);
696 if ( flags
& wxPATH_NORM_ENV_VARS
)
698 dir
= wxExpandEnvVars(dir
);
701 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
709 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
711 // VZ: expand env vars here too?
717 #if defined(__WIN32__)
718 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
720 Assign(GetLongPath());
727 // ----------------------------------------------------------------------------
728 // filename kind tests
729 // ----------------------------------------------------------------------------
731 bool wxFileName::SameAs( const wxFileName
&filepath
, wxPathFormat format
)
733 wxFileName fn1
= *this,
736 // get cwd only once - small time saving
737 wxString cwd
= wxGetCwd();
738 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
739 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
741 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
744 // TODO: compare inodes for Unix, this works even when filenames are
745 // different but files are the same (symlinks) (VZ)
751 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
753 // only Unix filenames are truely case-sensitive
754 return GetFormat(format
) == wxPATH_UNIX
;
757 bool wxFileName::IsAbsolute( wxPathFormat format
)
759 // if we have no path, we can't be an abs filename
760 if ( m_dirs
.IsEmpty() )
765 format
= GetFormat(format
);
767 if ( format
== wxPATH_UNIX
)
769 const wxString
& str
= m_dirs
[0u];
772 // the path started with '/', it's an absolute one
776 // the path is absolute if it starts with a path separator or
777 // with "~" or "~user"
780 return IsPathSeparator(ch
, format
) || ch
== _T('~');
784 // must have the drive
785 if ( m_volume
.empty() )
791 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
795 return m_dirs
[0u].empty();
798 // TODO: what is the relative path format here?
802 return !m_dirs
[0u].empty();
808 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
812 if ( GetFormat(format
) != wxPATH_UNIX
)
814 // so far it is the same for all systems which have it
815 sepVol
= wxFILE_SEP_DSK
;
817 //else: leave empty, no volume separators under Unix
823 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
826 switch ( GetFormat(format
) )
829 // accept both as native APIs do but put the native one first as
830 // this is the one we use in GetFullPath()
831 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
835 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
839 seps
= wxFILE_SEP_PATH_UNIX
;
843 seps
= wxFILE_SEP_PATH_MAC
;
847 seps
= wxFILE_SEP_PATH_VMS
;
855 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
857 // wxString::Find() doesn't work as expected with NUL - it will always find
858 // it, so it is almost surely a bug if this function is called with NUL arg
859 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
861 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
864 bool wxFileName::IsWild( wxPathFormat format
)
866 // FIXME: this is probably false for Mac and this is surely wrong for most
867 // of Unix shells (think about "[...]")
869 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
872 // ----------------------------------------------------------------------------
873 // path components manipulation
874 // ----------------------------------------------------------------------------
876 void wxFileName::AppendDir( const wxString
&dir
)
881 void wxFileName::PrependDir( const wxString
&dir
)
883 m_dirs
.Insert( dir
, 0 );
886 void wxFileName::InsertDir( int before
, const wxString
&dir
)
888 m_dirs
.Insert( dir
, before
);
891 void wxFileName::RemoveDir( int pos
)
893 m_dirs
.Remove( (size_t)pos
);
896 // ----------------------------------------------------------------------------
898 // ----------------------------------------------------------------------------
900 void wxFileName::SetFullName(const wxString
& fullname
)
902 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
905 wxString
wxFileName::GetFullName() const
907 wxString fullname
= m_name
;
908 if ( !m_ext
.empty() )
910 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
916 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
918 format
= GetFormat( format
);
921 size_t count
= m_dirs
.GetCount();
922 for ( size_t i
= 0; i
< count
; i
++ )
925 if ( add_separator
|| (i
< count
) )
926 ret
+= wxFILE_SEP_PATH
;
932 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
934 format
= GetFormat(format
);
938 // first put the volume
939 if ( !m_volume
.empty() )
941 // special Windows UNC paths hack, part 2: undo what we did in
942 // SplitPath() and make an UNC path if we have a drive which is not a
943 // single letter (hopefully the network shares can't be one letter only
944 // although I didn't find any authoritative docs on this)
945 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
947 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
951 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
955 // then concatenate all the path components using the path separator
956 size_t dirCount
= m_dirs
.GetCount();
959 // under Mac, we must have a path separator in the beginning of the
960 // relative path - otherwise it would be parsed as an absolute one
961 if ( format
== wxPATH_MAC
&& m_volume
.empty() && !m_dirs
[0].empty() )
963 fullpath
+= wxFILE_SEP_PATH_MAC
;
966 wxChar chPathSep
= GetPathSeparators(format
)[0u];
967 if ( format
== wxPATH_VMS
)
972 for ( size_t i
= 0; i
< dirCount
; i
++ )
974 // under VMS, we shouldn't have a leading dot
975 if ( i
&& (format
!= wxPATH_VMS
|| !m_dirs
[i
- 1].empty()) )
976 fullpath
+= chPathSep
;
978 fullpath
+= m_dirs
[i
];
981 if ( format
== wxPATH_VMS
)
987 // separate the file name from the last directory, notice that we
988 // intentionally do it even if the name and extension are empty as
989 // this allows us to distinguish the directories from the file
990 // names (the directories have the trailing slash)
991 fullpath
+= chPathSep
;
995 // finally add the file name and extension
996 fullpath
+= GetFullName();
1001 // Return the short form of the path (returns identity on non-Windows platforms)
1002 wxString
wxFileName::GetShortPath() const
1004 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1005 wxString
path(GetFullPath());
1007 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1011 ok
= ::GetShortPathName
1014 pathOut
.GetWriteBuf(sz
),
1017 pathOut
.UngetWriteBuf();
1024 return GetFullPath();
1028 // Return the long form of the path (returns identity on non-Windows platforms)
1029 wxString
wxFileName::GetLongPath() const
1032 path
= GetFullPath();
1034 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1035 bool success
= FALSE
;
1037 // VZ: this code was disabled, why?
1038 #if 0 // wxUSE_DYNLIB_CLASS
1039 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1041 static bool s_triedToLoad
= FALSE
;
1043 if ( !s_triedToLoad
)
1045 s_triedToLoad
= TRUE
;
1046 wxDllType dllKernel
= wxDllLoader::LoadLibrary(_T("kernel32"));
1049 // may succeed or fail depending on the Windows version
1050 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1052 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameW"));
1054 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) wxDllLoader::GetSymbol(dllKernel
, _T("GetLongPathNameA"));
1057 wxDllLoader::UnloadLibrary(dllKernel
);
1059 if ( s_pfnGetLongPathName
)
1061 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1062 bool ok
= dwSize
> 0;
1066 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1070 ok
= (*s_pfnGetLongPathName
)
1073 pathOut
.GetWriteBuf(sz
),
1076 pathOut
.UngetWriteBuf();
1086 #endif // wxUSE_DYNLIB_CLASS
1090 // The OS didn't support GetLongPathName, or some other error.
1091 // We need to call FindFirstFile on each component in turn.
1093 WIN32_FIND_DATA findFileData
;
1095 pathOut
= wxEmptyString
;
1097 wxArrayString dirs
= GetDirs();
1098 dirs
.Add(GetFullName());
1102 size_t count
= dirs
.GetCount();
1103 for ( size_t i
= 0; i
< count
; i
++ )
1105 // We're using pathOut to collect the long-name path, but using a
1106 // temporary for appending the last path component which may be
1108 tmpPath
= pathOut
+ dirs
[i
];
1110 if ( tmpPath
.empty() )
1113 if ( tmpPath
.Last() == wxT(':') )
1115 // Can't pass a drive and root dir to FindFirstFile,
1116 // so continue to next dir
1117 tmpPath
+= wxFILE_SEP_PATH
;
1122 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1123 if (hFind
== INVALID_HANDLE_VALUE
)
1125 // Error: return immediately with the original path
1129 pathOut
+= findFileData
.cFileName
;
1130 if ( (i
< (count
-1)) )
1131 pathOut
+= wxFILE_SEP_PATH
;
1138 #endif // Win32/!Win32
1143 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1145 if (format
== wxPATH_NATIVE
)
1147 #if defined(__WXMSW__) || defined(__WXPM__)
1148 format
= wxPATH_DOS
;
1149 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1150 format
= wxPATH_MAC
;
1151 #elif defined(__VMS)
1152 format
= wxPATH_VMS
;
1154 format
= wxPATH_UNIX
;
1160 // ----------------------------------------------------------------------------
1161 // path splitting function
1162 // ----------------------------------------------------------------------------
1165 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1166 wxString
*pstrVolume
,
1170 wxPathFormat format
)
1172 format
= GetFormat(format
);
1174 wxString fullpath
= fullpathWithVolume
;
1176 // under VMS the end of the path is ']', not the path separator used to
1177 // separate the components
1178 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1179 : GetPathSeparators(format
);
1181 // special Windows UNC paths hack: transform \\share\path into share:path
1182 if ( format
== wxPATH_DOS
)
1184 if ( fullpath
.length() >= 4 &&
1185 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1186 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1188 fullpath
.erase(0, 2);
1190 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1191 if ( posFirstSlash
!= wxString::npos
)
1193 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1195 // UNC paths are always absolute, right? (FIXME)
1196 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1201 // do we have the volume name in the beginning?
1202 wxString sepVol
= GetVolumeSeparator(format
);
1203 if ( !sepVol
.empty() )
1205 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1206 if ( posFirstColon
!= wxString::npos
)
1210 *pstrVolume
= fullpath
.Left(posFirstColon
);
1213 // remove the volume name and the separator from the full path
1214 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1218 // find the positions of the last dot and last path separator in the path
1219 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1220 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1222 if ( (posLastDot
!= wxString::npos
) &&
1223 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1225 if ( (posLastDot
== 0) ||
1226 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1228 // under Unix and VMS, dot may be (and commonly is) the first
1229 // character of the filename, don't treat the entire filename as
1230 // extension in this case
1231 posLastDot
= wxString::npos
;
1235 // if we do have a dot and a slash, check that the dot is in the name part
1236 if ( (posLastDot
!= wxString::npos
) &&
1237 (posLastSlash
!= wxString::npos
) &&
1238 (posLastDot
< posLastSlash
) )
1240 // the dot is part of the path, not the start of the extension
1241 posLastDot
= wxString::npos
;
1244 // now fill in the variables provided by user
1247 if ( posLastSlash
== wxString::npos
)
1254 // take everything up to the path separator but take care to make
1255 // tha path equal to something like '/', not empty, for the files
1256 // immediately under root directory
1257 size_t len
= posLastSlash
;
1261 *pstrPath
= fullpath
.Left(len
);
1263 // special VMS hack: remove the initial bracket
1264 if ( format
== wxPATH_VMS
)
1266 if ( (*pstrPath
)[0u] == _T('[') )
1267 pstrPath
->erase(0, 1);
1274 // take all characters starting from the one after the last slash and
1275 // up to, but excluding, the last dot
1276 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1278 if ( posLastDot
== wxString::npos
)
1280 // take all until the end
1281 count
= wxString::npos
;
1283 else if ( posLastSlash
== wxString::npos
)
1287 else // have both dot and slash
1289 count
= posLastDot
- posLastSlash
- 1;
1292 *pstrName
= fullpath
.Mid(nStart
, count
);
1297 if ( posLastDot
== wxString::npos
)
1304 // take everything after the dot
1305 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1311 void wxFileName::SplitPath(const wxString
& fullpath
,
1315 wxPathFormat format
)
1318 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1320 if ( path
&& !volume
.empty() )
1322 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1326 // ----------------------------------------------------------------------------
1328 // ----------------------------------------------------------------------------
1330 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1331 const wxDateTime
*dtAccess
,
1332 const wxDateTime
*dtMod
)
1334 #if defined(__UNIX_LIKE__)
1335 if ( !dtAccess
&& !dtMod
)
1337 // can't modify the creation time anyhow, don't try
1341 // if dtAccess or dtMod is not specified, use the other one (which must be
1342 // non NULL because of the test above) for both times
1344 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1345 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1346 if ( utime(GetFullPath(), &utm
) == 0 )
1350 #elif defined(__WIN32__)
1351 wxFileHandle
fh(GetFullPath());
1354 FILETIME ftAccess
, ftCreate
, ftWrite
;
1357 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1359 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1361 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1363 if ( ::SetFileTime(fh
,
1364 dtCreate
? &ftCreate
: NULL
,
1365 dtAccess
? &ftAccess
: NULL
,
1366 dtMod
? &ftWrite
: NULL
) )
1371 #else // other platform
1374 wxLogSysError(_("Failed to modify file times for '%s'"),
1375 GetFullPath().c_str());
1380 bool wxFileName::Touch()
1382 #if defined(__UNIX_LIKE__)
1383 // under Unix touching file is simple: just pass NULL to utime()
1384 if ( utime(GetFullPath(), NULL
) == 0 )
1389 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1392 #else // other platform
1393 wxDateTime dtNow
= wxDateTime::Now();
1395 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1399 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1401 wxDateTime
*dtChange
) const
1403 #if defined(__UNIX_LIKE__)
1405 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1408 dtAccess
->Set(stBuf
.st_atime
);
1410 dtMod
->Set(stBuf
.st_mtime
);
1412 dtChange
->Set(stBuf
.st_ctime
);
1416 #elif defined(__WXMAC__)
1418 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1421 dtAccess
->Set(stBuf
.st_atime
);
1423 dtMod
->Set(stBuf
.st_mtime
);
1425 dtChange
->Set(stBuf
.st_ctime
);
1429 #elif defined(__WIN32__)
1430 wxFileHandle
fh(GetFullPath());
1433 FILETIME ftAccess
, ftCreate
, ftWrite
;
1435 if ( ::GetFileTime(fh
,
1436 dtMod
? &ftCreate
: NULL
,
1437 dtAccess
? &ftAccess
: NULL
,
1438 dtChange
? &ftWrite
: NULL
) )
1441 ConvertFileTimeToWx(dtMod
, ftCreate
);
1443 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1445 ConvertFileTimeToWx(dtChange
, ftWrite
);
1450 #else // other platform
1453 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1454 GetFullPath().c_str());