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(int 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, wxPathFormat format
) const
1048 // Should add_seperator parameter be used?
1050 format
= GetFormat( format
);
1054 // the leading character
1055 if ( format
== wxPATH_MAC
&& m_relative
)
1057 fullpath
+= wxFILE_SEP_PATH_MAC
;
1059 else if ( format
== wxPATH_DOS
)
1062 fullpath
+= wxFILE_SEP_PATH_DOS
;
1064 else if ( format
== wxPATH_UNIX
)
1067 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1070 // then concatenate all the path components using the path separator
1071 size_t dirCount
= m_dirs
.GetCount();
1074 if ( format
== wxPATH_VMS
)
1076 fullpath
+= wxT('[');
1080 for ( size_t i
= 0; i
< dirCount
; i
++ )
1082 // TODO: What to do with ".." under VMS
1088 if (m_dirs
[i
] == wxT("."))
1090 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1091 fullpath
+= m_dirs
[i
];
1092 fullpath
+= wxT(':');
1097 fullpath
+= m_dirs
[i
];
1098 fullpath
+= wxT('\\');
1103 fullpath
+= m_dirs
[i
];
1104 fullpath
+= wxT('/');
1109 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1110 fullpath
+= m_dirs
[i
];
1111 if (i
== dirCount
-1)
1112 fullpath
+= wxT(']');
1114 fullpath
+= wxT('.');
1119 wxFAIL_MSG( wxT("error") );
1130 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1132 format
= GetFormat(format
);
1136 // first put the volume
1137 if ( !m_volume
.empty() )
1140 // Special Windows UNC paths hack, part 2: undo what we did in
1141 // SplitPath() and make an UNC path if we have a drive which is not a
1142 // single letter (hopefully the network shares can't be one letter only
1143 // although I didn't find any authoritative docs on this)
1144 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1146 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1148 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1150 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1156 // the leading character
1157 if ( format
== wxPATH_MAC
&& m_relative
)
1159 fullpath
+= wxFILE_SEP_PATH_MAC
;
1161 else if ( format
== wxPATH_DOS
)
1164 fullpath
+= wxFILE_SEP_PATH_DOS
;
1166 else if ( format
== wxPATH_UNIX
)
1169 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1172 // then concatenate all the path components using the path separator
1173 size_t dirCount
= m_dirs
.GetCount();
1176 if ( format
== wxPATH_VMS
)
1178 fullpath
+= wxT('[');
1182 for ( size_t i
= 0; i
< dirCount
; i
++ )
1184 // TODO: What to do with ".." under VMS
1190 if (m_dirs
[i
] == wxT("."))
1192 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1193 fullpath
+= m_dirs
[i
];
1194 fullpath
+= wxT(':');
1199 fullpath
+= m_dirs
[i
];
1200 fullpath
+= wxT('\\');
1205 fullpath
+= m_dirs
[i
];
1206 fullpath
+= wxT('/');
1211 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1212 fullpath
+= m_dirs
[i
];
1213 if (i
== dirCount
-1)
1214 fullpath
+= wxT(']');
1216 fullpath
+= wxT('.');
1221 wxFAIL_MSG( wxT("error") );
1227 // finally add the file name and extension
1228 fullpath
+= GetFullName();
1233 // Return the short form of the path (returns identity on non-Windows platforms)
1234 wxString
wxFileName::GetShortPath() const
1236 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1237 wxString
path(GetFullPath());
1239 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1243 ok
= ::GetShortPathName
1246 pathOut
.GetWriteBuf(sz
),
1249 pathOut
.UngetWriteBuf();
1256 return GetFullPath();
1260 // Return the long form of the path (returns identity on non-Windows platforms)
1261 wxString
wxFileName::GetLongPath() const
1264 path
= GetFullPath();
1266 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1267 bool success
= FALSE
;
1269 // VZ: this code was disabled, why?
1270 #if 0 // wxUSE_DYNAMIC_LOADER
1271 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1273 static bool s_triedToLoad
= FALSE
;
1275 if ( !s_triedToLoad
)
1277 s_triedToLoad
= TRUE
;
1278 wxDynamicLibrary
dllKernel(_T("kernel32"));
1279 if ( dllKernel
.IsLoaded() )
1281 // may succeed or fail depending on the Windows version
1282 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1284 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1286 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1289 if ( s_pfnGetLongPathName
)
1291 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1292 bool ok
= dwSize
> 0;
1296 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1300 ok
= (*s_pfnGetLongPathName
)
1303 pathOut
.GetWriteBuf(sz
),
1306 pathOut
.UngetWriteBuf();
1316 #endif // wxUSE_DYNAMIC_LOADER
1320 // The OS didn't support GetLongPathName, or some other error.
1321 // We need to call FindFirstFile on each component in turn.
1323 WIN32_FIND_DATA findFileData
;
1325 pathOut
= wxEmptyString
;
1327 wxArrayString dirs
= GetDirs();
1328 dirs
.Add(GetFullName());
1332 size_t count
= dirs
.GetCount();
1333 for ( size_t i
= 0; i
< count
; i
++ )
1335 // We're using pathOut to collect the long-name path, but using a
1336 // temporary for appending the last path component which may be
1338 tmpPath
= pathOut
+ dirs
[i
];
1340 if ( tmpPath
.empty() )
1343 if ( tmpPath
.Last() == wxT(':') )
1345 // Can't pass a drive and root dir to FindFirstFile,
1346 // so continue to next dir
1347 tmpPath
+= wxFILE_SEP_PATH
;
1352 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1353 if (hFind
== INVALID_HANDLE_VALUE
)
1355 // Error: return immediately with the original path
1359 pathOut
+= findFileData
.cFileName
;
1360 if ( (i
< (count
-1)) )
1361 pathOut
+= wxFILE_SEP_PATH
;
1368 #endif // Win32/!Win32
1373 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1375 if (format
== wxPATH_NATIVE
)
1377 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1378 format
= wxPATH_DOS
;
1379 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1380 format
= wxPATH_MAC
;
1381 #elif defined(__VMS)
1382 format
= wxPATH_VMS
;
1384 format
= wxPATH_UNIX
;
1390 // ----------------------------------------------------------------------------
1391 // path splitting function
1392 // ----------------------------------------------------------------------------
1395 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1396 wxString
*pstrVolume
,
1400 wxPathFormat format
)
1402 format
= GetFormat(format
);
1404 wxString fullpath
= fullpathWithVolume
;
1406 // under VMS the end of the path is ']', not the path separator used to
1407 // separate the components
1408 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1409 : GetPathSeparators(format
);
1411 // special Windows UNC paths hack: transform \\share\path into share:path
1412 if ( format
== wxPATH_DOS
)
1414 if ( fullpath
.length() >= 4 &&
1415 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1416 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1418 fullpath
.erase(0, 2);
1420 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1421 if ( posFirstSlash
!= wxString::npos
)
1423 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1425 // UNC paths are always absolute, right? (FIXME)
1426 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1431 // We separate the volume here
1432 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1434 wxString sepVol
= GetVolumeSeparator(format
);
1436 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1437 if ( posFirstColon
!= wxString::npos
)
1441 *pstrVolume
= fullpath
.Left(posFirstColon
);
1444 // remove the volume name and the separator from the full path
1445 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1449 // find the positions of the last dot and last path separator in the path
1450 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1451 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1453 if ( (posLastDot
!= wxString::npos
) &&
1454 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1456 if ( (posLastDot
== 0) ||
1457 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1459 // under Unix and VMS, dot may be (and commonly is) the first
1460 // character of the filename, don't treat the entire filename as
1461 // extension in this case
1462 posLastDot
= wxString::npos
;
1466 // if we do have a dot and a slash, check that the dot is in the name part
1467 if ( (posLastDot
!= wxString::npos
) &&
1468 (posLastSlash
!= wxString::npos
) &&
1469 (posLastDot
< posLastSlash
) )
1471 // the dot is part of the path, not the start of the extension
1472 posLastDot
= wxString::npos
;
1475 // now fill in the variables provided by user
1478 if ( posLastSlash
== wxString::npos
)
1485 // take everything up to the path separator but take care to make
1486 // the path equal to something like '/', not empty, for the files
1487 // immediately under root directory
1488 size_t len
= posLastSlash
;
1490 // this rule does not apply to mac since we do not start with colons (sep)
1491 // except for relative paths
1492 if ( !len
&& format
!= wxPATH_MAC
)
1495 *pstrPath
= fullpath
.Left(len
);
1497 // special VMS hack: remove the initial bracket
1498 if ( format
== wxPATH_VMS
)
1500 if ( (*pstrPath
)[0u] == _T('[') )
1501 pstrPath
->erase(0, 1);
1508 // take all characters starting from the one after the last slash and
1509 // up to, but excluding, the last dot
1510 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1512 if ( posLastDot
== wxString::npos
)
1514 // take all until the end
1515 count
= wxString::npos
;
1517 else if ( posLastSlash
== wxString::npos
)
1521 else // have both dot and slash
1523 count
= posLastDot
- posLastSlash
- 1;
1526 *pstrName
= fullpath
.Mid(nStart
, count
);
1531 if ( posLastDot
== wxString::npos
)
1538 // take everything after the dot
1539 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1545 void wxFileName::SplitPath(const wxString
& fullpath
,
1549 wxPathFormat format
)
1552 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1554 if ( path
&& !volume
.empty() )
1556 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1560 // ----------------------------------------------------------------------------
1562 // ----------------------------------------------------------------------------
1564 bool wxFileName::SetTimes(const wxDateTime
*dtCreate
,
1565 const wxDateTime
*dtAccess
,
1566 const wxDateTime
*dtMod
)
1568 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1569 if ( !dtAccess
&& !dtMod
)
1571 // can't modify the creation time anyhow, don't try
1575 // if dtAccess or dtMod is not specified, use the other one (which must be
1576 // non NULL because of the test above) for both times
1578 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1579 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1580 if ( utime(GetFullPath(), &utm
) == 0 )
1584 #elif defined(__WIN32__)
1585 wxFileHandle
fh(GetFullPath());
1588 FILETIME ftAccess
, ftCreate
, ftWrite
;
1591 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1593 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1595 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1597 if ( ::SetFileTime(fh
,
1598 dtCreate
? &ftCreate
: NULL
,
1599 dtAccess
? &ftAccess
: NULL
,
1600 dtMod
? &ftWrite
: NULL
) )
1605 #else // other platform
1608 wxLogSysError(_("Failed to modify file times for '%s'"),
1609 GetFullPath().c_str());
1614 bool wxFileName::Touch()
1616 #if defined(__UNIX_LIKE__)
1617 // under Unix touching file is simple: just pass NULL to utime()
1618 if ( utime(GetFullPath(), NULL
) == 0 )
1623 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1626 #else // other platform
1627 wxDateTime dtNow
= wxDateTime::Now();
1629 return SetTimes(NULL
/* don't change create time */, &dtNow
, &dtNow
);
1633 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1635 wxDateTime
*dtChange
) const
1637 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1639 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1642 dtAccess
->Set(stBuf
.st_atime
);
1644 dtMod
->Set(stBuf
.st_mtime
);
1646 dtChange
->Set(stBuf
.st_ctime
);
1650 #elif defined(__WIN32__)
1651 wxFileHandle
fh(GetFullPath());
1654 FILETIME ftAccess
, ftCreate
, ftWrite
;
1656 if ( ::GetFileTime(fh
,
1657 dtMod
? &ftCreate
: NULL
,
1658 dtAccess
? &ftAccess
: NULL
,
1659 dtChange
? &ftWrite
: NULL
) )
1662 ConvertFileTimeToWx(dtMod
, ftCreate
);
1664 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1666 ConvertFileTimeToWx(dtChange
, ftWrite
);
1671 #else // other platform
1674 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1675 GetFullPath().c_str());
1682 const short kMacExtensionMaxLength
= 16 ;
1685 char m_ext
[kMacExtensionMaxLength
] ;
1688 } MacDefaultExtensionRecord
;
1690 #include "wx/dynarray.h"
1691 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1692 #include "wx/arrimpl.cpp"
1693 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray
) ;
1695 MacDefaultExtensionArray gMacDefaultExtensions
;
1696 bool gMacDefaultExtensionsInited
= false ;
1698 static void MacEnsureDefaultExtensionsLoaded()
1700 if ( !gMacDefaultExtensionsInited
)
1702 // load the default extensions
1703 MacDefaultExtensionRecord defaults
[] =
1705 { "txt" , 'TEXT' , 'ttxt' } ,
1708 // we could load the pc exchange prefs here too
1710 for ( int i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1712 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1714 gMacDefaultExtensionsInited
= true ;
1717 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1721 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1722 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1723 wxCHECK( err
== noErr
, false ) ;
1725 fndrInfo
.fdType
= type
;
1726 fndrInfo
.fdCreator
= creator
;
1727 FSpSetFInfo( &spec
, &fndrInfo
) ;
1731 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1735 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1736 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1737 wxCHECK( err
== noErr
, false ) ;
1739 *type
= fndrInfo
.fdType
;
1740 *creator
= fndrInfo
.fdCreator
;
1744 bool wxFileName::MacSetDefaultTypeAndCreator()
1746 wxUint32 type
, creator
;
1747 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1750 return MacSetTypeAndCreator( type
, creator
) ;
1755 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1757 MacEnsureDefaultExtensionsLoaded() ;
1758 wxString extl
= ext
.Lower() ;
1759 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1761 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1763 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1764 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1771 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1773 MacEnsureDefaultExtensionsLoaded() ;
1774 MacDefaultExtensionRecord rec
;
1776 rec
.m_creator
= creator
;
1777 strncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1778 gMacDefaultExtensions
.Add( rec
) ;