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"
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
)
200 FILETIME ftcopy
= ft
;
202 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
204 wxLogLastError(_T("FileTimeToLocalFileTime"));
208 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
210 wxLogLastError(_T("FileTimeToSystemTime"));
213 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
214 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
217 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
220 st
.wDay
= dt
.GetDay();
221 st
.wMonth
= dt
.GetMonth() + 1;
222 st
.wYear
= dt
.GetYear();
223 st
.wHour
= dt
.GetHour();
224 st
.wMinute
= dt
.GetMinute();
225 st
.wSecond
= dt
.GetSecond();
226 st
.wMilliseconds
= dt
.GetMillisecond();
229 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
231 wxLogLastError(_T("SystemTimeToFileTime"));
234 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
236 wxLogLastError(_T("LocalFileTimeToFileTime"));
242 // return a string with the volume par
243 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
247 if ( !volume
.empty() )
249 format
= wxFileName::GetFormat(format
);
251 // Special Windows UNC paths hack, part 2: undo what we did in
252 // SplitPath() and make an UNC path if we have a drive which is not a
253 // single letter (hopefully the network shares can't be one letter only
254 // although I didn't find any authoritative docs on this)
255 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
257 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
259 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
261 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
269 // ============================================================================
271 // ============================================================================
273 // ----------------------------------------------------------------------------
274 // wxFileName construction
275 // ----------------------------------------------------------------------------
277 void wxFileName::Assign( const wxFileName
&filepath
)
279 m_volume
= filepath
.GetVolume();
280 m_dirs
= filepath
.GetDirs();
281 m_name
= filepath
.GetName();
282 m_ext
= filepath
.GetExt();
283 m_relative
= filepath
.m_relative
;
286 void wxFileName::Assign(const wxString
& volume
,
287 const wxString
& path
,
288 const wxString
& name
,
290 wxPathFormat format
)
292 SetPath( path
, format
);
299 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
305 wxPathFormat my_format
= GetFormat( format
);
306 wxString my_path
= path
;
308 // 1) Determine if the path is relative or absolute.
309 wxChar leadingChar
= my_path
[0u];
314 m_relative
= leadingChar
== wxT(':');
316 // We then remove a leading ":". The reason is in our
317 // storage form for relative paths:
318 // ":dir:file.txt" actually means "./dir/file.txt" in
319 // DOS notation and should get stored as
320 // (relative) (dir) (file.txt)
321 // "::dir:file.txt" actually means "../dir/file.txt"
322 // stored as (relative) (..) (dir) (file.txt)
323 // This is important only for the Mac as an empty dir
324 // actually means <UP>, whereas under DOS, double
325 // slashes can be ignored: "\\\\" is the same as "\\".
327 my_path
.erase( 0, 1 );
331 // TODO: what is the relative path format here?
336 // the paths of the form "~" or "~username" are absolute
337 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
341 m_relative
= !IsPathSeparator(leadingChar
, my_format
);
345 wxFAIL_MSG( wxT("error") );
349 // 2) Break up the path into its members. If the original path
350 // was just "/" or "\\", m_dirs will be empty. We know from
351 // the m_relative field, if this means "nothing" or "root dir".
353 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
355 while ( tn
.HasMoreTokens() )
357 wxString token
= tn
.GetNextToken();
359 // Remove empty token under DOS and Unix, interpret them
363 if (my_format
== wxPATH_MAC
)
364 m_dirs
.Add( wxT("..") );
373 else // no path at all
379 void wxFileName::Assign(const wxString
& fullpath
,
382 wxString volume
, path
, name
, ext
;
383 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
385 Assign(volume
, path
, name
, ext
, format
);
388 void wxFileName::Assign(const wxString
& fullpathOrig
,
389 const wxString
& fullname
,
392 // always recognize fullpath as directory, even if it doesn't end with a
394 wxString fullpath
= fullpathOrig
;
395 if ( !wxEndsWithPathSeparator(fullpath
) )
397 fullpath
+= GetPathSeparator(format
);
400 wxString volume
, path
, name
, ext
;
402 // do some consistency checks in debug mode: the name should be really just
403 // the filename and the path should be really just a path
405 wxString pathDummy
, nameDummy
, extDummy
;
407 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
409 wxASSERT_MSG( pathDummy
.empty(),
410 _T("the file name shouldn't contain the path") );
412 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
414 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
415 _T("the path shouldn't contain file name nor extension") );
417 #else // !__WXDEBUG__
418 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
419 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
420 #endif // __WXDEBUG__/!__WXDEBUG__
422 Assign(volume
, path
, name
, ext
, format
);
425 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
427 Assign(dir
, _T(""), format
);
430 void wxFileName::Clear()
436 m_ext
= wxEmptyString
;
438 // we don't have any absolute path for now
443 wxFileName
wxFileName::FileName(const wxString
& file
)
445 return wxFileName(file
);
449 wxFileName
wxFileName::DirName(const wxString
& dir
)
456 // ----------------------------------------------------------------------------
458 // ----------------------------------------------------------------------------
460 bool wxFileName::FileExists()
462 return wxFileName::FileExists( GetFullPath() );
465 bool wxFileName::FileExists( const wxString
&file
)
467 return ::wxFileExists( file
);
470 bool wxFileName::DirExists()
472 return wxFileName::DirExists( GetFullPath() );
475 bool wxFileName::DirExists( const wxString
&dir
)
477 return ::wxDirExists( dir
);
480 // ----------------------------------------------------------------------------
481 // CWD and HOME stuff
482 // ----------------------------------------------------------------------------
484 void wxFileName::AssignCwd(const wxString
& volume
)
486 AssignDir(wxFileName::GetCwd(volume
));
490 wxString
wxFileName::GetCwd(const wxString
& volume
)
492 // if we have the volume, we must get the current directory on this drive
493 // and to do this we have to chdir to this volume - at least under Windows,
494 // I don't know how to get the current drive on another volume elsewhere
497 if ( !volume
.empty() )
500 SetCwd(volume
+ GetVolumeSeparator());
503 wxString cwd
= ::wxGetCwd();
505 if ( !volume
.empty() )
513 bool wxFileName::SetCwd()
515 return wxFileName::SetCwd( GetFullPath() );
518 bool wxFileName::SetCwd( const wxString
&cwd
)
520 return ::wxSetWorkingDirectory( cwd
);
523 void wxFileName::AssignHomeDir()
525 AssignDir(wxFileName::GetHomeDir());
528 wxString
wxFileName::GetHomeDir()
530 return ::wxGetHomeDir();
533 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
535 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
536 if ( tempname
.empty() )
538 // error, failed to get temp file name
549 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
551 wxString path
, dir
, name
;
553 // use the directory specified by the prefix
554 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
556 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
561 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
563 wxLogLastError(_T("GetTempPath"));
568 // GetTempFileName() fails if we pass it an empty string
572 else // we have a dir to create the file in
574 // ensure we use only the back slashes as GetTempFileName(), unlike all
575 // the other APIs, is picky and doesn't accept the forward ones
576 dir
.Replace(_T("/"), _T("\\"));
579 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
581 wxLogLastError(_T("GetTempFileName"));
586 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
592 #elif defined(__WXPM__)
593 // for now just create a file
595 // future enhancements can be to set some extended attributes for file
596 // systems OS/2 supports that have them (HPFS, FAT32) and security
598 static const wxChar
*szMktempSuffix
= wxT("XXX");
599 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
601 // Temporarily remove - MN
603 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
606 #else // !Windows, !OS/2
609 #if defined(__WXMAC__) && !defined(__DARWIN__)
610 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
612 dir
= wxGetenv(_T("TMP"));
615 dir
= wxGetenv(_T("TEMP"));
632 if ( !wxEndsWithPathSeparator(dir
) &&
633 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
635 path
+= wxFILE_SEP_PATH
;
640 #if defined(HAVE_MKSTEMP)
641 // scratch space for mkstemp()
642 path
+= _T("XXXXXX");
644 // we need to copy the path to the buffer in which mkstemp() can modify it
645 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
647 // cast is safe because the string length doesn't change
648 int fdTemp
= mkstemp( (char*)(const char*) buf
);
651 // this might be not necessary as mkstemp() on most systems should have
652 // already done it but it doesn't hurt neither...
655 else // mkstemp() succeeded
657 path
= wxConvFile
.cMB2WX( (const char*) buf
);
659 // avoid leaking the fd
662 fileTemp
->Attach(fdTemp
);
669 #else // !HAVE_MKSTEMP
673 path
+= _T("XXXXXX");
675 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
676 if ( !mktemp( (const char*) buf
) )
682 path
= wxConvFile
.cMB2WX( (const char*) buf
);
684 #else // !HAVE_MKTEMP (includes __DOS__)
685 // generate the unique file name ourselves
687 path
<< (unsigned int)getpid();
692 static const size_t numTries
= 1000;
693 for ( size_t n
= 0; n
< numTries
; n
++ )
695 // 3 hex digits is enough for numTries == 1000 < 4096
696 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
697 if ( !wxFile::Exists(pathTry
) )
706 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
711 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
713 #endif // Windows/!Windows
717 wxLogSysError(_("Failed to create a temporary file name"));
719 else if ( fileTemp
&& !fileTemp
->IsOpened() )
721 // open the file - of course, there is a race condition here, this is
722 // why we always prefer using mkstemp()...
724 // NB: GetTempFileName() under Windows creates the file, so using
725 // write_excl there would fail
726 if ( !fileTemp
->Open(path
,
727 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
732 wxS_IRUSR
| wxS_IWUSR
) )
734 // FIXME: If !ok here should we loop and try again with another
735 // file name? That is the standard recourse if open(O_EXCL)
736 // fails, though of course it should be protected against
737 // possible infinite looping too.
739 wxLogError(_("Failed to open temporary file."));
748 // ----------------------------------------------------------------------------
749 // directory operations
750 // ----------------------------------------------------------------------------
752 bool wxFileName::Mkdir( int perm
, int flags
)
754 return wxFileName::Mkdir( GetFullPath(), perm
, flags
);
757 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
759 if ( flags
& wxPATH_MKDIR_FULL
)
761 // split the path in components
763 filename
.AssignDir(dir
);
766 if ( filename
.HasVolume())
768 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
771 wxArrayString dirs
= filename
.GetDirs();
772 size_t count
= dirs
.GetCount();
773 for ( size_t i
= 0; i
< count
; i
++ )
775 if ( i
> 0 || filename
.IsAbsolute() )
776 currPath
+= wxFILE_SEP_PATH
;
779 if (!DirExists(currPath
))
781 if (!wxMkdir(currPath
, perm
))
783 // no need to try creating further directories
793 return ::wxMkdir( dir
, perm
);
796 bool wxFileName::Rmdir()
798 return wxFileName::Rmdir( GetFullPath() );
801 bool wxFileName::Rmdir( const wxString
&dir
)
803 return ::wxRmdir( dir
);
806 // ----------------------------------------------------------------------------
807 // path normalization
808 // ----------------------------------------------------------------------------
810 bool wxFileName::Normalize(int flags
,
814 // the existing path components
815 wxArrayString dirs
= GetDirs();
817 // the path to prepend in front to make the path absolute
820 format
= GetFormat(format
);
822 // make the path absolute
823 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
827 curDir
.AssignCwd(GetVolume());
831 curDir
.AssignDir(cwd
);
834 // the path may be not absolute because it doesn't have the volume name
835 // but in this case we shouldn't modify the directory components of it
836 // but just set the current volume
837 if ( !HasVolume() && curDir
.HasVolume() )
839 SetVolume(curDir
.GetVolume());
843 // yes, it was the case - we don't need curDir then
849 // handle ~ stuff under Unix only
850 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
852 if ( !dirs
.IsEmpty() )
854 wxString dir
= dirs
[0u];
855 if ( !dir
.empty() && dir
[0u] == _T('~') )
857 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
864 // transform relative path into abs one
867 wxArrayString dirsNew
= curDir
.GetDirs();
868 size_t count
= dirs
.GetCount();
869 for ( size_t n
= 0; n
< count
; n
++ )
871 dirsNew
.Add(dirs
[n
]);
877 // now deal with ".", ".." and the rest
879 size_t count
= dirs
.GetCount();
880 for ( size_t n
= 0; n
< count
; n
++ )
882 wxString dir
= dirs
[n
];
884 if ( flags
& wxPATH_NORM_DOTS
)
886 if ( dir
== wxT(".") )
892 if ( dir
== wxT("..") )
894 if ( m_dirs
.IsEmpty() )
896 wxLogError(_("The path '%s' contains too many \"..\"!"),
897 GetFullPath().c_str());
901 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
906 if ( flags
& wxPATH_NORM_ENV_VARS
)
908 dir
= wxExpandEnvVars(dir
);
911 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
919 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
921 // VZ: expand env vars here too?
927 // we do have the path now
929 // NB: need to do this before (maybe) calling Assign() below
932 #if defined(__WIN32__)
933 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
935 Assign(GetLongPath());
942 // ----------------------------------------------------------------------------
943 // absolute/relative paths
944 // ----------------------------------------------------------------------------
946 bool wxFileName::IsAbsolute(wxPathFormat format
) const
948 // if our path doesn't start with a path separator, it's not an absolute
953 if ( !GetVolumeSeparator(format
).empty() )
955 // this format has volumes and an absolute path must have one, it's not
956 // enough to have the full path to bean absolute file under Windows
957 if ( GetVolume().empty() )
964 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
966 wxFileName
fnBase(pathBase
, format
);
968 // get cwd only once - small time saving
969 wxString cwd
= wxGetCwd();
970 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
971 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
973 bool withCase
= IsCaseSensitive(format
);
975 // we can't do anything if the files live on different volumes
976 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
982 // same drive, so we don't need our volume
985 // remove common directories starting at the top
986 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
987 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
990 fnBase
.m_dirs
.RemoveAt(0);
993 // add as many ".." as needed
994 size_t count
= fnBase
.m_dirs
.GetCount();
995 for ( size_t i
= 0; i
< count
; i
++ )
997 m_dirs
.Insert(wxT(".."), 0u);
1000 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1002 // a directory made relative with respect to itself is '.' under Unix
1003 // and DOS, by definition (but we don't have to insert "./" for the
1005 if ( m_dirs
.IsEmpty() && IsDir() )
1007 m_dirs
.Add(_T('.'));
1017 // ----------------------------------------------------------------------------
1018 // filename kind tests
1019 // ----------------------------------------------------------------------------
1021 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
1023 wxFileName fn1
= *this,
1026 // get cwd only once - small time saving
1027 wxString cwd
= wxGetCwd();
1028 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
1029 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
1031 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1034 // TODO: compare inodes for Unix, this works even when filenames are
1035 // different but files are the same (symlinks) (VZ)
1041 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1043 // only Unix filenames are truely case-sensitive
1044 return GetFormat(format
) == wxPATH_UNIX
;
1048 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
1052 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1053 (GetFormat(format
) == wxPATH_VMS
) )
1055 sepVol
= wxFILE_SEP_DSK
;
1063 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1066 switch ( GetFormat(format
) )
1069 // accept both as native APIs do but put the native one first as
1070 // this is the one we use in GetFullPath()
1071 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1075 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
1079 seps
= wxFILE_SEP_PATH_UNIX
;
1083 seps
= wxFILE_SEP_PATH_MAC
;
1087 seps
= wxFILE_SEP_PATH_VMS
;
1095 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1097 // wxString::Find() doesn't work as expected with NUL - it will always find
1098 // it, so it is almost surely a bug if this function is called with NUL arg
1099 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1101 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1104 // ----------------------------------------------------------------------------
1105 // path components manipulation
1106 // ----------------------------------------------------------------------------
1108 void wxFileName::AppendDir( const wxString
&dir
)
1113 void wxFileName::PrependDir( const wxString
&dir
)
1115 m_dirs
.Insert( dir
, 0 );
1118 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1120 m_dirs
.Insert( dir
, before
);
1123 void wxFileName::RemoveDir( int pos
)
1125 m_dirs
.Remove( (size_t)pos
);
1128 // ----------------------------------------------------------------------------
1130 // ----------------------------------------------------------------------------
1132 void wxFileName::SetFullName(const wxString
& fullname
)
1134 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1137 wxString
wxFileName::GetFullName() const
1139 wxString fullname
= m_name
;
1140 if ( !m_ext
.empty() )
1142 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1148 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1150 format
= GetFormat( format
);
1154 // return the volume with the path as well if requested
1155 if ( flags
& wxPATH_GET_VOLUME
)
1157 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1160 // the leading character
1165 fullpath
+= wxFILE_SEP_PATH_MAC
;
1170 fullpath
+= wxFILE_SEP_PATH_DOS
;
1174 wxFAIL_MSG( _T("unknown path format") );
1180 // normally the absolute file names starts with a slash with
1181 // one exception: file names like "~/foo.bar" don't have it
1182 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1184 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1190 // no leading character here but use this place to unset
1191 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense as,
1192 // if I understand correctly, there should never be a dot before
1193 // the closing bracket
1194 flags
&= ~wxPATH_GET_SEPARATOR
;
1197 // then concatenate all the path components using the path separator
1198 size_t dirCount
= m_dirs
.GetCount();
1201 if ( format
== wxPATH_VMS
)
1203 fullpath
+= wxT('[');
1206 for ( size_t i
= 0; i
< dirCount
; i
++ )
1211 if ( m_dirs
[i
] == wxT(".") )
1213 // skip appending ':', this shouldn't be done in this
1214 // case as "::" is interpreted as ".." under Unix
1218 // convert back from ".." to nothing
1219 if ( m_dirs
[i
] != wxT("..") )
1220 fullpath
+= m_dirs
[i
];
1224 wxFAIL_MSG( wxT("unexpected path format") );
1225 // still fall through
1229 fullpath
+= m_dirs
[i
];
1233 // TODO: What to do with ".." under VMS
1235 // convert back from ".." to nothing
1236 if ( m_dirs
[i
] != wxT("..") )
1237 fullpath
+= m_dirs
[i
];
1241 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1242 fullpath
+= GetPathSeparator(format
);
1245 if ( format
== wxPATH_VMS
)
1247 fullpath
+= wxT(']');
1254 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1256 // we already have a function to get the path
1257 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1260 // now just add the file name and extension to it
1261 fullpath
+= GetFullName();
1266 // Return the short form of the path (returns identity on non-Windows platforms)
1267 wxString
wxFileName::GetShortPath() const
1269 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1270 wxString
path(GetFullPath());
1272 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1276 ok
= ::GetShortPathName
1279 pathOut
.GetWriteBuf(sz
),
1282 pathOut
.UngetWriteBuf();
1289 return GetFullPath();
1293 // Return the long form of the path (returns identity on non-Windows platforms)
1294 wxString
wxFileName::GetLongPath() const
1297 path
= GetFullPath();
1299 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1300 bool success
= FALSE
;
1302 #if wxUSE_DYNAMIC_LOADER
1303 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1305 static bool s_triedToLoad
= FALSE
;
1307 if ( !s_triedToLoad
)
1309 // suppress the errors about missing GetLongPathName[AW]
1312 s_triedToLoad
= TRUE
;
1313 wxDynamicLibrary
dllKernel(_T("kernel32"));
1314 if ( dllKernel
.IsLoaded() )
1316 // may succeed or fail depending on the Windows version
1317 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1319 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1321 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1324 if ( s_pfnGetLongPathName
)
1326 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1327 bool ok
= dwSize
> 0;
1331 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1335 ok
= (*s_pfnGetLongPathName
)
1338 pathOut
.GetWriteBuf(sz
),
1341 pathOut
.UngetWriteBuf();
1352 #endif // wxUSE_DYNAMIC_LOADER
1356 // The OS didn't support GetLongPathName, or some other error.
1357 // We need to call FindFirstFile on each component in turn.
1359 WIN32_FIND_DATA findFileData
;
1361 pathOut
= wxEmptyString
;
1363 wxArrayString dirs
= GetDirs();
1364 dirs
.Add(GetFullName());
1368 size_t count
= dirs
.GetCount();
1369 for ( size_t i
= 0; i
< count
; i
++ )
1371 // We're using pathOut to collect the long-name path, but using a
1372 // temporary for appending the last path component which may be
1374 tmpPath
= pathOut
+ dirs
[i
];
1376 if ( tmpPath
.empty() )
1379 if ( tmpPath
.Last() == wxT(':') )
1381 // Can't pass a drive and root dir to FindFirstFile,
1382 // so continue to next dir
1383 tmpPath
+= wxFILE_SEP_PATH
;
1388 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1389 if (hFind
== INVALID_HANDLE_VALUE
)
1391 // Error: return immediately with the original path
1395 pathOut
+= findFileData
.cFileName
;
1396 if ( (i
< (count
-1)) )
1397 pathOut
+= wxFILE_SEP_PATH
;
1404 #endif // Win32/!Win32
1409 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1411 if (format
== wxPATH_NATIVE
)
1413 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1414 format
= wxPATH_DOS
;
1415 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1416 format
= wxPATH_MAC
;
1417 #elif defined(__VMS)
1418 format
= wxPATH_VMS
;
1420 format
= wxPATH_UNIX
;
1426 // ----------------------------------------------------------------------------
1427 // path splitting function
1428 // ----------------------------------------------------------------------------
1431 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1432 wxString
*pstrVolume
,
1436 wxPathFormat format
)
1438 format
= GetFormat(format
);
1440 wxString fullpath
= fullpathWithVolume
;
1442 // under VMS the end of the path is ']', not the path separator used to
1443 // separate the components
1444 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1445 : GetPathSeparators(format
);
1447 // special Windows UNC paths hack: transform \\share\path into share:path
1448 if ( format
== wxPATH_DOS
)
1450 if ( fullpath
.length() >= 4 &&
1451 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1452 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1454 fullpath
.erase(0, 2);
1456 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1457 if ( posFirstSlash
!= wxString::npos
)
1459 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1461 // UNC paths are always absolute, right? (FIXME)
1462 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1467 // We separate the volume here
1468 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1470 wxString sepVol
= GetVolumeSeparator(format
);
1472 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1473 if ( posFirstColon
!= wxString::npos
)
1477 *pstrVolume
= fullpath
.Left(posFirstColon
);
1480 // remove the volume name and the separator from the full path
1481 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1485 // find the positions of the last dot and last path separator in the path
1486 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1487 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1489 if ( (posLastDot
!= wxString::npos
) &&
1490 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1492 if ( (posLastDot
== 0) ||
1493 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1495 // under Unix and VMS, dot may be (and commonly is) the first
1496 // character of the filename, don't treat the entire filename as
1497 // extension in this case
1498 posLastDot
= wxString::npos
;
1502 // if we do have a dot and a slash, check that the dot is in the name part
1503 if ( (posLastDot
!= wxString::npos
) &&
1504 (posLastSlash
!= wxString::npos
) &&
1505 (posLastDot
< posLastSlash
) )
1507 // the dot is part of the path, not the start of the extension
1508 posLastDot
= wxString::npos
;
1511 // now fill in the variables provided by user
1514 if ( posLastSlash
== wxString::npos
)
1521 // take everything up to the path separator but take care to make
1522 // the path equal to something like '/', not empty, for the files
1523 // immediately under root directory
1524 size_t len
= posLastSlash
;
1526 // this rule does not apply to mac since we do not start with colons (sep)
1527 // except for relative paths
1528 if ( !len
&& format
!= wxPATH_MAC
)
1531 *pstrPath
= fullpath
.Left(len
);
1533 // special VMS hack: remove the initial bracket
1534 if ( format
== wxPATH_VMS
)
1536 if ( (*pstrPath
)[0u] == _T('[') )
1537 pstrPath
->erase(0, 1);
1544 // take all characters starting from the one after the last slash and
1545 // up to, but excluding, the last dot
1546 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1548 if ( posLastDot
== wxString::npos
)
1550 // take all until the end
1551 count
= wxString::npos
;
1553 else if ( posLastSlash
== wxString::npos
)
1557 else // have both dot and slash
1559 count
= posLastDot
- posLastSlash
- 1;
1562 *pstrName
= fullpath
.Mid(nStart
, count
);
1567 if ( posLastDot
== wxString::npos
)
1574 // take everything after the dot
1575 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1581 void wxFileName::SplitPath(const wxString
& fullpath
,
1585 wxPathFormat format
)
1588 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1592 path
->Prepend(wxGetVolumeString(volume
, format
));
1596 // ----------------------------------------------------------------------------
1598 // ----------------------------------------------------------------------------
1600 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1601 const wxDateTime
*dtMod
,
1602 const wxDateTime
*dtCreate
)
1604 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1605 if ( !dtAccess
&& !dtMod
)
1607 // can't modify the creation time anyhow, don't try
1611 // if dtAccess or dtMod is not specified, use the other one (which must be
1612 // non NULL because of the test above) for both times
1614 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1615 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1616 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
1620 #elif defined(__WIN32__)
1621 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1624 FILETIME ftAccess
, ftCreate
, ftWrite
;
1627 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1629 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1631 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1633 if ( ::SetFileTime(fh
,
1634 dtCreate
? &ftCreate
: NULL
,
1635 dtAccess
? &ftAccess
: NULL
,
1636 dtMod
? &ftWrite
: NULL
) )
1641 #else // other platform
1644 wxLogSysError(_("Failed to modify file times for '%s'"),
1645 GetFullPath().c_str());
1650 bool wxFileName::Touch()
1652 #if defined(__UNIX_LIKE__)
1653 // under Unix touching file is simple: just pass NULL to utime()
1654 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
1659 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1662 #else // other platform
1663 wxDateTime dtNow
= wxDateTime::Now();
1665 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1669 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1671 wxDateTime
*dtCreate
) const
1673 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1675 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
1678 dtAccess
->Set(stBuf
.st_atime
);
1680 dtMod
->Set(stBuf
.st_mtime
);
1682 dtCreate
->Set(stBuf
.st_ctime
);
1686 #elif defined(__WIN32__)
1687 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1690 FILETIME ftAccess
, ftCreate
, ftWrite
;
1692 if ( ::GetFileTime(fh
,
1693 dtCreate
? &ftCreate
: NULL
,
1694 dtAccess
? &ftAccess
: NULL
,
1695 dtMod
? &ftWrite
: NULL
) )
1698 ConvertFileTimeToWx(dtCreate
, ftCreate
);
1700 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1702 ConvertFileTimeToWx(dtMod
, ftWrite
);
1707 #else // other platform
1710 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1711 GetFullPath().c_str());
1718 const short kMacExtensionMaxLength
= 16 ;
1719 class MacDefaultExtensionRecord
1722 MacDefaultExtensionRecord()
1725 m_type
= m_creator
= NULL
;
1727 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
1729 strcpy( m_ext
, from
.m_ext
) ;
1730 m_type
= from
.m_type
;
1731 m_creator
= from
.m_creator
;
1733 MacDefaultExtensionRecord( const char * extension
, OSType type
, OSType creator
)
1735 strncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
1736 m_ext
[kMacExtensionMaxLength
] = 0 ;
1738 m_creator
= creator
;
1740 char m_ext
[kMacExtensionMaxLength
] ;
1745 #include "wx/dynarray.h"
1746 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1748 bool gMacDefaultExtensionsInited
= false ;
1750 #include "wx/arrimpl.cpp"
1752 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
1754 MacDefaultExtensionArray gMacDefaultExtensions
;
1756 static void MacEnsureDefaultExtensionsLoaded()
1758 if ( !gMacDefaultExtensionsInited
)
1761 // load the default extensions
1762 MacDefaultExtensionRecord defaults
[1] =
1764 MacDefaultExtensionRecord( "txt" , 'TEXT' , 'ttxt' ) ,
1767 // we could load the pc exchange prefs here too
1769 for ( size_t i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1771 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1773 gMacDefaultExtensionsInited
= true ;
1776 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1780 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1781 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1782 wxCHECK( err
== noErr
, false ) ;
1784 fndrInfo
.fdType
= type
;
1785 fndrInfo
.fdCreator
= creator
;
1786 FSpSetFInfo( &spec
, &fndrInfo
) ;
1790 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1794 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1795 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1796 wxCHECK( err
== noErr
, false ) ;
1798 *type
= fndrInfo
.fdType
;
1799 *creator
= fndrInfo
.fdCreator
;
1803 bool wxFileName::MacSetDefaultTypeAndCreator()
1805 wxUint32 type
, creator
;
1806 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1809 return MacSetTypeAndCreator( type
, creator
) ;
1814 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1816 MacEnsureDefaultExtensionsLoaded() ;
1817 wxString extl
= ext
.Lower() ;
1818 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1820 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1822 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1823 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1830 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1832 MacEnsureDefaultExtensionsLoaded() ;
1833 MacDefaultExtensionRecord rec
;
1835 rec
.m_creator
= creator
;
1836 strncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1837 gMacDefaultExtensions
.Add( rec
) ;