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 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
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"
80 #include "wx/filename.h"
81 #include "wx/tokenzr.h"
82 #include "wx/config.h" // for wxExpandEnvVars
85 //#include "wx/dynlib.h" // see GetLongPath below, code disabled.
87 // 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>
113 #include <sys/utime.h>
114 #include <sys/stat.h>
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 // small helper class which opens and closes the file - we use it just to get
128 // a file handle for the given file name to pass it to some Win32 API function
129 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
134 wxFileHandle(const wxString
& filename
)
136 m_hFile
= ::CreateFile
139 GENERIC_READ
, // access mask
141 NULL
, // no secutity attr
142 OPEN_EXISTING
, // creation disposition
144 NULL
// no template file
147 if ( m_hFile
== INVALID_HANDLE_VALUE
)
149 wxLogSysError(_("Failed to open '%s' for reading"),
156 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
158 if ( !::CloseHandle(m_hFile
) )
160 wxLogSysError(_("Failed to close file handle"));
165 // return TRUE only if the file could be opened successfully
166 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
169 operator HANDLE() const { return m_hFile
; }
177 // ----------------------------------------------------------------------------
179 // ----------------------------------------------------------------------------
181 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
183 // convert between wxDateTime and FILETIME which is a 64-bit value representing
184 // the number of 100-nanosecond intervals since January 1, 1601.
186 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
187 // FILETIME reference point (January 1, 1601)
188 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
190 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
192 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
194 // convert 100ns to ms
197 // move it to our Epoch
198 ll
-= FILETIME_EPOCH_OFFSET
;
200 *dt
= wxDateTime(ll
);
203 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
205 // do the reverse of ConvertFileTimeToWx()
206 wxLongLong ll
= dt
.GetValue();
208 ll
+= FILETIME_EPOCH_OFFSET
;
210 ft
->dwHighDateTime
= ll
.GetHi();
211 ft
->dwLowDateTime
= ll
.GetLo();
216 // ============================================================================
218 // ============================================================================
220 // ----------------------------------------------------------------------------
221 // wxFileName construction
222 // ----------------------------------------------------------------------------
224 void wxFileName::Assign( const wxFileName
&filepath
)
226 m_volume
= filepath
.GetVolume();
227 m_dirs
= filepath
.GetDirs();
228 m_name
= filepath
.GetName();
229 m_ext
= filepath
.GetExt();
230 m_relative
= filepath
.IsRelative();
233 void wxFileName::Assign(const wxString
& volume
,
234 const wxString
& path
,
235 const wxString
& name
,
237 wxPathFormat format
)
239 SetPath( path
, format
);
246 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
248 wxPathFormat my_format
= GetFormat( format
);
249 wxString my_path
= path
;
253 if (!my_path
.empty())
255 // 1) Determine if the path is relative or absolute.
260 m_relative
= ( my_path
[0u] == wxT(':') );
261 // We then remove a leading ":". The reason is in our
262 // storage form for relative paths:
263 // ":dir:file.txt" actually means "./dir/file.txt" in
264 // DOS notation and should get stored as
265 // (relative) (dir) (file.txt)
266 // "::dir:file.txt" actually means "../dir/file.txt"
267 // stored as (relative) (..) (dir) (file.txt)
268 // This is important only for the Mac as an empty dir
269 // actually means <UP>, whereas under DOS, double
270 // slashes can be ignored: "\\\\" is the same as "\\".
272 my_path
.Remove( 0, 1 );
275 // TODO: what is the relative path format here?
279 m_relative
= ( my_path
[0u] != wxT('/') );
282 m_relative
= ( (my_path
[0u] != wxT('/')) && (my_path
[0u] != wxT('\\')) );
285 wxFAIL_MSG( wxT("error") );
289 // 2) Break up the path into its members. If the original path
290 // was just "/" or "\\", m_dirs will be empty. We know from
291 // the m_relative field, if this means "nothing" or "root dir".
293 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
295 while ( tn
.HasMoreTokens() )
297 wxString token
= tn
.GetNextToken();
299 // Remove empty token under DOS and Unix, interpret them
303 if (my_format
== wxPATH_MAC
)
304 m_dirs
.Add( wxT("..") );
319 void wxFileName::Assign(const wxString
& fullpath
,
322 wxString volume
, path
, name
, ext
;
323 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
325 Assign(volume
, path
, name
, ext
, format
);
328 void wxFileName::Assign(const wxString
& fullpathOrig
,
329 const wxString
& fullname
,
332 // always recognize fullpath as directory, even if it doesn't end with a
334 wxString fullpath
= fullpathOrig
;
335 if ( !wxEndsWithPathSeparator(fullpath
) )
337 fullpath
+= GetPathSeparators(format
)[0u];
340 wxString volume
, path
, name
, ext
;
342 // do some consistency checks in debug mode: the name should be really just
343 // the filename and the path should be really just a path
345 wxString pathDummy
, nameDummy
, extDummy
;
347 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
349 wxASSERT_MSG( pathDummy
.empty(),
350 _T("the file name shouldn't contain the path") );
352 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
354 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
355 _T("the path shouldn't contain file name nor extension") );
357 #else // !__WXDEBUG__
358 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
359 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
360 #endif // __WXDEBUG__/!__WXDEBUG__
362 Assign(volume
, path
, name
, ext
, format
);
365 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
367 Assign(dir
, _T(""), format
);
370 void wxFileName::Clear()
376 m_ext
= wxEmptyString
;
380 wxFileName
wxFileName::FileName(const wxString
& file
)
382 return wxFileName(file
);
386 wxFileName
wxFileName::DirName(const wxString
& dir
)
393 // ----------------------------------------------------------------------------
395 // ----------------------------------------------------------------------------
397 bool wxFileName::FileExists()
399 return wxFileName::FileExists( GetFullPath() );
402 bool wxFileName::FileExists( const wxString
&file
)
404 return ::wxFileExists( file
);
407 bool wxFileName::DirExists()
409 return wxFileName::DirExists( GetFullPath() );
412 bool wxFileName::DirExists( const wxString
&dir
)
414 return ::wxDirExists( dir
);
417 // ----------------------------------------------------------------------------
418 // CWD and HOME stuff
419 // ----------------------------------------------------------------------------
421 void wxFileName::AssignCwd(const wxString
& volume
)
423 AssignDir(wxFileName::GetCwd(volume
));
427 wxString
wxFileName::GetCwd(const wxString
& volume
)
429 // if we have the volume, we must get the current directory on this drive
430 // and to do this we have to chdir to this volume - at least under Windows,
431 // I don't know how to get the current drive on another volume elsewhere
434 if ( !volume
.empty() )
437 SetCwd(volume
+ GetVolumeSeparator());
440 wxString cwd
= ::wxGetCwd();
442 if ( !volume
.empty() )
450 bool wxFileName::SetCwd()
452 return wxFileName::SetCwd( GetFullPath() );
455 bool wxFileName::SetCwd( const wxString
&cwd
)
457 return ::wxSetWorkingDirectory( cwd
);
460 void wxFileName::AssignHomeDir()
462 AssignDir(wxFileName::GetHomeDir());
465 wxString
wxFileName::GetHomeDir()
467 return ::wxGetHomeDir();
470 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
472 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
473 if ( tempname
.empty() )
475 // error, failed to get temp file name
486 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
488 wxString path
, dir
, name
;
490 // use the directory specified by the prefix
491 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
493 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
498 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
500 wxLogLastError(_T("GetTempPath"));
505 // GetTempFileName() fails if we pass it an empty string
510 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
512 wxLogLastError(_T("GetTempFileName"));
517 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
523 #elif defined(__WXPM__)
524 // for now just create a file
526 // future enhancements can be to set some extended attributes for file
527 // systems OS/2 supports that have them (HPFS, FAT32) and security
529 static const wxChar
*szMktempSuffix
= wxT("XXX");
530 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
532 // Temporarily remove - MN
534 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
537 #else // !Windows, !OS/2
540 #if defined( __WXMAC__ ) && !defined(__DARWIN__)
541 dir
= wxMacFindFolder( (short) kOnSystemDisk
, pTemporaryFolder
, kCreateFolder
) ;
543 dir
= wxGetenv(_T("TMP"));
546 dir
= wxGetenv(_T("TEMP"));
563 if ( !wxEndsWithPathSeparator(dir
) &&
564 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
566 path
+= wxFILE_SEP_PATH
;
571 #if defined(HAVE_MKSTEMP)
572 // scratch space for mkstemp()
573 path
+= _T("XXXXXX");
575 // can use the cast here because the length doesn't change and the string
577 int fdTemp
= mkstemp((char *)path
.mb_str());
580 // this might be not necessary as mkstemp() on most systems should have
581 // already done it but it doesn't hurt neither...
584 else // mkstemp() succeeded
586 // avoid leaking the fd
589 fileTemp
->Attach(fdTemp
);
596 #else // !HAVE_MKSTEMP
600 path
+= _T("XXXXXX");
602 if ( !mktemp((char *)path
.mb_str()) )
606 #else // !HAVE_MKTEMP (includes __DOS__)
607 // generate the unique file name ourselves
609 path
<< (unsigned int)getpid();
614 static const size_t numTries
= 1000;
615 for ( size_t n
= 0; n
< numTries
; n
++ )
617 // 3 hex digits is enough for numTries == 1000 < 4096
618 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
619 if ( !wxFile::Exists(pathTry
) )
628 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
633 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
635 #endif // Windows/!Windows
639 wxLogSysError(_("Failed to create a temporary file name"));
641 else if ( fileTemp
&& !fileTemp
->IsOpened() )
643 // open the file - of course, there is a race condition here, this is
644 // why we always prefer using mkstemp()...
646 // NB: GetTempFileName() under Windows creates the file, so using
647 // write_excl there would fail
648 if ( !fileTemp
->Open(path
,
649 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
654 wxS_IRUSR
| wxS_IWUSR
) )
656 // FIXME: If !ok here should we loop and try again with another
657 // file name? That is the standard recourse if open(O_EXCL)
658 // fails, though of course it should be protected against
659 // possible infinite looping too.
661 wxLogError(_("Failed to open temporary file."));
670 // ----------------------------------------------------------------------------
671 // directory operations
672 // ----------------------------------------------------------------------------
674 bool wxFileName::Mkdir( int perm
, bool full
)
676 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
679 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
683 wxFileName
filename(dir
);
684 wxArrayString dirs
= filename
.GetDirs();
685 dirs
.Add(filename
.GetName());
687 size_t count
= dirs
.GetCount();
691 for ( i
= 0; i
< count
; i
++ )
695 if (currPath
.Last() == wxT(':'))
697 // Can't create a root directory so continue to next dir
698 currPath
+= wxFILE_SEP_PATH
;
702 if (!DirExists(currPath
))
703 if (!wxMkdir(currPath
, perm
))
706 if ( (i
< (count
-1)) )
707 currPath
+= wxFILE_SEP_PATH
;
710 return (noErrors
== 0);
714 return ::wxMkdir( dir
, perm
);
717 bool wxFileName::Rmdir()
719 return wxFileName::Rmdir( GetFullPath() );
722 bool wxFileName::Rmdir( const wxString
&dir
)
724 return ::wxRmdir( dir
);
727 // ----------------------------------------------------------------------------
728 // path normalization
729 // ----------------------------------------------------------------------------
731 bool wxFileName::Normalize(wxPathNormalize flags
,
735 // the existing path components
736 wxArrayString dirs
= GetDirs();
738 // the path to prepend in front to make the path absolute
741 format
= GetFormat(format
);
743 // make the path absolute
744 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
748 curDir
.AssignCwd(GetVolume());
752 curDir
.AssignDir(cwd
);
756 // the path may be not absolute because it doesn't have the volume name
757 // but in this case we shouldn't modify the directory components of it
758 // but just set the current volume
759 if ( !HasVolume() && curDir
.HasVolume() )
761 SetVolume(curDir
.GetVolume());
765 // yes, it was the case - we don't need curDir then
773 // handle ~ stuff under Unix only
774 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
776 if ( !dirs
.IsEmpty() )
778 wxString dir
= dirs
[0u];
779 if ( !dir
.empty() && dir
[0u] == _T('~') )
781 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
788 // transform relative path into abs one
791 wxArrayString dirsNew
= curDir
.GetDirs();
792 size_t count
= dirs
.GetCount();
793 for ( size_t n
= 0; n
< count
; n
++ )
795 dirsNew
.Add(dirs
[n
]);
801 // now deal with ".", ".." and the rest
803 size_t count
= dirs
.GetCount();
804 for ( size_t n
= 0; n
< count
; n
++ )
806 wxString dir
= dirs
[n
];
808 if ( flags
& wxPATH_NORM_DOTS
)
810 if ( dir
== wxT(".") )
816 if ( dir
== wxT("..") )
818 if ( m_dirs
.IsEmpty() )
820 wxLogError(_("The path '%s' contains too many \"..\"!"),
821 GetFullPath().c_str());
825 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
830 if ( flags
& wxPATH_NORM_ENV_VARS
)
832 dir
= wxExpandEnvVars(dir
);
835 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
843 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
845 // VZ: expand env vars here too?
851 #if defined(__WIN32__)
852 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
854 Assign(GetLongPath());
861 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
863 wxFileName
fnBase(pathBase
, format
);
865 // get cwd only once - small time saving
866 wxString cwd
= wxGetCwd();
867 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
868 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
870 bool withCase
= IsCaseSensitive(format
);
872 // we can't do anything if the files live on different volumes
873 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
879 // same drive, so we don't need our volume
882 // remove common directories starting at the top
883 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
884 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
887 fnBase
.m_dirs
.RemoveAt(0);
890 // add as many ".." as needed
891 size_t count
= fnBase
.m_dirs
.GetCount();
892 for ( size_t i
= 0; i
< count
; i
++ )
894 m_dirs
.Insert(wxT(".."), 0u);
903 // ----------------------------------------------------------------------------
904 // filename kind tests
905 // ----------------------------------------------------------------------------
907 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
909 wxFileName fn1
= *this,
912 // get cwd only once - small time saving
913 wxString cwd
= wxGetCwd();
914 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
915 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
917 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
920 // TODO: compare inodes for Unix, this works even when filenames are
921 // different but files are the same (symlinks) (VZ)
927 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
929 // only Unix filenames are truely case-sensitive
930 return GetFormat(format
) == wxPATH_UNIX
;
934 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
938 if ( (GetFormat(format
) == wxPATH_DOS
) ||
939 (GetFormat(format
) == wxPATH_VMS
) )
941 sepVol
= wxFILE_SEP_DSK
;
949 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
952 switch ( GetFormat(format
) )
955 // accept both as native APIs do but put the native one first as
956 // this is the one we use in GetFullPath()
957 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
961 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
965 seps
= wxFILE_SEP_PATH_UNIX
;
969 seps
= wxFILE_SEP_PATH_MAC
;
973 seps
= wxFILE_SEP_PATH_VMS
;
981 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
983 // wxString::Find() doesn't work as expected with NUL - it will always find
984 // it, so it is almost surely a bug if this function is called with NUL arg
985 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
987 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
990 bool wxFileName::IsWild( wxPathFormat format
)
992 // FIXME: this is probably false for Mac and this is surely wrong for most
993 // of Unix shells (think about "[...]")
995 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
998 // ----------------------------------------------------------------------------
999 // path components manipulation
1000 // ----------------------------------------------------------------------------
1002 void wxFileName::AppendDir( const wxString
&dir
)
1007 void wxFileName::PrependDir( const wxString
&dir
)
1009 m_dirs
.Insert( dir
, 0 );
1012 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1014 m_dirs
.Insert( dir
, before
);
1017 void wxFileName::RemoveDir( int pos
)
1019 m_dirs
.Remove( (size_t)pos
);
1022 // ----------------------------------------------------------------------------
1024 // ----------------------------------------------------------------------------
1026 void wxFileName::SetFullName(const wxString
& fullname
)
1028 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1031 wxString
wxFileName::GetFullName() const
1033 wxString fullname
= m_name
;
1034 if ( !m_ext
.empty() )
1036 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1042 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1044 format
= GetFormat( format
);
1048 // the leading character
1049 if ( format
== wxPATH_MAC
&& m_relative
)
1051 fullpath
+= wxFILE_SEP_PATH_MAC
;
1053 else if ( format
== wxPATH_DOS
)
1056 fullpath
+= wxFILE_SEP_PATH_DOS
;
1058 else if ( format
== wxPATH_UNIX
)
1061 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1064 // then concatenate all the path components using the path separator
1065 size_t dirCount
= m_dirs
.GetCount();
1068 if ( format
== wxPATH_VMS
)
1070 fullpath
+= wxT('[');
1074 for ( size_t i
= 0; i
< dirCount
; i
++ )
1076 // TODO: What to do with ".." under VMS
1082 if (m_dirs
[i
] == wxT("."))
1084 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1085 fullpath
+= m_dirs
[i
];
1086 fullpath
+= wxT(':');
1091 fullpath
+= m_dirs
[i
];
1092 fullpath
+= wxT('\\');
1097 fullpath
+= m_dirs
[i
];
1098 fullpath
+= wxT('/');
1103 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1104 fullpath
+= m_dirs
[i
];
1105 if (i
== dirCount
-1)
1106 fullpath
+= wxT(']');
1108 fullpath
+= wxT('.');
1113 wxFAIL_MSG( wxT("error") );
1124 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1126 format
= GetFormat(format
);
1130 // first put the volume
1131 if ( !m_volume
.empty() )
1134 // Special Windows UNC paths hack, part 2: undo what we did in
1135 // SplitPath() and make an UNC path if we have a drive which is not a
1136 // single letter (hopefully the network shares can't be one letter only
1137 // although I didn't find any authoritative docs on this)
1138 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1140 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1142 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1144 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1150 // the leading character
1151 if ( format
== wxPATH_MAC
&& m_relative
)
1153 fullpath
+= wxFILE_SEP_PATH_MAC
;
1155 else if ( format
== wxPATH_DOS
)
1158 fullpath
+= wxFILE_SEP_PATH_DOS
;
1160 else if ( format
== wxPATH_UNIX
)
1163 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1166 // then concatenate all the path components using the path separator
1167 size_t dirCount
= m_dirs
.GetCount();
1170 if ( format
== wxPATH_VMS
)
1172 fullpath
+= wxT('[');
1176 for ( size_t i
= 0; i
< dirCount
; i
++ )
1178 // TODO: What to do with ".." under VMS
1184 if (m_dirs
[i
] == wxT("."))
1186 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1187 fullpath
+= m_dirs
[i
];
1188 fullpath
+= wxT(':');
1193 fullpath
+= m_dirs
[i
];
1194 fullpath
+= wxT('\\');
1199 fullpath
+= m_dirs
[i
];
1200 fullpath
+= wxT('/');
1205 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1206 fullpath
+= m_dirs
[i
];
1207 if (i
== dirCount
-1)
1208 fullpath
+= wxT(']');
1210 fullpath
+= wxT('.');
1215 wxFAIL_MSG( wxT("error") );
1221 // finally add the file name and extension
1222 fullpath
+= GetFullName();
1227 // Return the short form of the path (returns identity on non-Windows platforms)
1228 wxString
wxFileName::GetShortPath() const
1230 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1231 wxString
path(GetFullPath());
1233 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1237 ok
= ::GetShortPathName
1240 pathOut
.GetWriteBuf(sz
),
1243 pathOut
.UngetWriteBuf();
1250 return GetFullPath();
1254 // Return the long form of the path (returns identity on non-Windows platforms)
1255 wxString
wxFileName::GetLongPath() const
1258 path
= GetFullPath();
1260 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1261 bool success
= FALSE
;
1263 // VZ: this code was disabled, why?
1264 #if 0 // wxUSE_DYNAMIC_LOADER
1265 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1267 static bool s_triedToLoad
= FALSE
;
1269 if ( !s_triedToLoad
)
1271 s_triedToLoad
= TRUE
;
1272 wxDynamicLibrary
dllKernel(_T("kernel32"));
1273 if ( dllKernel
.IsLoaded() )
1275 // may succeed or fail depending on the Windows version
1276 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1278 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1280 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1283 if ( s_pfnGetLongPathName
)
1285 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1286 bool ok
= dwSize
> 0;
1290 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1294 ok
= (*s_pfnGetLongPathName
)
1297 pathOut
.GetWriteBuf(sz
),
1300 pathOut
.UngetWriteBuf();
1310 #endif // wxUSE_DYNAMIC_LOADER
1314 // The OS didn't support GetLongPathName, or some other error.
1315 // We need to call FindFirstFile on each component in turn.
1317 WIN32_FIND_DATA findFileData
;
1319 pathOut
= wxEmptyString
;
1321 wxArrayString dirs
= GetDirs();
1322 dirs
.Add(GetFullName());
1326 size_t count
= dirs
.GetCount();
1327 for ( size_t i
= 0; i
< count
; i
++ )
1329 // We're using pathOut to collect the long-name path, but using a
1330 // temporary for appending the last path component which may be
1332 tmpPath
= pathOut
+ dirs
[i
];
1334 if ( tmpPath
.empty() )
1337 if ( tmpPath
.Last() == wxT(':') )
1339 // Can't pass a drive and root dir to FindFirstFile,
1340 // so continue to next dir
1341 tmpPath
+= wxFILE_SEP_PATH
;
1346 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1347 if (hFind
== INVALID_HANDLE_VALUE
)
1349 // Error: return immediately with the original path
1353 pathOut
+= findFileData
.cFileName
;
1354 if ( (i
< (count
-1)) )
1355 pathOut
+= wxFILE_SEP_PATH
;
1362 #endif // Win32/!Win32
1367 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1369 if (format
== wxPATH_NATIVE
)
1371 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1372 format
= wxPATH_DOS
;
1373 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1374 format
= wxPATH_MAC
;
1375 #elif defined(__VMS)
1376 format
= wxPATH_VMS
;
1378 format
= wxPATH_UNIX
;
1384 // ----------------------------------------------------------------------------
1385 // path splitting function
1386 // ----------------------------------------------------------------------------
1389 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1390 wxString
*pstrVolume
,
1394 wxPathFormat format
)
1396 format
= GetFormat(format
);
1398 wxString fullpath
= fullpathWithVolume
;
1400 // under VMS the end of the path is ']', not the path separator used to
1401 // separate the components
1402 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1403 : GetPathSeparators(format
);
1405 // special Windows UNC paths hack: transform \\share\path into share:path
1406 if ( format
== wxPATH_DOS
)
1408 if ( fullpath
.length() >= 4 &&
1409 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1410 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1412 fullpath
.erase(0, 2);
1414 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1415 if ( posFirstSlash
!= wxString::npos
)
1417 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1419 // UNC paths are always absolute, right? (FIXME)
1420 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1425 // We separate the volume here
1426 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1428 wxString sepVol
= GetVolumeSeparator(format
);
1430 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1431 if ( posFirstColon
!= wxString::npos
)
1435 *pstrVolume
= fullpath
.Left(posFirstColon
);
1438 // remove the volume name and the separator from the full path
1439 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1443 // find the positions of the last dot and last path separator in the path
1444 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1445 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1447 if ( (posLastDot
!= wxString::npos
) &&
1448 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1450 if ( (posLastDot
== 0) ||
1451 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1453 // under Unix and VMS, dot may be (and commonly is) the first
1454 // character of the filename, don't treat the entire filename as
1455 // extension in this case
1456 posLastDot
= wxString::npos
;
1460 // if we do have a dot and a slash, check that the dot is in the name part
1461 if ( (posLastDot
!= wxString::npos
) &&
1462 (posLastSlash
!= wxString::npos
) &&
1463 (posLastDot
< posLastSlash
) )
1465 // the dot is part of the path, not the start of the extension
1466 posLastDot
= wxString::npos
;
1469 // now fill in the variables provided by user
1472 if ( posLastSlash
== wxString::npos
)
1479 // take everything up to the path separator but take care to make
1480 // the path equal to something like '/', not empty, for the files
1481 // immediately under root directory
1482 size_t len
= posLastSlash
;
1486 *pstrPath
= fullpath
.Left(len
);
1488 // special VMS hack: remove the initial bracket
1489 if ( format
== wxPATH_VMS
)
1491 if ( (*pstrPath
)[0u] == _T('[') )
1492 pstrPath
->erase(0, 1);
1499 // take all characters starting from the one after the last slash and
1500 // up to, but excluding, the last dot
1501 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1503 if ( posLastDot
== wxString::npos
)
1505 // take all until the end
1506 count
= wxString::npos
;
1508 else if ( posLastSlash
== wxString::npos
)
1512 else // have both dot and slash
1514 count
= posLastDot
- posLastSlash
- 1;
1517 *pstrName
= fullpath
.Mid(nStart
, count
);
1522 if ( posLastDot
== wxString::npos
)
1529 // take everything after the dot
1530 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1536 void wxFileName::SplitPath(const wxString
& fullpath
,
1540 wxPathFormat format
)
1543 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1545 if ( path
&& !volume
.empty() )
1547 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1551 // ----------------------------------------------------------------------------
1553 // ----------------------------------------------------------------------------
1555 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1556 const wxDateTime
*dtAccess
,
1557 const wxDateTime
*dtMod
)
1559 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1560 if ( !dtAccess
&& !dtMod
)
1562 // can't modify the creation time anyhow, don't try
1566 // if dtAccess or dtMod is not specified, use the other one (which must be
1567 // non NULL because of the test above) for both times
1569 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1570 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1571 if ( utime(GetFullPath(), &utm
) == 0 )
1575 #elif defined(__WIN32__)
1576 wxFileHandle
fh(GetFullPath());
1579 FILETIME ftAccess
, ftCreate
, ftWrite
;
1582 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1584 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1586 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1588 if ( ::SetFileTime(fh
,
1589 dtCreate
? &ftCreate
: NULL
,
1590 dtAccess
? &ftAccess
: NULL
,
1591 dtMod
? &ftWrite
: NULL
) )
1596 #else // other platform
1599 wxLogSysError(_("Failed to modify file times for '%s'"),
1600 GetFullPath().c_str());
1605 bool wxFileName::Touch()
1607 #if defined(__UNIX_LIKE__)
1608 // under Unix touching file is simple: just pass NULL to utime()
1609 if ( utime(GetFullPath(), NULL
) == 0 )
1614 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1617 #else // other platform
1618 wxDateTime dtNow
= wxDateTime::Now();
1620 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1624 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1626 wxDateTime
*dtChange
) const
1628 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1630 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1633 dtAccess
->Set(stBuf
.st_atime
);
1635 dtMod
->Set(stBuf
.st_mtime
);
1637 dtChange
->Set(stBuf
.st_ctime
);
1641 #elif defined(__WIN32__)
1642 wxFileHandle
fh(GetFullPath());
1645 FILETIME ftAccess
, ftCreate
, ftWrite
;
1647 if ( ::GetFileTime(fh
,
1648 dtMod
? &ftCreate
: NULL
,
1649 dtAccess
? &ftAccess
: NULL
,
1650 dtChange
? &ftWrite
: NULL
) )
1653 ConvertFileTimeToWx(dtMod
, ftCreate
);
1655 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1657 ConvertFileTimeToWx(dtChange
, ftWrite
);
1662 #else // other platform
1665 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1666 GetFullPath().c_str());