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__)
138 wxFileHandle(const wxString
& filename
)
140 m_hFile
= ::CreateFile
143 GENERIC_READ
, // access mask
145 NULL
, // no secutity attr
146 OPEN_EXISTING
, // creation disposition
148 NULL
// no template file
151 if ( m_hFile
== INVALID_HANDLE_VALUE
)
153 wxLogSysError(_("Failed to open '%s' for reading"),
160 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
162 if ( !::CloseHandle(m_hFile
) )
164 wxLogSysError(_("Failed to close file handle"));
169 // return TRUE only if the file could be opened successfully
170 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
173 operator HANDLE() const { return m_hFile
; }
181 // ----------------------------------------------------------------------------
183 // ----------------------------------------------------------------------------
185 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
187 // convert between wxDateTime and FILETIME which is a 64-bit value representing
188 // the number of 100-nanosecond intervals since January 1, 1601.
190 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
191 // FILETIME reference point (January 1, 1601)
192 static const wxLongLong FILETIME_EPOCH_OFFSET
= wxLongLong(0xa97, 0x30b66800);
194 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
196 wxLongLong
ll(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
198 // convert 100ns to ms
201 // move it to our Epoch
202 ll
-= FILETIME_EPOCH_OFFSET
;
204 *dt
= wxDateTime(ll
);
207 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
209 // do the reverse of ConvertFileTimeToWx()
210 wxLongLong ll
= dt
.GetValue();
212 ll
+= FILETIME_EPOCH_OFFSET
;
214 ft
->dwHighDateTime
= ll
.GetHi();
215 ft
->dwLowDateTime
= ll
.GetLo();
220 // ============================================================================
222 // ============================================================================
224 // ----------------------------------------------------------------------------
225 // wxFileName construction
226 // ----------------------------------------------------------------------------
228 void wxFileName::Assign( const wxFileName
&filepath
)
230 m_volume
= filepath
.GetVolume();
231 m_dirs
= filepath
.GetDirs();
232 m_name
= filepath
.GetName();
233 m_ext
= filepath
.GetExt();
234 m_relative
= filepath
.IsRelative();
237 void wxFileName::Assign(const wxString
& volume
,
238 const wxString
& path
,
239 const wxString
& name
,
241 wxPathFormat format
)
243 SetPath( path
, format
);
250 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
252 wxPathFormat my_format
= GetFormat( format
);
253 wxString my_path
= path
;
257 if (!my_path
.empty())
259 // 1) Determine if the path is relative or absolute.
264 m_relative
= ( my_path
[0u] == wxT(':') );
265 // We then remove a leading ":". The reason is in our
266 // storage form for relative paths:
267 // ":dir:file.txt" actually means "./dir/file.txt" in
268 // DOS notation and should get stored as
269 // (relative) (dir) (file.txt)
270 // "::dir:file.txt" actually means "../dir/file.txt"
271 // stored as (relative) (..) (dir) (file.txt)
272 // This is important only for the Mac as an empty dir
273 // actually means <UP>, whereas under DOS, double
274 // slashes can be ignored: "\\\\" is the same as "\\".
276 my_path
.Remove( 0, 1 );
279 // TODO: what is the relative path format here?
283 m_relative
= ( my_path
[0u] != wxT('/') );
286 m_relative
= ( (my_path
[0u] != wxT('/')) && (my_path
[0u] != wxT('\\')) );
289 wxFAIL_MSG( wxT("error") );
293 // 2) Break up the path into its members. If the original path
294 // was just "/" or "\\", m_dirs will be empty. We know from
295 // the m_relative field, if this means "nothing" or "root dir".
297 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
299 while ( tn
.HasMoreTokens() )
301 wxString token
= tn
.GetNextToken();
303 // Remove empty token under DOS and Unix, interpret them
307 if (my_format
== wxPATH_MAC
)
308 m_dirs
.Add( wxT("..") );
323 void wxFileName::Assign(const wxString
& fullpath
,
326 wxString volume
, path
, name
, ext
;
327 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
329 Assign(volume
, path
, name
, ext
, format
);
332 void wxFileName::Assign(const wxString
& fullpathOrig
,
333 const wxString
& fullname
,
336 // always recognize fullpath as directory, even if it doesn't end with a
338 wxString fullpath
= fullpathOrig
;
339 if ( !wxEndsWithPathSeparator(fullpath
) )
341 fullpath
+= GetPathSeparators(format
)[0u];
344 wxString volume
, path
, name
, ext
;
346 // do some consistency checks in debug mode: the name should be really just
347 // the filename and the path should be really just a path
349 wxString pathDummy
, nameDummy
, extDummy
;
351 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
353 wxASSERT_MSG( pathDummy
.empty(),
354 _T("the file name shouldn't contain the path") );
356 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
358 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
359 _T("the path shouldn't contain file name nor extension") );
361 #else // !__WXDEBUG__
362 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
363 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
364 #endif // __WXDEBUG__/!__WXDEBUG__
366 Assign(volume
, path
, name
, ext
, format
);
369 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
371 Assign(dir
, _T(""), format
);
374 void wxFileName::Clear()
380 m_ext
= wxEmptyString
;
384 wxFileName
wxFileName::FileName(const wxString
& file
)
386 return wxFileName(file
);
390 wxFileName
wxFileName::DirName(const wxString
& dir
)
397 // ----------------------------------------------------------------------------
399 // ----------------------------------------------------------------------------
401 bool wxFileName::FileExists()
403 return wxFileName::FileExists( GetFullPath() );
406 bool wxFileName::FileExists( const wxString
&file
)
408 return ::wxFileExists( file
);
411 bool wxFileName::DirExists()
413 return wxFileName::DirExists( GetFullPath() );
416 bool wxFileName::DirExists( const wxString
&dir
)
418 return ::wxDirExists( dir
);
421 // ----------------------------------------------------------------------------
422 // CWD and HOME stuff
423 // ----------------------------------------------------------------------------
425 void wxFileName::AssignCwd(const wxString
& volume
)
427 AssignDir(wxFileName::GetCwd(volume
));
431 wxString
wxFileName::GetCwd(const wxString
& volume
)
433 // if we have the volume, we must get the current directory on this drive
434 // and to do this we have to chdir to this volume - at least under Windows,
435 // I don't know how to get the current drive on another volume elsewhere
438 if ( !volume
.empty() )
441 SetCwd(volume
+ GetVolumeSeparator());
444 wxString cwd
= ::wxGetCwd();
446 if ( !volume
.empty() )
454 bool wxFileName::SetCwd()
456 return wxFileName::SetCwd( GetFullPath() );
459 bool wxFileName::SetCwd( const wxString
&cwd
)
461 return ::wxSetWorkingDirectory( cwd
);
464 void wxFileName::AssignHomeDir()
466 AssignDir(wxFileName::GetHomeDir());
469 wxString
wxFileName::GetHomeDir()
471 return ::wxGetHomeDir();
474 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
476 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
477 if ( tempname
.empty() )
479 // error, failed to get temp file name
490 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
492 wxString path
, dir
, name
;
494 // use the directory specified by the prefix
495 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
497 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
502 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
504 wxLogLastError(_T("GetTempPath"));
509 // GetTempFileName() fails if we pass it an empty string
514 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
516 wxLogLastError(_T("GetTempFileName"));
521 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
527 #elif defined(__WXPM__)
528 // for now just create a file
530 // future enhancements can be to set some extended attributes for file
531 // systems OS/2 supports that have them (HPFS, FAT32) and security
533 static const wxChar
*szMktempSuffix
= wxT("XXX");
534 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
536 // Temporarily remove - MN
538 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
541 #else // !Windows, !OS/2
544 #if defined(__WXMAC__) && !defined(__DARWIN__)
545 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
547 dir
= wxGetenv(_T("TMP"));
550 dir
= wxGetenv(_T("TEMP"));
567 if ( !wxEndsWithPathSeparator(dir
) &&
568 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
570 path
+= wxFILE_SEP_PATH
;
575 #if defined(HAVE_MKSTEMP)
576 // scratch space for mkstemp()
577 path
+= _T("XXXXXX");
579 // can use the cast here because the length doesn't change and the string
581 int fdTemp
= mkstemp((char *)path
.mb_str());
584 // this might be not necessary as mkstemp() on most systems should have
585 // already done it but it doesn't hurt neither...
588 else // mkstemp() succeeded
590 // avoid leaking the fd
593 fileTemp
->Attach(fdTemp
);
600 #else // !HAVE_MKSTEMP
604 path
+= _T("XXXXXX");
606 if ( !mktemp((char *)path
.mb_str()) )
610 #else // !HAVE_MKTEMP (includes __DOS__)
611 // generate the unique file name ourselves
613 path
<< (unsigned int)getpid();
618 static const size_t numTries
= 1000;
619 for ( size_t n
= 0; n
< numTries
; n
++ )
621 // 3 hex digits is enough for numTries == 1000 < 4096
622 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
623 if ( !wxFile::Exists(pathTry
) )
632 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
637 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
639 #endif // Windows/!Windows
643 wxLogSysError(_("Failed to create a temporary file name"));
645 else if ( fileTemp
&& !fileTemp
->IsOpened() )
647 // open the file - of course, there is a race condition here, this is
648 // why we always prefer using mkstemp()...
650 // NB: GetTempFileName() under Windows creates the file, so using
651 // write_excl there would fail
652 if ( !fileTemp
->Open(path
,
653 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
658 wxS_IRUSR
| wxS_IWUSR
) )
660 // FIXME: If !ok here should we loop and try again with another
661 // file name? That is the standard recourse if open(O_EXCL)
662 // fails, though of course it should be protected against
663 // possible infinite looping too.
665 wxLogError(_("Failed to open temporary file."));
674 // ----------------------------------------------------------------------------
675 // directory operations
676 // ----------------------------------------------------------------------------
678 bool wxFileName::Mkdir( int perm
, bool full
)
680 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
683 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
687 wxFileName
filename(dir
);
688 wxArrayString dirs
= filename
.GetDirs();
689 dirs
.Add(filename
.GetName());
691 size_t count
= dirs
.GetCount();
695 for ( i
= 0; i
< count
; i
++ )
699 if (currPath
.Last() == wxT(':'))
701 // Can't create a root directory so continue to next dir
702 currPath
+= wxFILE_SEP_PATH
;
706 if (!DirExists(currPath
))
707 if (!wxMkdir(currPath
, perm
))
710 if ( (i
< (count
-1)) )
711 currPath
+= wxFILE_SEP_PATH
;
714 return (noErrors
== 0);
718 return ::wxMkdir( dir
, perm
);
721 bool wxFileName::Rmdir()
723 return wxFileName::Rmdir( GetFullPath() );
726 bool wxFileName::Rmdir( const wxString
&dir
)
728 return ::wxRmdir( dir
);
731 // ----------------------------------------------------------------------------
732 // path normalization
733 // ----------------------------------------------------------------------------
735 bool wxFileName::Normalize(wxPathNormalize flags
,
739 // the existing path components
740 wxArrayString dirs
= GetDirs();
742 // the path to prepend in front to make the path absolute
745 format
= GetFormat(format
);
747 // make the path absolute
748 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && m_relative
)
752 curDir
.AssignCwd(GetVolume());
756 curDir
.AssignDir(cwd
);
760 // the path may be not absolute because it doesn't have the volume name
761 // but in this case we shouldn't modify the directory components of it
762 // but just set the current volume
763 if ( !HasVolume() && curDir
.HasVolume() )
765 SetVolume(curDir
.GetVolume());
769 // yes, it was the case - we don't need curDir then
777 // handle ~ stuff under Unix only
778 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
780 if ( !dirs
.IsEmpty() )
782 wxString dir
= dirs
[0u];
783 if ( !dir
.empty() && dir
[0u] == _T('~') )
785 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
792 // transform relative path into abs one
795 wxArrayString dirsNew
= curDir
.GetDirs();
796 size_t count
= dirs
.GetCount();
797 for ( size_t n
= 0; n
< count
; n
++ )
799 dirsNew
.Add(dirs
[n
]);
805 // now deal with ".", ".." and the rest
807 size_t count
= dirs
.GetCount();
808 for ( size_t n
= 0; n
< count
; n
++ )
810 wxString dir
= dirs
[n
];
812 if ( flags
& wxPATH_NORM_DOTS
)
814 if ( dir
== wxT(".") )
820 if ( dir
== wxT("..") )
822 if ( m_dirs
.IsEmpty() )
824 wxLogError(_("The path '%s' contains too many \"..\"!"),
825 GetFullPath().c_str());
829 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
834 if ( flags
& wxPATH_NORM_ENV_VARS
)
836 dir
= wxExpandEnvVars(dir
);
839 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
847 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
849 // VZ: expand env vars here too?
855 #if defined(__WIN32__)
856 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
858 Assign(GetLongPath());
865 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
867 wxFileName
fnBase(pathBase
, format
);
869 // get cwd only once - small time saving
870 wxString cwd
= wxGetCwd();
871 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
872 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
874 bool withCase
= IsCaseSensitive(format
);
876 // we can't do anything if the files live on different volumes
877 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
883 // same drive, so we don't need our volume
886 // remove common directories starting at the top
887 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
888 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
891 fnBase
.m_dirs
.RemoveAt(0);
894 // add as many ".." as needed
895 size_t count
= fnBase
.m_dirs
.GetCount();
896 for ( size_t i
= 0; i
< count
; i
++ )
898 m_dirs
.Insert(wxT(".."), 0u);
907 // ----------------------------------------------------------------------------
908 // filename kind tests
909 // ----------------------------------------------------------------------------
911 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
913 wxFileName fn1
= *this,
916 // get cwd only once - small time saving
917 wxString cwd
= wxGetCwd();
918 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
919 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
921 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
924 // TODO: compare inodes for Unix, this works even when filenames are
925 // different but files are the same (symlinks) (VZ)
931 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
933 // only Unix filenames are truely case-sensitive
934 return GetFormat(format
) == wxPATH_UNIX
;
938 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
942 if ( (GetFormat(format
) == wxPATH_DOS
) ||
943 (GetFormat(format
) == wxPATH_VMS
) )
945 sepVol
= wxFILE_SEP_DSK
;
953 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
956 switch ( GetFormat(format
) )
959 // accept both as native APIs do but put the native one first as
960 // this is the one we use in GetFullPath()
961 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
965 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
969 seps
= wxFILE_SEP_PATH_UNIX
;
973 seps
= wxFILE_SEP_PATH_MAC
;
977 seps
= wxFILE_SEP_PATH_VMS
;
985 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
987 // wxString::Find() doesn't work as expected with NUL - it will always find
988 // it, so it is almost surely a bug if this function is called with NUL arg
989 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
991 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
994 bool wxFileName::IsWild( wxPathFormat format
)
996 // FIXME: this is probably false for Mac and this is surely wrong for most
997 // of Unix shells (think about "[...]")
999 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
1002 // ----------------------------------------------------------------------------
1003 // path components manipulation
1004 // ----------------------------------------------------------------------------
1006 void wxFileName::AppendDir( const wxString
&dir
)
1011 void wxFileName::PrependDir( const wxString
&dir
)
1013 m_dirs
.Insert( dir
, 0 );
1016 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1018 m_dirs
.Insert( dir
, before
);
1021 void wxFileName::RemoveDir( int pos
)
1023 m_dirs
.Remove( (size_t)pos
);
1026 // ----------------------------------------------------------------------------
1028 // ----------------------------------------------------------------------------
1030 void wxFileName::SetFullName(const wxString
& fullname
)
1032 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1035 wxString
wxFileName::GetFullName() const
1037 wxString fullname
= m_name
;
1038 if ( !m_ext
.empty() )
1040 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1046 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1048 format
= GetFormat( format
);
1052 // the leading character
1053 if ( format
== wxPATH_MAC
&& m_relative
)
1055 fullpath
+= wxFILE_SEP_PATH_MAC
;
1057 else if ( format
== wxPATH_DOS
)
1060 fullpath
+= wxFILE_SEP_PATH_DOS
;
1062 else if ( format
== wxPATH_UNIX
)
1065 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1068 // then concatenate all the path components using the path separator
1069 size_t dirCount
= m_dirs
.GetCount();
1072 if ( format
== wxPATH_VMS
)
1074 fullpath
+= wxT('[');
1078 for ( size_t i
= 0; i
< dirCount
; i
++ )
1080 // TODO: What to do with ".." under VMS
1086 if (m_dirs
[i
] == wxT("."))
1088 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1089 fullpath
+= m_dirs
[i
];
1090 fullpath
+= wxT(':');
1095 fullpath
+= m_dirs
[i
];
1096 fullpath
+= wxT('\\');
1101 fullpath
+= m_dirs
[i
];
1102 fullpath
+= wxT('/');
1107 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1108 fullpath
+= m_dirs
[i
];
1109 if (i
== dirCount
-1)
1110 fullpath
+= wxT(']');
1112 fullpath
+= wxT('.');
1117 wxFAIL_MSG( wxT("error") );
1128 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1130 format
= GetFormat(format
);
1134 // first put the volume
1135 if ( !m_volume
.empty() )
1138 // Special Windows UNC paths hack, part 2: undo what we did in
1139 // SplitPath() and make an UNC path if we have a drive which is not a
1140 // single letter (hopefully the network shares can't be one letter only
1141 // although I didn't find any authoritative docs on this)
1142 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1144 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1146 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1148 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1154 // the leading character
1155 if ( format
== wxPATH_MAC
&& m_relative
)
1157 fullpath
+= wxFILE_SEP_PATH_MAC
;
1159 else if ( format
== wxPATH_DOS
)
1162 fullpath
+= wxFILE_SEP_PATH_DOS
;
1164 else if ( format
== wxPATH_UNIX
)
1167 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1170 // then concatenate all the path components using the path separator
1171 size_t dirCount
= m_dirs
.GetCount();
1174 if ( format
== wxPATH_VMS
)
1176 fullpath
+= wxT('[');
1180 for ( size_t i
= 0; i
< dirCount
; i
++ )
1182 // TODO: What to do with ".." under VMS
1188 if (m_dirs
[i
] == wxT("."))
1190 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1191 fullpath
+= m_dirs
[i
];
1192 fullpath
+= wxT(':');
1197 fullpath
+= m_dirs
[i
];
1198 fullpath
+= wxT('\\');
1203 fullpath
+= m_dirs
[i
];
1204 fullpath
+= wxT('/');
1209 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1210 fullpath
+= m_dirs
[i
];
1211 if (i
== dirCount
-1)
1212 fullpath
+= wxT(']');
1214 fullpath
+= wxT('.');
1219 wxFAIL_MSG( wxT("error") );
1225 // finally add the file name and extension
1226 fullpath
+= GetFullName();
1231 // Return the short form of the path (returns identity on non-Windows platforms)
1232 wxString
wxFileName::GetShortPath() const
1234 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1235 wxString
path(GetFullPath());
1237 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1241 ok
= ::GetShortPathName
1244 pathOut
.GetWriteBuf(sz
),
1247 pathOut
.UngetWriteBuf();
1254 return GetFullPath();
1258 // Return the long form of the path (returns identity on non-Windows platforms)
1259 wxString
wxFileName::GetLongPath() const
1262 path
= GetFullPath();
1264 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1265 bool success
= FALSE
;
1267 // VZ: this code was disabled, why?
1268 #if 0 // wxUSE_DYNAMIC_LOADER
1269 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1271 static bool s_triedToLoad
= FALSE
;
1273 if ( !s_triedToLoad
)
1275 s_triedToLoad
= TRUE
;
1276 wxDynamicLibrary
dllKernel(_T("kernel32"));
1277 if ( dllKernel
.IsLoaded() )
1279 // may succeed or fail depending on the Windows version
1280 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1282 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1284 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1287 if ( s_pfnGetLongPathName
)
1289 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1290 bool ok
= dwSize
> 0;
1294 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1298 ok
= (*s_pfnGetLongPathName
)
1301 pathOut
.GetWriteBuf(sz
),
1304 pathOut
.UngetWriteBuf();
1314 #endif // wxUSE_DYNAMIC_LOADER
1318 // The OS didn't support GetLongPathName, or some other error.
1319 // We need to call FindFirstFile on each component in turn.
1321 WIN32_FIND_DATA findFileData
;
1323 pathOut
= wxEmptyString
;
1325 wxArrayString dirs
= GetDirs();
1326 dirs
.Add(GetFullName());
1330 size_t count
= dirs
.GetCount();
1331 for ( size_t i
= 0; i
< count
; i
++ )
1333 // We're using pathOut to collect the long-name path, but using a
1334 // temporary for appending the last path component which may be
1336 tmpPath
= pathOut
+ dirs
[i
];
1338 if ( tmpPath
.empty() )
1341 if ( tmpPath
.Last() == wxT(':') )
1343 // Can't pass a drive and root dir to FindFirstFile,
1344 // so continue to next dir
1345 tmpPath
+= wxFILE_SEP_PATH
;
1350 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1351 if (hFind
== INVALID_HANDLE_VALUE
)
1353 // Error: return immediately with the original path
1357 pathOut
+= findFileData
.cFileName
;
1358 if ( (i
< (count
-1)) )
1359 pathOut
+= wxFILE_SEP_PATH
;
1366 #endif // Win32/!Win32
1371 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1373 if (format
== wxPATH_NATIVE
)
1375 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1376 format
= wxPATH_DOS
;
1377 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1378 format
= wxPATH_MAC
;
1379 #elif defined(__VMS)
1380 format
= wxPATH_VMS
;
1382 format
= wxPATH_UNIX
;
1388 // ----------------------------------------------------------------------------
1389 // path splitting function
1390 // ----------------------------------------------------------------------------
1393 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1394 wxString
*pstrVolume
,
1398 wxPathFormat format
)
1400 format
= GetFormat(format
);
1402 wxString fullpath
= fullpathWithVolume
;
1404 // under VMS the end of the path is ']', not the path separator used to
1405 // separate the components
1406 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1407 : GetPathSeparators(format
);
1409 // special Windows UNC paths hack: transform \\share\path into share:path
1410 if ( format
== wxPATH_DOS
)
1412 if ( fullpath
.length() >= 4 &&
1413 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1414 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1416 fullpath
.erase(0, 2);
1418 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1419 if ( posFirstSlash
!= wxString::npos
)
1421 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1423 // UNC paths are always absolute, right? (FIXME)
1424 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1429 // We separate the volume here
1430 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1432 wxString sepVol
= GetVolumeSeparator(format
);
1434 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1435 if ( posFirstColon
!= wxString::npos
)
1439 *pstrVolume
= fullpath
.Left(posFirstColon
);
1442 // remove the volume name and the separator from the full path
1443 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1447 // find the positions of the last dot and last path separator in the path
1448 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1449 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1451 if ( (posLastDot
!= wxString::npos
) &&
1452 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1454 if ( (posLastDot
== 0) ||
1455 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1457 // under Unix and VMS, dot may be (and commonly is) the first
1458 // character of the filename, don't treat the entire filename as
1459 // extension in this case
1460 posLastDot
= wxString::npos
;
1464 // if we do have a dot and a slash, check that the dot is in the name part
1465 if ( (posLastDot
!= wxString::npos
) &&
1466 (posLastSlash
!= wxString::npos
) &&
1467 (posLastDot
< posLastSlash
) )
1469 // the dot is part of the path, not the start of the extension
1470 posLastDot
= wxString::npos
;
1473 // now fill in the variables provided by user
1476 if ( posLastSlash
== wxString::npos
)
1483 // take everything up to the path separator but take care to make
1484 // the path equal to something like '/', not empty, for the files
1485 // immediately under root directory
1486 size_t len
= posLastSlash
;
1488 // this rule does not apply to mac since we do not start with colons (sep)
1489 // except for relative paths
1490 if ( !len
&& format
!= wxPATH_MAC
)
1493 *pstrPath
= fullpath
.Left(len
);
1495 // special VMS hack: remove the initial bracket
1496 if ( format
== wxPATH_VMS
)
1498 if ( (*pstrPath
)[0u] == _T('[') )
1499 pstrPath
->erase(0, 1);
1506 // take all characters starting from the one after the last slash and
1507 // up to, but excluding, the last dot
1508 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1510 if ( posLastDot
== wxString::npos
)
1512 // take all until the end
1513 count
= wxString::npos
;
1515 else if ( posLastSlash
== wxString::npos
)
1519 else // have both dot and slash
1521 count
= posLastDot
- posLastSlash
- 1;
1524 *pstrName
= fullpath
.Mid(nStart
, count
);
1529 if ( posLastDot
== wxString::npos
)
1536 // take everything after the dot
1537 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1543 void wxFileName::SplitPath(const wxString
& fullpath
,
1547 wxPathFormat format
)
1550 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1552 if ( path
&& !volume
.empty() )
1554 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1558 // ----------------------------------------------------------------------------
1560 // ----------------------------------------------------------------------------
1562 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1563 const wxDateTime
*dtAccess
,
1564 const wxDateTime
*dtMod
)
1566 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1567 if ( !dtAccess
&& !dtMod
)
1569 // can't modify the creation time anyhow, don't try
1573 // if dtAccess or dtMod is not specified, use the other one (which must be
1574 // non NULL because of the test above) for both times
1576 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1577 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1578 if ( utime(GetFullPath(), &utm
) == 0 )
1582 #elif defined(__WIN32__)
1583 wxFileHandle
fh(GetFullPath());
1586 FILETIME ftAccess
, ftCreate
, ftWrite
;
1589 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1591 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1593 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1595 if ( ::SetFileTime(fh
,
1596 dtCreate
? &ftCreate
: NULL
,
1597 dtAccess
? &ftAccess
: NULL
,
1598 dtMod
? &ftWrite
: NULL
) )
1603 #else // other platform
1606 wxLogSysError(_("Failed to modify file times for '%s'"),
1607 GetFullPath().c_str());
1612 bool wxFileName::Touch()
1614 #if defined(__UNIX_LIKE__)
1615 // under Unix touching file is simple: just pass NULL to utime()
1616 if ( utime(GetFullPath(), NULL
) == 0 )
1621 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1624 #else // other platform
1625 wxDateTime dtNow
= wxDateTime::Now();
1627 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1631 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1633 wxDateTime
*dtChange
) const
1635 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1637 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1640 dtAccess
->Set(stBuf
.st_atime
);
1642 dtMod
->Set(stBuf
.st_mtime
);
1644 dtChange
->Set(stBuf
.st_ctime
);
1648 #elif defined(__WIN32__)
1649 wxFileHandle
fh(GetFullPath());
1652 FILETIME ftAccess
, ftCreate
, ftWrite
;
1654 if ( ::GetFileTime(fh
,
1655 dtMod
? &ftCreate
: NULL
,
1656 dtAccess
? &ftAccess
: NULL
,
1657 dtChange
? &ftWrite
: NULL
) )
1660 ConvertFileTimeToWx(dtMod
, ftCreate
);
1662 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1664 ConvertFileTimeToWx(dtChange
, ftWrite
);
1669 #else // other platform
1672 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1673 GetFullPath().c_str());
1680 const short kMacExtensionMaxLength
= 16 ;
1683 char m_ext
[kMacExtensionMaxLength
] ;
1686 } MacDefaultExtensionRecord
;
1688 #include "wx/dynarray.h"
1689 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1690 #include "wx/arrimpl.cpp"
1691 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray
) ;
1693 MacDefaultExtensionArray gMacDefaultExtensions
;
1694 bool gMacDefaultExtensionsInited
= false ;
1696 static void MacEnsureDefaultExtensionsLoaded()
1698 if ( !gMacDefaultExtensionsInited
)
1700 // load the default extensions
1701 MacDefaultExtensionRecord defaults
[] =
1703 { "txt" , 'TEXT' , 'ttxt' } ,
1706 // we could load the pc exchange prefs here too
1708 for ( int i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1710 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1712 gMacDefaultExtensionsInited
= true ;
1715 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1719 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1720 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1721 wxCHECK( err
== noErr
, false ) ;
1723 fndrInfo
.fdType
= type
;
1724 fndrInfo
.fdCreator
= creator
;
1725 FSpSetFInfo( &spec
, &fndrInfo
) ;
1729 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1733 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1734 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1735 wxCHECK( err
== noErr
, false ) ;
1737 *type
= fndrInfo
.fdType
;
1738 *creator
= fndrInfo
.fdCreator
;
1742 bool wxFileName::MacSetDefaultTypeAndCreator()
1744 wxUint32 type
, creator
;
1745 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1748 return MacSetTypeAndCreator( type
, creator
) ;
1753 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1755 MacEnsureDefaultExtensionsLoaded() ;
1756 wxString extl
= ext
.Lower() ;
1757 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1759 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1761 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1762 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1769 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1771 MacEnsureDefaultExtensionsLoaded() ;
1772 MacDefaultExtensionRecord rec
;
1774 rec
.m_creator
= creator
;
1775 strncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1776 gMacDefaultExtensions
.Add( rec
) ;