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
.m_relative
;
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
)
277 wxPathFormat my_format
= GetFormat( format
);
278 wxString my_path
= path
;
280 // 1) Determine if the path is relative or absolute.
281 wxChar leadingChar
= my_path
[0u];
286 m_relative
= leadingChar
== wxT(':');
288 // We then remove a leading ":". The reason is in our
289 // storage form for relative paths:
290 // ":dir:file.txt" actually means "./dir/file.txt" in
291 // DOS notation and should get stored as
292 // (relative) (dir) (file.txt)
293 // "::dir:file.txt" actually means "../dir/file.txt"
294 // stored as (relative) (..) (dir) (file.txt)
295 // This is important only for the Mac as an empty dir
296 // actually means <UP>, whereas under DOS, double
297 // slashes can be ignored: "\\\\" is the same as "\\".
299 my_path
.erase( 0, 1 );
303 // TODO: what is the relative path format here?
308 // the paths of the form "~" or "~username" are absolute
309 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
313 m_relative
= !IsPathSeparator(leadingChar
, my_format
);
317 wxFAIL_MSG( wxT("error") );
321 // 2) Break up the path into its members. If the original path
322 // was just "/" or "\\", m_dirs will be empty. We know from
323 // the m_relative field, if this means "nothing" or "root dir".
325 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
327 while ( tn
.HasMoreTokens() )
329 wxString token
= tn
.GetNextToken();
331 // Remove empty token under DOS and Unix, interpret them
335 if (my_format
== wxPATH_MAC
)
336 m_dirs
.Add( wxT("..") );
345 else // no path at all
351 void wxFileName::Assign(const wxString
& fullpath
,
354 wxString volume
, path
, name
, ext
;
355 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
357 Assign(volume
, path
, name
, ext
, format
);
360 void wxFileName::Assign(const wxString
& fullpathOrig
,
361 const wxString
& fullname
,
364 // always recognize fullpath as directory, even if it doesn't end with a
366 wxString fullpath
= fullpathOrig
;
367 if ( !wxEndsWithPathSeparator(fullpath
) )
369 fullpath
+= GetPathSeparators(format
)[0u];
372 wxString volume
, path
, name
, ext
;
374 // do some consistency checks in debug mode: the name should be really just
375 // the filename and the path should be really just a path
377 wxString pathDummy
, nameDummy
, extDummy
;
379 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
381 wxASSERT_MSG( pathDummy
.empty(),
382 _T("the file name shouldn't contain the path") );
384 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
386 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
387 _T("the path shouldn't contain file name nor extension") );
389 #else // !__WXDEBUG__
390 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
391 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
392 #endif // __WXDEBUG__/!__WXDEBUG__
394 Assign(volume
, path
, name
, ext
, format
);
397 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
399 Assign(dir
, _T(""), format
);
402 void wxFileName::Clear()
408 m_ext
= wxEmptyString
;
412 wxFileName
wxFileName::FileName(const wxString
& file
)
414 return wxFileName(file
);
418 wxFileName
wxFileName::DirName(const wxString
& dir
)
425 // ----------------------------------------------------------------------------
427 // ----------------------------------------------------------------------------
429 bool wxFileName::FileExists()
431 return wxFileName::FileExists( GetFullPath() );
434 bool wxFileName::FileExists( const wxString
&file
)
436 return ::wxFileExists( file
);
439 bool wxFileName::DirExists()
441 return wxFileName::DirExists( GetFullPath() );
444 bool wxFileName::DirExists( const wxString
&dir
)
446 return ::wxDirExists( dir
);
449 // ----------------------------------------------------------------------------
450 // CWD and HOME stuff
451 // ----------------------------------------------------------------------------
453 void wxFileName::AssignCwd(const wxString
& volume
)
455 AssignDir(wxFileName::GetCwd(volume
));
459 wxString
wxFileName::GetCwd(const wxString
& volume
)
461 // if we have the volume, we must get the current directory on this drive
462 // and to do this we have to chdir to this volume - at least under Windows,
463 // I don't know how to get the current drive on another volume elsewhere
466 if ( !volume
.empty() )
469 SetCwd(volume
+ GetVolumeSeparator());
472 wxString cwd
= ::wxGetCwd();
474 if ( !volume
.empty() )
482 bool wxFileName::SetCwd()
484 return wxFileName::SetCwd( GetFullPath() );
487 bool wxFileName::SetCwd( const wxString
&cwd
)
489 return ::wxSetWorkingDirectory( cwd
);
492 void wxFileName::AssignHomeDir()
494 AssignDir(wxFileName::GetHomeDir());
497 wxString
wxFileName::GetHomeDir()
499 return ::wxGetHomeDir();
502 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
504 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
505 if ( tempname
.empty() )
507 // error, failed to get temp file name
518 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
520 wxString path
, dir
, name
;
522 // use the directory specified by the prefix
523 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
525 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
530 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
532 wxLogLastError(_T("GetTempPath"));
537 // GetTempFileName() fails if we pass it an empty string
541 else // we have a dir to create the file in
543 // ensure we use only the back slashes as GetTempFileName(), unlike all
544 // the other APIs, is picky and doesn't accept the forward ones
545 dir
.Replace(_T("/"), _T("\\"));
548 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
550 wxLogLastError(_T("GetTempFileName"));
555 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
561 #elif defined(__WXPM__)
562 // for now just create a file
564 // future enhancements can be to set some extended attributes for file
565 // systems OS/2 supports that have them (HPFS, FAT32) and security
567 static const wxChar
*szMktempSuffix
= wxT("XXX");
568 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
570 // Temporarily remove - MN
572 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
575 #else // !Windows, !OS/2
578 #if defined(__WXMAC__) && !defined(__DARWIN__)
579 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
581 dir
= wxGetenv(_T("TMP"));
584 dir
= wxGetenv(_T("TEMP"));
601 if ( !wxEndsWithPathSeparator(dir
) &&
602 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
604 path
+= wxFILE_SEP_PATH
;
609 #if defined(HAVE_MKSTEMP)
610 // scratch space for mkstemp()
611 path
+= _T("XXXXXX");
613 // can use the cast here because the length doesn't change and the string
615 int fdTemp
= mkstemp((char *)path
.mb_str());
618 // this might be not necessary as mkstemp() on most systems should have
619 // already done it but it doesn't hurt neither...
622 else // mkstemp() succeeded
624 // avoid leaking the fd
627 fileTemp
->Attach(fdTemp
);
634 #else // !HAVE_MKSTEMP
638 path
+= _T("XXXXXX");
640 if ( !mktemp((char *)path
.mb_str()) )
644 #else // !HAVE_MKTEMP (includes __DOS__)
645 // generate the unique file name ourselves
647 path
<< (unsigned int)getpid();
652 static const size_t numTries
= 1000;
653 for ( size_t n
= 0; n
< numTries
; n
++ )
655 // 3 hex digits is enough for numTries == 1000 < 4096
656 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
657 if ( !wxFile::Exists(pathTry
) )
666 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
671 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
673 #endif // Windows/!Windows
677 wxLogSysError(_("Failed to create a temporary file name"));
679 else if ( fileTemp
&& !fileTemp
->IsOpened() )
681 // open the file - of course, there is a race condition here, this is
682 // why we always prefer using mkstemp()...
684 // NB: GetTempFileName() under Windows creates the file, so using
685 // write_excl there would fail
686 if ( !fileTemp
->Open(path
,
687 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
692 wxS_IRUSR
| wxS_IWUSR
) )
694 // FIXME: If !ok here should we loop and try again with another
695 // file name? That is the standard recourse if open(O_EXCL)
696 // fails, though of course it should be protected against
697 // possible infinite looping too.
699 wxLogError(_("Failed to open temporary file."));
708 // ----------------------------------------------------------------------------
709 // directory operations
710 // ----------------------------------------------------------------------------
712 bool wxFileName::Mkdir( int perm
, bool full
)
714 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
717 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
721 wxFileName
filename(dir
);
722 wxArrayString dirs
= filename
.GetDirs();
723 dirs
.Add(filename
.GetName());
725 size_t count
= dirs
.GetCount();
729 for ( i
= 0; i
< count
; i
++ )
733 if (currPath
.Last() == wxT(':'))
735 // Can't create a root directory so continue to next dir
736 currPath
+= wxFILE_SEP_PATH
;
740 if (!DirExists(currPath
))
741 if (!wxMkdir(currPath
, perm
))
744 if ( (i
< (count
-1)) )
745 currPath
+= wxFILE_SEP_PATH
;
748 return (noErrors
== 0);
752 return ::wxMkdir( dir
, perm
);
755 bool wxFileName::Rmdir()
757 return wxFileName::Rmdir( GetFullPath() );
760 bool wxFileName::Rmdir( const wxString
&dir
)
762 return ::wxRmdir( dir
);
765 // ----------------------------------------------------------------------------
766 // path normalization
767 // ----------------------------------------------------------------------------
769 bool wxFileName::Normalize(int flags
,
773 // the existing path components
774 wxArrayString dirs
= GetDirs();
776 // the path to prepend in front to make the path absolute
779 format
= GetFormat(format
);
781 // make the path absolute
782 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
786 curDir
.AssignCwd(GetVolume());
790 curDir
.AssignDir(cwd
);
793 // the path may be not absolute because it doesn't have the volume name
794 // but in this case we shouldn't modify the directory components of it
795 // but just set the current volume
796 if ( !HasVolume() && curDir
.HasVolume() )
798 SetVolume(curDir
.GetVolume());
802 // yes, it was the case - we don't need curDir then
808 // handle ~ stuff under Unix only
809 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
811 if ( !dirs
.IsEmpty() )
813 wxString dir
= dirs
[0u];
814 if ( !dir
.empty() && dir
[0u] == _T('~') )
816 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
823 // transform relative path into abs one
826 wxArrayString dirsNew
= curDir
.GetDirs();
827 size_t count
= dirs
.GetCount();
828 for ( size_t n
= 0; n
< count
; n
++ )
830 dirsNew
.Add(dirs
[n
]);
836 // now deal with ".", ".." and the rest
838 size_t count
= dirs
.GetCount();
839 for ( size_t n
= 0; n
< count
; n
++ )
841 wxString dir
= dirs
[n
];
843 if ( flags
& wxPATH_NORM_DOTS
)
845 if ( dir
== wxT(".") )
851 if ( dir
== wxT("..") )
853 if ( m_dirs
.IsEmpty() )
855 wxLogError(_("The path '%s' contains too many \"..\"!"),
856 GetFullPath().c_str());
860 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
865 if ( flags
& wxPATH_NORM_ENV_VARS
)
867 dir
= wxExpandEnvVars(dir
);
870 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
878 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
880 // VZ: expand env vars here too?
886 #if defined(__WIN32__)
887 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
889 Assign(GetLongPath());
893 // we do have the path now
899 // ----------------------------------------------------------------------------
900 // absolute/relative paths
901 // ----------------------------------------------------------------------------
903 bool wxFileName::IsAbsolute(wxPathFormat format
) const
905 // if our path doesn't start with a path separator, it's not an absolute
910 if ( !GetVolumeSeparator(format
).empty() )
912 // this format has volumes and an absolute path must have one, it's not
913 // enough to have the full path to bean absolute file under Windows
914 if ( GetVolume().empty() )
921 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
923 wxFileName
fnBase(pathBase
, format
);
925 // get cwd only once - small time saving
926 wxString cwd
= wxGetCwd();
927 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
928 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
930 bool withCase
= IsCaseSensitive(format
);
932 // we can't do anything if the files live on different volumes
933 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
939 // same drive, so we don't need our volume
942 // remove common directories starting at the top
943 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
944 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
947 fnBase
.m_dirs
.RemoveAt(0);
950 // add as many ".." as needed
951 size_t count
= fnBase
.m_dirs
.GetCount();
952 for ( size_t i
= 0; i
< count
; i
++ )
954 m_dirs
.Insert(wxT(".."), 0u);
963 // ----------------------------------------------------------------------------
964 // filename kind tests
965 // ----------------------------------------------------------------------------
967 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
969 wxFileName fn1
= *this,
972 // get cwd only once - small time saving
973 wxString cwd
= wxGetCwd();
974 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
975 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
977 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
980 // TODO: compare inodes for Unix, this works even when filenames are
981 // different but files are the same (symlinks) (VZ)
987 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
989 // only Unix filenames are truely case-sensitive
990 return GetFormat(format
) == wxPATH_UNIX
;
994 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
998 if ( (GetFormat(format
) == wxPATH_DOS
) ||
999 (GetFormat(format
) == wxPATH_VMS
) )
1001 sepVol
= wxFILE_SEP_DSK
;
1009 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1012 switch ( GetFormat(format
) )
1015 // accept both as native APIs do but put the native one first as
1016 // this is the one we use in GetFullPath()
1017 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1021 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
1025 seps
= wxFILE_SEP_PATH_UNIX
;
1029 seps
= wxFILE_SEP_PATH_MAC
;
1033 seps
= wxFILE_SEP_PATH_VMS
;
1041 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1043 // wxString::Find() doesn't work as expected with NUL - it will always find
1044 // it, so it is almost surely a bug if this function is called with NUL arg
1045 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1047 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1050 bool wxFileName::IsWild( wxPathFormat
WXUNUSED(format
) )
1052 // FIXME: this is probably false for Mac and this is surely wrong for most
1053 // of Unix shells (think about "[...]")
1054 return m_name
.find_first_of(_T("*?")) != wxString::npos
;
1057 // ----------------------------------------------------------------------------
1058 // path components manipulation
1059 // ----------------------------------------------------------------------------
1061 void wxFileName::AppendDir( const wxString
&dir
)
1066 void wxFileName::PrependDir( const wxString
&dir
)
1068 m_dirs
.Insert( dir
, 0 );
1071 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1073 m_dirs
.Insert( dir
, before
);
1076 void wxFileName::RemoveDir( int pos
)
1078 m_dirs
.Remove( (size_t)pos
);
1081 // ----------------------------------------------------------------------------
1083 // ----------------------------------------------------------------------------
1085 void wxFileName::SetFullName(const wxString
& fullname
)
1087 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1090 wxString
wxFileName::GetFullName() const
1092 wxString fullname
= m_name
;
1093 if ( !m_ext
.empty() )
1095 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1101 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1103 format
= GetFormat( format
);
1107 // the leading character
1108 if ( format
== wxPATH_MAC
&& m_relative
)
1110 fullpath
+= wxFILE_SEP_PATH_MAC
;
1112 else if ( format
== wxPATH_DOS
)
1115 fullpath
+= wxFILE_SEP_PATH_DOS
;
1117 else if ( format
== wxPATH_UNIX
)
1120 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1123 // then concatenate all the path components using the path separator
1124 size_t dirCount
= m_dirs
.GetCount();
1127 if ( format
== wxPATH_VMS
)
1129 fullpath
+= wxT('[');
1133 for ( size_t i
= 0; i
< dirCount
; i
++ )
1135 // TODO: What to do with ".." under VMS
1141 if (m_dirs
[i
] == wxT("."))
1143 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1144 fullpath
+= m_dirs
[i
];
1145 fullpath
+= wxT(':');
1150 fullpath
+= m_dirs
[i
];
1151 fullpath
+= wxT('\\');
1156 fullpath
+= m_dirs
[i
];
1157 fullpath
+= wxT('/');
1162 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1163 fullpath
+= m_dirs
[i
];
1164 if (i
== dirCount
-1)
1165 fullpath
+= wxT(']');
1167 fullpath
+= wxT('.');
1172 wxFAIL_MSG( wxT("error") );
1178 if ( add_separator
&& !fullpath
.empty() )
1180 fullpath
+= GetPathSeparators(format
)[0u];
1186 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1188 format
= GetFormat(format
);
1192 // first put the volume
1193 if ( !m_volume
.empty() )
1196 // Special Windows UNC paths hack, part 2: undo what we did in
1197 // SplitPath() and make an UNC path if we have a drive which is not a
1198 // single letter (hopefully the network shares can't be one letter only
1199 // although I didn't find any authoritative docs on this)
1200 if ( format
== wxPATH_DOS
&& m_volume
.length() > 1 )
1202 fullpath
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< m_volume
;
1204 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1206 fullpath
<< m_volume
<< GetVolumeSeparator(format
);
1212 // the leading character
1213 if ( format
== wxPATH_MAC
)
1216 fullpath
+= wxFILE_SEP_PATH_MAC
;
1218 else if ( format
== wxPATH_DOS
)
1221 fullpath
+= wxFILE_SEP_PATH_DOS
;
1223 else if ( format
== wxPATH_UNIX
)
1227 // normally the absolute file names starts with a slash with one
1228 // exception: file names like "~/foo.bar" don't have it
1229 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1231 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1236 // then concatenate all the path components using the path separator
1237 size_t dirCount
= m_dirs
.GetCount();
1240 if ( format
== wxPATH_VMS
)
1242 fullpath
+= wxT('[');
1246 for ( size_t i
= 0; i
< dirCount
; i
++ )
1248 // TODO: What to do with ".." under VMS
1254 if (m_dirs
[i
] == wxT("."))
1256 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1257 fullpath
+= m_dirs
[i
];
1258 fullpath
+= wxT(':');
1263 fullpath
+= m_dirs
[i
];
1264 fullpath
+= wxT('\\');
1269 fullpath
+= m_dirs
[i
];
1270 fullpath
+= wxT('/');
1275 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1276 fullpath
+= m_dirs
[i
];
1277 if (i
== dirCount
-1)
1278 fullpath
+= wxT(']');
1280 fullpath
+= wxT('.');
1285 wxFAIL_MSG( wxT("error") );
1291 // finally add the file name and extension
1292 fullpath
+= GetFullName();
1297 // Return the short form of the path (returns identity on non-Windows platforms)
1298 wxString
wxFileName::GetShortPath() const
1300 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1301 wxString
path(GetFullPath());
1303 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1307 ok
= ::GetShortPathName
1310 pathOut
.GetWriteBuf(sz
),
1313 pathOut
.UngetWriteBuf();
1320 return GetFullPath();
1324 // Return the long form of the path (returns identity on non-Windows platforms)
1325 wxString
wxFileName::GetLongPath() const
1328 path
= GetFullPath();
1330 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1331 bool success
= FALSE
;
1333 // VZ: why was this code disabled?
1334 #if 0 // wxUSE_DYNAMIC_LOADER
1335 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1337 static bool s_triedToLoad
= FALSE
;
1339 if ( !s_triedToLoad
)
1341 s_triedToLoad
= TRUE
;
1342 wxDynamicLibrary
dllKernel(_T("kernel32"));
1343 if ( dllKernel
.IsLoaded() )
1345 // may succeed or fail depending on the Windows version
1346 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1348 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1350 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1353 if ( s_pfnGetLongPathName
)
1355 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1356 bool ok
= dwSize
> 0;
1360 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1364 ok
= (*s_pfnGetLongPathName
)
1367 pathOut
.GetWriteBuf(sz
),
1370 pathOut
.UngetWriteBuf();
1380 #endif // wxUSE_DYNAMIC_LOADER
1384 // The OS didn't support GetLongPathName, or some other error.
1385 // We need to call FindFirstFile on each component in turn.
1387 WIN32_FIND_DATA findFileData
;
1389 pathOut
= wxEmptyString
;
1391 wxArrayString dirs
= GetDirs();
1392 dirs
.Add(GetFullName());
1396 size_t count
= dirs
.GetCount();
1397 for ( size_t i
= 0; i
< count
; i
++ )
1399 // We're using pathOut to collect the long-name path, but using a
1400 // temporary for appending the last path component which may be
1402 tmpPath
= pathOut
+ dirs
[i
];
1404 if ( tmpPath
.empty() )
1407 if ( tmpPath
.Last() == wxT(':') )
1409 // Can't pass a drive and root dir to FindFirstFile,
1410 // so continue to next dir
1411 tmpPath
+= wxFILE_SEP_PATH
;
1416 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1417 if (hFind
== INVALID_HANDLE_VALUE
)
1419 // Error: return immediately with the original path
1423 pathOut
+= findFileData
.cFileName
;
1424 if ( (i
< (count
-1)) )
1425 pathOut
+= wxFILE_SEP_PATH
;
1432 #endif // Win32/!Win32
1437 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1439 if (format
== wxPATH_NATIVE
)
1441 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1442 format
= wxPATH_DOS
;
1443 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1444 format
= wxPATH_MAC
;
1445 #elif defined(__VMS)
1446 format
= wxPATH_VMS
;
1448 format
= wxPATH_UNIX
;
1454 // ----------------------------------------------------------------------------
1455 // path splitting function
1456 // ----------------------------------------------------------------------------
1459 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1460 wxString
*pstrVolume
,
1464 wxPathFormat format
)
1466 format
= GetFormat(format
);
1468 wxString fullpath
= fullpathWithVolume
;
1470 // under VMS the end of the path is ']', not the path separator used to
1471 // separate the components
1472 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1473 : GetPathSeparators(format
);
1475 // special Windows UNC paths hack: transform \\share\path into share:path
1476 if ( format
== wxPATH_DOS
)
1478 if ( fullpath
.length() >= 4 &&
1479 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1480 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1482 fullpath
.erase(0, 2);
1484 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1485 if ( posFirstSlash
!= wxString::npos
)
1487 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1489 // UNC paths are always absolute, right? (FIXME)
1490 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1495 // We separate the volume here
1496 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1498 wxString sepVol
= GetVolumeSeparator(format
);
1500 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1501 if ( posFirstColon
!= wxString::npos
)
1505 *pstrVolume
= fullpath
.Left(posFirstColon
);
1508 // remove the volume name and the separator from the full path
1509 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1513 // find the positions of the last dot and last path separator in the path
1514 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1515 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1517 if ( (posLastDot
!= wxString::npos
) &&
1518 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1520 if ( (posLastDot
== 0) ||
1521 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1523 // under Unix and VMS, dot may be (and commonly is) the first
1524 // character of the filename, don't treat the entire filename as
1525 // extension in this case
1526 posLastDot
= wxString::npos
;
1530 // if we do have a dot and a slash, check that the dot is in the name part
1531 if ( (posLastDot
!= wxString::npos
) &&
1532 (posLastSlash
!= wxString::npos
) &&
1533 (posLastDot
< posLastSlash
) )
1535 // the dot is part of the path, not the start of the extension
1536 posLastDot
= wxString::npos
;
1539 // now fill in the variables provided by user
1542 if ( posLastSlash
== wxString::npos
)
1549 // take everything up to the path separator but take care to make
1550 // the path equal to something like '/', not empty, for the files
1551 // immediately under root directory
1552 size_t len
= posLastSlash
;
1554 // this rule does not apply to mac since we do not start with colons (sep)
1555 // except for relative paths
1556 if ( !len
&& format
!= wxPATH_MAC
)
1559 *pstrPath
= fullpath
.Left(len
);
1561 // special VMS hack: remove the initial bracket
1562 if ( format
== wxPATH_VMS
)
1564 if ( (*pstrPath
)[0u] == _T('[') )
1565 pstrPath
->erase(0, 1);
1572 // take all characters starting from the one after the last slash and
1573 // up to, but excluding, the last dot
1574 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1576 if ( posLastDot
== wxString::npos
)
1578 // take all until the end
1579 count
= wxString::npos
;
1581 else if ( posLastSlash
== wxString::npos
)
1585 else // have both dot and slash
1587 count
= posLastDot
- posLastSlash
- 1;
1590 *pstrName
= fullpath
.Mid(nStart
, count
);
1595 if ( posLastDot
== wxString::npos
)
1602 // take everything after the dot
1603 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1609 void wxFileName::SplitPath(const wxString
& fullpath
,
1613 wxPathFormat format
)
1616 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1618 if ( path
&& !volume
.empty() )
1620 path
->Prepend(volume
+ GetVolumeSeparator(format
));
1624 // ----------------------------------------------------------------------------
1626 // ----------------------------------------------------------------------------
1628 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1629 const wxDateTime
*dtMod
,
1630 const wxDateTime
*dtCreate
)
1632 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1633 if ( !dtAccess
&& !dtMod
)
1635 // can't modify the creation time anyhow, don't try
1639 // if dtAccess or dtMod is not specified, use the other one (which must be
1640 // non NULL because of the test above) for both times
1642 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1643 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1644 if ( utime(GetFullPath(), &utm
) == 0 )
1648 #elif defined(__WIN32__)
1649 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1652 FILETIME ftAccess
, ftCreate
, ftWrite
;
1655 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1657 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1659 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1661 if ( ::SetFileTime(fh
,
1662 dtCreate
? &ftCreate
: NULL
,
1663 dtAccess
? &ftAccess
: NULL
,
1664 dtMod
? &ftWrite
: NULL
) )
1669 #else // other platform
1672 wxLogSysError(_("Failed to modify file times for '%s'"),
1673 GetFullPath().c_str());
1678 bool wxFileName::Touch()
1680 #if defined(__UNIX_LIKE__)
1681 // under Unix touching file is simple: just pass NULL to utime()
1682 if ( utime(GetFullPath(), NULL
) == 0 )
1687 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1690 #else // other platform
1691 wxDateTime dtNow
= wxDateTime::Now();
1693 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1697 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1699 wxDateTime
*dtCreate
) const
1701 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1703 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1706 dtAccess
->Set(stBuf
.st_atime
);
1708 dtMod
->Set(stBuf
.st_mtime
);
1710 dtCreate
->Set(stBuf
.st_ctime
);
1714 #elif defined(__WIN32__)
1715 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1718 FILETIME ftAccess
, ftCreate
, ftWrite
;
1720 if ( ::GetFileTime(fh
,
1721 dtMod
? &ftCreate
: NULL
,
1722 dtAccess
? &ftAccess
: NULL
,
1723 dtCreate
? &ftWrite
: NULL
) )
1726 ConvertFileTimeToWx(dtMod
, ftCreate
);
1728 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1730 ConvertFileTimeToWx(dtCreate
, ftWrite
);
1735 #else // other platform
1738 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1739 GetFullPath().c_str());
1746 const short kMacExtensionMaxLength
= 16 ;
1749 char m_ext
[kMacExtensionMaxLength
] ;
1752 } MacDefaultExtensionRecord
;
1754 #include "wx/dynarray.h"
1755 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1756 #include "wx/arrimpl.cpp"
1757 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray
) ;
1759 MacDefaultExtensionArray gMacDefaultExtensions
;
1760 bool gMacDefaultExtensionsInited
= false ;
1762 static void MacEnsureDefaultExtensionsLoaded()
1764 if ( !gMacDefaultExtensionsInited
)
1766 // load the default extensions
1767 MacDefaultExtensionRecord defaults
[] =
1769 { "txt" , 'TEXT' , 'ttxt' } ,
1772 // we could load the pc exchange prefs here too
1774 for ( int i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1776 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1778 gMacDefaultExtensionsInited
= true ;
1781 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1785 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1786 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1787 wxCHECK( err
== noErr
, false ) ;
1789 fndrInfo
.fdType
= type
;
1790 fndrInfo
.fdCreator
= creator
;
1791 FSpSetFInfo( &spec
, &fndrInfo
) ;
1795 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1799 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1800 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1801 wxCHECK( err
== noErr
, false ) ;
1803 *type
= fndrInfo
.fdType
;
1804 *creator
= fndrInfo
.fdCreator
;
1808 bool wxFileName::MacSetDefaultTypeAndCreator()
1810 wxUint32 type
, creator
;
1811 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1814 return MacSetTypeAndCreator( type
, creator
) ;
1819 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1821 MacEnsureDefaultExtensionsLoaded() ;
1822 wxString extl
= ext
.Lower() ;
1823 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1825 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1827 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1828 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1835 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1837 MacEnsureDefaultExtensionsLoaded() ;
1838 MacDefaultExtensionRecord rec
;
1840 rec
.m_creator
= creator
;
1841 strncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1842 gMacDefaultExtensions
.Add( rec
) ;