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 #if defined(__WXMAC__)
94 #include "wx/mac/private.h" // includes mac headers
97 // utime() is POSIX so should normally be available on all Unices
99 #include <sys/types.h>
101 #include <sys/stat.h>
117 #include <sys/utime.h>
118 #include <sys/stat.h>
127 // ----------------------------------------------------------------------------
129 // ----------------------------------------------------------------------------
131 // small helper class which opens and closes the file - we use it just to get
132 // a file handle for the given file name to pass it to some Win32 API function
133 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
144 wxFileHandle(const wxString
& filename
, OpenMode mode
)
146 m_hFile
= ::CreateFile
149 mode
== Read
? GENERIC_READ
// access mask
152 NULL
, // no secutity attr
153 OPEN_EXISTING
, // creation disposition
155 NULL
// no template file
158 if ( m_hFile
== INVALID_HANDLE_VALUE
)
160 wxLogSysError(_("Failed to open '%s' for %s"),
162 mode
== Read
? _("reading") : _("writing"));
168 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
170 if ( !::CloseHandle(m_hFile
) )
172 wxLogSysError(_("Failed to close file handle"));
177 // return TRUE only if the file could be opened successfully
178 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
181 operator HANDLE() const { return m_hFile
; }
189 // ----------------------------------------------------------------------------
191 // ----------------------------------------------------------------------------
193 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
195 // convert between wxDateTime and FILETIME which is a 64-bit value representing
196 // the number of 100-nanosecond intervals since January 1, 1601.
198 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
201 if ( !::FileTimeToLocalFileTime(&ft
, &ftLocal
) )
203 wxLogLastError(_T("FileTimeToLocalFileTime"));
207 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
209 wxLogLastError(_T("FileTimeToSystemTime"));
212 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
213 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
216 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
219 st
.wDay
= dt
.GetDay();
220 st
.wMonth
= dt
.GetMonth() + 1;
221 st
.wYear
= dt
.GetYear();
222 st
.wHour
= dt
.GetHour();
223 st
.wMinute
= dt
.GetMinute();
224 st
.wSecond
= dt
.GetSecond();
225 st
.wMilliseconds
= dt
.GetMillisecond();
228 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
230 wxLogLastError(_T("SystemTimeToFileTime"));
233 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
235 wxLogLastError(_T("LocalFileTimeToFileTime"));
241 // ============================================================================
243 // ============================================================================
245 // ----------------------------------------------------------------------------
246 // wxFileName construction
247 // ----------------------------------------------------------------------------
249 void wxFileName::Assign( const wxFileName
&filepath
)
251 m_volume
= filepath
.GetVolume();
252 m_dirs
= filepath
.GetDirs();
253 m_name
= filepath
.GetName();
254 m_ext
= filepath
.GetExt();
255 m_relative
= filepath
.IsRelative();
258 void wxFileName::Assign(const wxString
& volume
,
259 const wxString
& path
,
260 const wxString
& name
,
262 wxPathFormat format
)
264 SetPath( path
, format
);
271 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
273 wxPathFormat my_format
= GetFormat( format
);
274 wxString my_path
= path
;
278 if (!my_path
.empty())
280 // 1) Determine if the path is relative or absolute.
285 m_relative
= ( my_path
[0u] == wxT(':') );
286 // We then remove a leading ":". The reason is in our
287 // storage form for relative paths:
288 // ":dir:file.txt" actually means "./dir/file.txt" in
289 // DOS notation and should get stored as
290 // (relative) (dir) (file.txt)
291 // "::dir:file.txt" actually means "../dir/file.txt"
292 // stored as (relative) (..) (dir) (file.txt)
293 // This is important only for the Mac as an empty dir
294 // actually means <UP>, whereas under DOS, double
295 // slashes can be ignored: "\\\\" is the same as "\\".
297 my_path
.Remove( 0, 1 );
300 // TODO: what is the relative path format here?
304 m_relative
= ( my_path
[0u] != wxT('/') );
307 m_relative
= ( (my_path
[0u] != wxT('/')) && (my_path
[0u] != wxT('\\')) );
310 wxFAIL_MSG( wxT("error") );
314 // 2) Break up the path into its members. If the original path
315 // was just "/" or "\\", m_dirs will be empty. We know from
316 // the m_relative field, if this means "nothing" or "root dir".
318 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
320 while ( tn
.HasMoreTokens() )
322 wxString token
= tn
.GetNextToken();
324 // Remove empty token under DOS and Unix, interpret them
328 if (my_format
== wxPATH_MAC
)
329 m_dirs
.Add( wxT("..") );
344 void wxFileName::Assign(const wxString
& fullpath
,
347 wxString volume
, path
, name
, ext
;
348 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
350 Assign(volume
, path
, name
, ext
, format
);
353 void wxFileName::Assign(const wxString
& fullpathOrig
,
354 const wxString
& fullname
,
357 // always recognize fullpath as directory, even if it doesn't end with a
359 wxString fullpath
= fullpathOrig
;
360 if ( !wxEndsWithPathSeparator(fullpath
) )
362 fullpath
+= GetPathSeparators(format
)[0u];
365 wxString volume
, path
, name
, ext
;
367 // do some consistency checks in debug mode: the name should be really just
368 // the filename and the path should be really just a path
370 wxString pathDummy
, nameDummy
, extDummy
;
372 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
374 wxASSERT_MSG( pathDummy
.empty(),
375 _T("the file name shouldn't contain the path") );
377 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
379 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
380 _T("the path shouldn't contain file name nor extension") );
382 #else // !__WXDEBUG__
383 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
384 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
385 #endif // __WXDEBUG__/!__WXDEBUG__
387 Assign(volume
, path
, name
, ext
, format
);
390 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
392 Assign(dir
, _T(""), format
);
395 void wxFileName::Clear()
401 m_ext
= wxEmptyString
;
405 wxFileName
wxFileName::FileName(const wxString
& file
)
407 return wxFileName(file
);
411 wxFileName
wxFileName::DirName(const wxString
& dir
)
418 // ----------------------------------------------------------------------------
420 // ----------------------------------------------------------------------------
422 bool wxFileName::FileExists()
424 return wxFileName::FileExists( GetFullPath() );
427 bool wxFileName::FileExists( const wxString
&file
)
429 return ::wxFileExists( file
);
432 bool wxFileName::DirExists()
434 return wxFileName::DirExists( GetFullPath() );
437 bool wxFileName::DirExists( const wxString
&dir
)
439 return ::wxDirExists( dir
);
442 // ----------------------------------------------------------------------------
443 // CWD and HOME stuff
444 // ----------------------------------------------------------------------------
446 void wxFileName::AssignCwd(const wxString
& volume
)
448 AssignDir(wxFileName::GetCwd(volume
));
452 wxString
wxFileName::GetCwd(const wxString
& volume
)
454 // if we have the volume, we must get the current directory on this drive
455 // and to do this we have to chdir to this volume - at least under Windows,
456 // I don't know how to get the current drive on another volume elsewhere
459 if ( !volume
.empty() )
462 SetCwd(volume
+ GetVolumeSeparator());
465 wxString cwd
= ::wxGetCwd();
467 if ( !volume
.empty() )
475 bool wxFileName::SetCwd()
477 return wxFileName::SetCwd( GetFullPath() );
480 bool wxFileName::SetCwd( const wxString
&cwd
)
482 return ::wxSetWorkingDirectory( cwd
);
485 void wxFileName::AssignHomeDir()
487 AssignDir(wxFileName::GetHomeDir());
490 wxString
wxFileName::GetHomeDir()
492 return ::wxGetHomeDir();
495 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
497 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
498 if ( tempname
.empty() )
500 // error, failed to get temp file name
511 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
513 wxString path
, dir
, name
;
515 // use the directory specified by the prefix
516 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
518 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
523 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
525 wxLogLastError(_T("GetTempPath"));
530 // GetTempFileName() fails if we pass it an empty string
535 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
537 wxLogLastError(_T("GetTempFileName"));
542 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
548 #elif defined(__WXPM__)
549 // for now just create a file
551 // future enhancements can be to set some extended attributes for file
552 // systems OS/2 supports that have them (HPFS, FAT32) and security
554 static const wxChar
*szMktempSuffix
= wxT("XXX");
555 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
557 // Temporarily remove - MN
559 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
562 #else // !Windows, !OS/2
565 #if defined(__WXMAC__) && !defined(__DARWIN__)
566 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
568 dir
= wxGetenv(_T("TMP"));
571 dir
= wxGetenv(_T("TEMP"));
588 if ( !wxEndsWithPathSeparator(dir
) &&
589 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
591 path
+= wxFILE_SEP_PATH
;
596 #if defined(HAVE_MKSTEMP)
597 // scratch space for mkstemp()
598 path
+= _T("XXXXXX");
600 // can use the cast here because the length doesn't change and the string
602 int fdTemp
= mkstemp((char *)path
.mb_str());
605 // this might be not necessary as mkstemp() on most systems should have
606 // already done it but it doesn't hurt neither...
609 else // mkstemp() succeeded
611 // avoid leaking the fd
614 fileTemp
->Attach(fdTemp
);
621 #else // !HAVE_MKSTEMP
625 path
+= _T("XXXXXX");
627 if ( !mktemp((char *)path
.mb_str()) )
631 #else // !HAVE_MKTEMP (includes __DOS__)
632 // generate the unique file name ourselves
634 path
<< (unsigned int)getpid();
639 static const size_t numTries
= 1000;
640 for ( size_t n
= 0; n
< numTries
; n
++ )
642 // 3 hex digits is enough for numTries == 1000 < 4096
643 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
644 if ( !wxFile::Exists(pathTry
) )
653 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
658 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
660 #endif // Windows/!Windows
664 wxLogSysError(_("Failed to create a temporary file name"));
666 else if ( fileTemp
&& !fileTemp
->IsOpened() )
668 // open the file - of course, there is a race condition here, this is
669 // why we always prefer using mkstemp()...
671 // NB: GetTempFileName() under Windows creates the file, so using
672 // write_excl there would fail
673 if ( !fileTemp
->Open(path
,
674 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
679 wxS_IRUSR
| wxS_IWUSR
) )
681 // FIXME: If !ok here should we loop and try again with another
682 // file name? That is the standard recourse if open(O_EXCL)
683 // fails, though of course it should be protected against
684 // possible infinite looping too.
686 wxLogError(_("Failed to open temporary file."));
695 // ----------------------------------------------------------------------------
696 // directory operations
697 // ----------------------------------------------------------------------------
699 bool wxFileName::Mkdir( int perm
, bool full
)
701 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
704 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
708 wxFileName
filename(dir
);
709 wxArrayString dirs
= filename
.GetDirs();
710 dirs
.Add(filename
.GetName());
712 size_t count
= dirs
.GetCount();
716 for ( i
= 0; i
< count
; i
++ )
720 if (currPath
.Last() == wxT(':'))
722 // Can't create a root directory so continue to next dir
723 currPath
+= wxFILE_SEP_PATH
;
727 if (!DirExists(currPath
))
728 if (!wxMkdir(currPath
, perm
))
731 if ( (i
< (count
-1)) )
732 currPath
+= wxFILE_SEP_PATH
;
735 return (noErrors
== 0);
739 return ::wxMkdir( dir
, perm
);
742 bool wxFileName::Rmdir()
744 return wxFileName::Rmdir( GetFullPath() );
747 bool wxFileName::Rmdir( const wxString
&dir
)
749 return ::wxRmdir( dir
);
752 // ----------------------------------------------------------------------------
753 // path normalization
754 // ----------------------------------------------------------------------------
756 bool wxFileName::Normalize(int flags
,
760 // the existing path components
761 wxArrayString dirs
= GetDirs();
763 // the path to prepend in front to make the path absolute
766 format
= GetFormat(format
);
768 // make the path absolute
769 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
773 curDir
.AssignCwd(GetVolume());
777 curDir
.AssignDir(cwd
);
781 // the path may be not absolute because it doesn't have the volume name
782 // but in this case we shouldn't modify the directory components of it
783 // but just set the current volume
784 if ( !HasVolume() && curDir
.HasVolume() )
786 SetVolume(curDir
.GetVolume());
790 // yes, it was the case - we don't need curDir then
798 // handle ~ stuff under Unix only
799 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
801 if ( !dirs
.IsEmpty() )
803 wxString dir
= dirs
[0u];
804 if ( !dir
.empty() && dir
[0u] == _T('~') )
806 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
813 // transform relative path into abs one
816 wxArrayString dirsNew
= curDir
.GetDirs();
817 size_t count
= dirs
.GetCount();
818 for ( size_t n
= 0; n
< count
; n
++ )
820 dirsNew
.Add(dirs
[n
]);
826 // now deal with ".", ".." and the rest
828 size_t count
= dirs
.GetCount();
829 for ( size_t n
= 0; n
< count
; n
++ )
831 wxString dir
= dirs
[n
];
833 if ( flags
& wxPATH_NORM_DOTS
)
835 if ( dir
== wxT(".") )
841 if ( dir
== wxT("..") )
843 if ( m_dirs
.IsEmpty() )
845 wxLogError(_("The path '%s' contains too many \"..\"!"),
846 GetFullPath().c_str());
850 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
855 if ( flags
& wxPATH_NORM_ENV_VARS
)
857 dir
= wxExpandEnvVars(dir
);
860 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
868 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
870 // VZ: expand env vars here too?
876 #if defined(__WIN32__)
877 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
879 Assign(GetLongPath());
886 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
888 wxFileName
fnBase(pathBase
, format
);
890 // get cwd only once - small time saving
891 wxString cwd
= wxGetCwd();
892 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
893 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
895 bool withCase
= IsCaseSensitive(format
);
897 // we can't do anything if the files live on different volumes
898 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
904 // same drive, so we don't need our volume
907 // remove common directories starting at the top
908 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
909 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
912 fnBase
.m_dirs
.RemoveAt(0);
915 // add as many ".." as needed
916 size_t count
= fnBase
.m_dirs
.GetCount();
917 for ( size_t i
= 0; i
< count
; i
++ )
919 m_dirs
.Insert(wxT(".."), 0u);
928 // ----------------------------------------------------------------------------
929 // filename kind tests
930 // ----------------------------------------------------------------------------
932 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
934 wxFileName fn1
= *this,
937 // get cwd only once - small time saving
938 wxString cwd
= wxGetCwd();
939 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
940 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
942 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
945 // TODO: compare inodes for Unix, this works even when filenames are
946 // different but files are the same (symlinks) (VZ)
952 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
954 // only Unix filenames are truely case-sensitive
955 return GetFormat(format
) == wxPATH_UNIX
;
959 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
963 if ( (GetFormat(format
) == wxPATH_DOS
) ||
964 (GetFormat(format
) == wxPATH_VMS
) )
966 sepVol
= wxFILE_SEP_DSK
;
974 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
977 switch ( GetFormat(format
) )
980 // accept both as native APIs do but put the native one first as
981 // this is the one we use in GetFullPath()
982 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
986 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
990 seps
= wxFILE_SEP_PATH_UNIX
;
994 seps
= wxFILE_SEP_PATH_MAC
;
998 seps
= wxFILE_SEP_PATH_VMS
;
1006 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1008 // wxString::Find() doesn't work as expected with NUL - it will always find
1009 // it, so it is almost surely a bug if this function is called with NUL arg
1010 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1012 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1015 bool wxFileName::IsWild( wxPathFormat format
)
1017 // FIXME: this is probably false for Mac and this is surely wrong for most
1018 // of Unix shells (think about "[...]")
1020 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
1023 // ----------------------------------------------------------------------------
1024 // path components manipulation
1025 // ----------------------------------------------------------------------------
1027 void wxFileName::AppendDir( const wxString
&dir
)
1032 void wxFileName::PrependDir( const wxString
&dir
)
1034 m_dirs
.Insert( dir
, 0 );
1037 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1039 m_dirs
.Insert( dir
, before
);
1042 void wxFileName::RemoveDir( int pos
)
1044 m_dirs
.Remove( (size_t)pos
);
1047 // ----------------------------------------------------------------------------
1049 // ----------------------------------------------------------------------------
1051 void wxFileName::SetFullName(const wxString
& fullname
)
1053 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1056 wxString
wxFileName::GetFullName() const
1058 wxString fullname
= m_name
;
1059 if ( !m_ext
.empty() )
1061 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1067 wxString
wxFileName::GetPath( bool, wxPathFormat format
) const
1069 // Should add_seperator parameter be used?
1071 format
= GetFormat( format
);
1075 // the leading character
1076 if ( format
== wxPATH_MAC
&& m_relative
)
1078 fullpath
+= wxFILE_SEP_PATH_MAC
;
1080 else if ( format
== wxPATH_DOS
)
1083 fullpath
+= wxFILE_SEP_PATH_DOS
;
1085 else if ( format
== wxPATH_UNIX
)
1088 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1091 // then concatenate all the path components using the path separator
1092 size_t dirCount
= m_dirs
.GetCount();
1095 if ( format
== wxPATH_VMS
)
1097 fullpath
+= wxT('[');
1101 for ( size_t i
= 0; i
< dirCount
; i
++ )
1103 // TODO: What to do with ".." under VMS
1109 if (m_dirs
[i
] == wxT("."))
1111 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1112 fullpath
+= m_dirs
[i
];
1113 fullpath
+= wxT(':');
1118 fullpath
+= m_dirs
[i
];
1119 fullpath
+= wxT('\\');
1124 fullpath
+= m_dirs
[i
];
1125 fullpath
+= wxT('/');
1130 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1131 fullpath
+= m_dirs
[i
];
1132 if (i
== dirCount
-1)
1133 fullpath
+= wxT(']');
1135 fullpath
+= wxT('.');
1140 wxFAIL_MSG( wxT("error") );
1151 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1153 format
= GetFormat(format
);
1157 // first put the volume
1158 if ( !m_volume
.empty() )
1161 // Special Windows UNC paths hack, part 2: undo what we did in
1162 // SplitPath() and make an UNC path if we have a drive which is not a
1163 // single letter (hopefully the network shares can't be one letter only
1164 // although I didn't find any authoritative docs on this)
1165 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1167 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1169 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1171 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1177 // the leading character
1178 if ( format
== wxPATH_MAC
&& m_relative
)
1180 fullpath
+= wxFILE_SEP_PATH_MAC
;
1182 else if ( format
== wxPATH_DOS
)
1185 fullpath
+= wxFILE_SEP_PATH_DOS
;
1187 else if ( format
== wxPATH_UNIX
)
1190 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1193 // then concatenate all the path components using the path separator
1194 size_t dirCount
= m_dirs
.GetCount();
1197 if ( format
== wxPATH_VMS
)
1199 fullpath
+= wxT('[');
1203 for ( size_t i
= 0; i
< dirCount
; i
++ )
1205 // TODO: What to do with ".." under VMS
1211 if (m_dirs
[i
] == wxT("."))
1213 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1214 fullpath
+= m_dirs
[i
];
1215 fullpath
+= wxT(':');
1220 fullpath
+= m_dirs
[i
];
1221 fullpath
+= wxT('\\');
1226 fullpath
+= m_dirs
[i
];
1227 fullpath
+= wxT('/');
1232 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1233 fullpath
+= m_dirs
[i
];
1234 if (i
== dirCount
-1)
1235 fullpath
+= wxT(']');
1237 fullpath
+= wxT('.');
1242 wxFAIL_MSG( wxT("error") );
1248 // finally add the file name and extension
1249 fullpath
+= GetFullName();
1254 // Return the short form of the path (returns identity on non-Windows platforms)
1255 wxString
wxFileName::GetShortPath() const
1257 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1258 wxString
path(GetFullPath());
1260 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1264 ok
= ::GetShortPathName
1267 pathOut
.GetWriteBuf(sz
),
1270 pathOut
.UngetWriteBuf();
1277 return GetFullPath();
1281 // Return the long form of the path (returns identity on non-Windows platforms)
1282 wxString
wxFileName::GetLongPath() const
1285 path
= GetFullPath();
1287 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1288 bool success
= FALSE
;
1290 // VZ: this code was disabled, why?
1291 #if 0 // wxUSE_DYNAMIC_LOADER
1292 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1294 static bool s_triedToLoad
= FALSE
;
1296 if ( !s_triedToLoad
)
1298 s_triedToLoad
= TRUE
;
1299 wxDynamicLibrary
dllKernel(_T("kernel32"));
1300 if ( dllKernel
.IsLoaded() )
1302 // may succeed or fail depending on the Windows version
1303 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1305 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1307 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1310 if ( s_pfnGetLongPathName
)
1312 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1313 bool ok
= dwSize
> 0;
1317 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1321 ok
= (*s_pfnGetLongPathName
)
1324 pathOut
.GetWriteBuf(sz
),
1327 pathOut
.UngetWriteBuf();
1337 #endif // wxUSE_DYNAMIC_LOADER
1341 // The OS didn't support GetLongPathName, or some other error.
1342 // We need to call FindFirstFile on each component in turn.
1344 WIN32_FIND_DATA findFileData
;
1346 pathOut
= wxEmptyString
;
1348 wxArrayString dirs
= GetDirs();
1349 dirs
.Add(GetFullName());
1353 size_t count
= dirs
.GetCount();
1354 for ( size_t i
= 0; i
< count
; i
++ )
1356 // We're using pathOut to collect the long-name path, but using a
1357 // temporary for appending the last path component which may be
1359 tmpPath
= pathOut
+ dirs
[i
];
1361 if ( tmpPath
.empty() )
1364 if ( tmpPath
.Last() == wxT(':') )
1366 // Can't pass a drive and root dir to FindFirstFile,
1367 // so continue to next dir
1368 tmpPath
+= wxFILE_SEP_PATH
;
1373 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1374 if (hFind
== INVALID_HANDLE_VALUE
)
1376 // Error: return immediately with the original path
1380 pathOut
+= findFileData
.cFileName
;
1381 if ( (i
< (count
-1)) )
1382 pathOut
+= wxFILE_SEP_PATH
;
1389 #endif // Win32/!Win32
1394 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1396 if (format
== wxPATH_NATIVE
)
1398 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1399 format
= wxPATH_DOS
;
1400 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1401 format
= wxPATH_MAC
;
1402 #elif defined(__VMS)
1403 format
= wxPATH_VMS
;
1405 format
= wxPATH_UNIX
;
1411 // ----------------------------------------------------------------------------
1412 // path splitting function
1413 // ----------------------------------------------------------------------------
1416 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1417 wxString
*pstrVolume
,
1421 wxPathFormat format
)
1423 format
= GetFormat(format
);
1425 wxString fullpath
= fullpathWithVolume
;
1427 // under VMS the end of the path is ']', not the path separator used to
1428 // separate the components
1429 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1430 : GetPathSeparators(format
);
1432 // special Windows UNC paths hack: transform \\share\path into share:path
1433 if ( format
== wxPATH_DOS
)
1435 if ( fullpath
.length() >= 4 &&
1436 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1437 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1439 fullpath
.erase(0, 2);
1441 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1442 if ( posFirstSlash
!= wxString::npos
)
1444 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1446 // UNC paths are always absolute, right? (FIXME)
1447 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1452 // We separate the volume here
1453 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1455 wxString sepVol
= GetVolumeSeparator(format
);
1457 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1458 if ( posFirstColon
!= wxString::npos
)
1462 *pstrVolume
= fullpath
.Left(posFirstColon
);
1465 // remove the volume name and the separator from the full path
1466 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1470 // find the positions of the last dot and last path separator in the path
1471 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1472 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1474 if ( (posLastDot
!= wxString::npos
) &&
1475 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1477 if ( (posLastDot
== 0) ||
1478 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1480 // under Unix and VMS, dot may be (and commonly is) the first
1481 // character of the filename, don't treat the entire filename as
1482 // extension in this case
1483 posLastDot
= wxString::npos
;
1487 // if we do have a dot and a slash, check that the dot is in the name part
1488 if ( (posLastDot
!= wxString::npos
) &&
1489 (posLastSlash
!= wxString::npos
) &&
1490 (posLastDot
< posLastSlash
) )
1492 // the dot is part of the path, not the start of the extension
1493 posLastDot
= wxString::npos
;
1496 // now fill in the variables provided by user
1499 if ( posLastSlash
== wxString::npos
)
1506 // take everything up to the path separator but take care to make
1507 // the path equal to something like '/', not empty, for the files
1508 // immediately under root directory
1509 size_t len
= posLastSlash
;
1511 // this rule does not apply to mac since we do not start with colons (sep)
1512 // except for relative paths
1513 if ( !len
&& format
!= wxPATH_MAC
)
1516 *pstrPath
= fullpath
.Left(len
);
1518 // special VMS hack: remove the initial bracket
1519 if ( format
== wxPATH_VMS
)
1521 if ( (*pstrPath
)[0u] == _T('[') )
1522 pstrPath
->erase(0, 1);
1529 // take all characters starting from the one after the last slash and
1530 // up to, but excluding, the last dot
1531 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1533 if ( posLastDot
== wxString::npos
)
1535 // take all until the end
1536 count
= wxString::npos
;
1538 else if ( posLastSlash
== wxString::npos
)
1542 else // have both dot and slash
1544 count
= posLastDot
- posLastSlash
- 1;
1547 *pstrName
= fullpath
.Mid(nStart
, count
);
1552 if ( posLastDot
== wxString::npos
)
1559 // take everything after the dot
1560 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1566 void wxFileName::SplitPath(const wxString
& fullpath
,
1570 wxPathFormat format
)
1573 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1575 if ( path
&& !volume
.empty() )
1577 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1581 // ----------------------------------------------------------------------------
1583 // ----------------------------------------------------------------------------
1585 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1586 const wxDateTime
*dtMod
,
1587 const wxDateTime
*dtCreate
)
1589 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1590 if ( !dtAccess
&& !dtMod
)
1592 // can't modify the creation time anyhow, don't try
1596 // if dtAccess or dtMod is not specified, use the other one (which must be
1597 // non NULL because of the test above) for both times
1599 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1600 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1601 if ( utime(GetFullPath(), &utm
) == 0 )
1605 #elif defined(__WIN32__)
1606 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1609 FILETIME ftAccess
, ftCreate
, ftWrite
;
1612 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1614 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1616 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1618 if ( ::SetFileTime(fh
,
1619 dtCreate
? &ftCreate
: NULL
,
1620 dtAccess
? &ftAccess
: NULL
,
1621 dtMod
? &ftWrite
: NULL
) )
1626 #else // other platform
1629 wxLogSysError(_("Failed to modify file times for '%s'"),
1630 GetFullPath().c_str());
1635 bool wxFileName::Touch()
1637 #if defined(__UNIX_LIKE__)
1638 // under Unix touching file is simple: just pass NULL to utime()
1639 if ( utime(GetFullPath(), NULL
) == 0 )
1644 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1647 #else // other platform
1648 wxDateTime dtNow
= wxDateTime::Now();
1650 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1654 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1656 wxDateTime
*dtCreate
) const
1658 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1660 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1663 dtAccess
->Set(stBuf
.st_atime
);
1665 dtMod
->Set(stBuf
.st_mtime
);
1667 dtCreate
->Set(stBuf
.st_ctime
);
1671 #elif defined(__WIN32__)
1672 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1675 FILETIME ftAccess
, ftCreate
, ftWrite
;
1677 if ( ::GetFileTime(fh
,
1678 dtMod
? &ftCreate
: NULL
,
1679 dtAccess
? &ftAccess
: NULL
,
1680 dtCreate
? &ftWrite
: NULL
) )
1683 ConvertFileTimeToWx(dtMod
, ftCreate
);
1685 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1687 ConvertFileTimeToWx(dtCreate
, ftWrite
);
1692 #else // other platform
1695 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1696 GetFullPath().c_str());
1703 const short kMacExtensionMaxLength
= 16 ;
1706 char m_ext
[kMacExtensionMaxLength
] ;
1709 } MacDefaultExtensionRecord
;
1711 #include "wx/dynarray.h"
1712 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1713 #include "wx/arrimpl.cpp"
1714 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray
) ;
1716 MacDefaultExtensionArray gMacDefaultExtensions
;
1717 bool gMacDefaultExtensionsInited
= false ;
1719 static void MacEnsureDefaultExtensionsLoaded()
1721 if ( !gMacDefaultExtensionsInited
)
1723 // load the default extensions
1724 MacDefaultExtensionRecord defaults
[] =
1726 { "txt" , 'TEXT' , 'ttxt' } ,
1729 // we could load the pc exchange prefs here too
1731 for ( int i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1733 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1735 gMacDefaultExtensionsInited
= true ;
1738 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1742 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1743 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1744 wxCHECK( err
== noErr
, false ) ;
1746 fndrInfo
.fdType
= type
;
1747 fndrInfo
.fdCreator
= creator
;
1748 FSpSetFInfo( &spec
, &fndrInfo
) ;
1752 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1756 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1757 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1758 wxCHECK( err
== noErr
, false ) ;
1760 *type
= fndrInfo
.fdType
;
1761 *creator
= fndrInfo
.fdCreator
;
1765 bool wxFileName::MacSetDefaultTypeAndCreator()
1767 wxUint32 type
, creator
;
1768 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1771 return MacSetTypeAndCreator( type
, creator
) ;
1776 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1778 MacEnsureDefaultExtensionsLoaded() ;
1779 wxString extl
= ext
.Lower() ;
1780 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1782 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1784 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1785 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1792 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1794 MacEnsureDefaultExtensionsLoaded() ;
1795 MacDefaultExtensionRecord rec
;
1797 rec
.m_creator
= creator
;
1798 strncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1799 gMacDefaultExtensions
.Add( rec
) ;