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 licence
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>
111 #include <sys/types.h>
113 #include <sys/stat.h>
124 #include <sys/utime.h>
125 #include <sys/stat.h>
135 #define MAX_PATH _MAX_PATH
138 // ----------------------------------------------------------------------------
140 // ----------------------------------------------------------------------------
142 // small helper class which opens and closes the file - we use it just to get
143 // a file handle for the given file name to pass it to some Win32 API function
144 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
155 wxFileHandle(const wxString
& filename
, OpenMode mode
)
157 m_hFile
= ::CreateFile
160 mode
== Read
? GENERIC_READ
// access mask
163 NULL
, // no secutity attr
164 OPEN_EXISTING
, // creation disposition
166 NULL
// no template file
169 if ( m_hFile
== INVALID_HANDLE_VALUE
)
171 wxLogSysError(_("Failed to open '%s' for %s"),
173 mode
== Read
? _("reading") : _("writing"));
179 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
181 if ( !::CloseHandle(m_hFile
) )
183 wxLogSysError(_("Failed to close file handle"));
188 // return TRUE only if the file could be opened successfully
189 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
192 operator HANDLE() const { return m_hFile
; }
200 // ----------------------------------------------------------------------------
202 // ----------------------------------------------------------------------------
204 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
206 // convert between wxDateTime and FILETIME which is a 64-bit value representing
207 // the number of 100-nanosecond intervals since January 1, 1601.
209 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
211 FILETIME ftcopy
= ft
;
213 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
215 wxLogLastError(_T("FileTimeToLocalFileTime"));
219 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
221 wxLogLastError(_T("FileTimeToSystemTime"));
224 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
225 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
228 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
231 st
.wDay
= dt
.GetDay();
232 st
.wMonth
= dt
.GetMonth() + 1;
233 st
.wYear
= dt
.GetYear();
234 st
.wHour
= dt
.GetHour();
235 st
.wMinute
= dt
.GetMinute();
236 st
.wSecond
= dt
.GetSecond();
237 st
.wMilliseconds
= dt
.GetMillisecond();
240 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
242 wxLogLastError(_T("SystemTimeToFileTime"));
245 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
247 wxLogLastError(_T("LocalFileTimeToFileTime"));
251 #endif // wxUSE_DATETIME && __WIN32__
253 // return a string with the volume par
254 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
258 if ( !volume
.empty() )
260 format
= wxFileName::GetFormat(format
);
262 // Special Windows UNC paths hack, part 2: undo what we did in
263 // SplitPath() and make an UNC path if we have a drive which is not a
264 // single letter (hopefully the network shares can't be one letter only
265 // although I didn't find any authoritative docs on this)
266 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
268 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
270 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
272 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
280 // ============================================================================
282 // ============================================================================
284 // ----------------------------------------------------------------------------
285 // wxFileName construction
286 // ----------------------------------------------------------------------------
288 void wxFileName::Assign( const wxFileName
&filepath
)
290 m_volume
= filepath
.GetVolume();
291 m_dirs
= filepath
.GetDirs();
292 m_name
= filepath
.GetName();
293 m_ext
= filepath
.GetExt();
294 m_relative
= filepath
.m_relative
;
297 void wxFileName::Assign(const wxString
& volume
,
298 const wxString
& path
,
299 const wxString
& name
,
301 wxPathFormat format
)
303 SetPath( path
, format
);
310 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
316 wxPathFormat my_format
= GetFormat( format
);
317 wxString my_path
= path
;
319 // 1) Determine if the path is relative or absolute.
320 wxChar leadingChar
= my_path
[0u];
325 m_relative
= leadingChar
== wxT(':');
327 // We then remove a leading ":". The reason is in our
328 // storage form for relative paths:
329 // ":dir:file.txt" actually means "./dir/file.txt" in
330 // DOS notation and should get stored as
331 // (relative) (dir) (file.txt)
332 // "::dir:file.txt" actually means "../dir/file.txt"
333 // stored as (relative) (..) (dir) (file.txt)
334 // This is important only for the Mac as an empty dir
335 // actually means <UP>, whereas under DOS, double
336 // slashes can be ignored: "\\\\" is the same as "\\".
338 my_path
.erase( 0, 1 );
342 // TODO: what is the relative path format here?
347 // the paths of the form "~" or "~username" are absolute
348 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
352 m_relative
= !IsPathSeparator(leadingChar
, my_format
);
356 wxFAIL_MSG( wxT("error") );
360 // 2) Break up the path into its members. If the original path
361 // was just "/" or "\\", m_dirs will be empty. We know from
362 // the m_relative field, if this means "nothing" or "root dir".
364 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
366 while ( tn
.HasMoreTokens() )
368 wxString token
= tn
.GetNextToken();
370 // Remove empty token under DOS and Unix, interpret them
374 if (my_format
== wxPATH_MAC
)
375 m_dirs
.Add( wxT("..") );
384 else // no path at all
390 void wxFileName::Assign(const wxString
& fullpath
,
393 wxString volume
, path
, name
, ext
;
394 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
396 Assign(volume
, path
, name
, ext
, format
);
399 void wxFileName::Assign(const wxString
& fullpathOrig
,
400 const wxString
& fullname
,
403 // always recognize fullpath as directory, even if it doesn't end with a
405 wxString fullpath
= fullpathOrig
;
406 if ( !wxEndsWithPathSeparator(fullpath
) )
408 fullpath
+= GetPathSeparator(format
);
411 wxString volume
, path
, name
, ext
;
413 // do some consistency checks in debug mode: the name should be really just
414 // the filename and the path should be really just a path
416 wxString pathDummy
, nameDummy
, extDummy
;
418 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
420 wxASSERT_MSG( pathDummy
.empty(),
421 _T("the file name shouldn't contain the path") );
423 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
425 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
426 _T("the path shouldn't contain file name nor extension") );
428 #else // !__WXDEBUG__
429 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
430 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
431 #endif // __WXDEBUG__/!__WXDEBUG__
433 Assign(volume
, path
, name
, ext
, format
);
436 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
438 Assign(dir
, _T(""), format
);
441 void wxFileName::Clear()
447 m_ext
= wxEmptyString
;
449 // we don't have any absolute path for now
454 wxFileName
wxFileName::FileName(const wxString
& file
)
456 return wxFileName(file
);
460 wxFileName
wxFileName::DirName(const wxString
& dir
)
467 // ----------------------------------------------------------------------------
469 // ----------------------------------------------------------------------------
471 bool wxFileName::FileExists() const
473 return wxFileName::FileExists( GetFullPath() );
476 bool wxFileName::FileExists( const wxString
&file
)
478 return ::wxFileExists( file
);
481 bool wxFileName::DirExists() const
483 return wxFileName::DirExists( GetFullPath() );
486 bool wxFileName::DirExists( const wxString
&dir
)
488 return ::wxDirExists( dir
);
491 // ----------------------------------------------------------------------------
492 // CWD and HOME stuff
493 // ----------------------------------------------------------------------------
495 void wxFileName::AssignCwd(const wxString
& volume
)
497 AssignDir(wxFileName::GetCwd(volume
));
501 wxString
wxFileName::GetCwd(const wxString
& volume
)
503 // if we have the volume, we must get the current directory on this drive
504 // and to do this we have to chdir to this volume - at least under Windows,
505 // I don't know how to get the current drive on another volume elsewhere
508 if ( !volume
.empty() )
511 SetCwd(volume
+ GetVolumeSeparator());
514 wxString cwd
= ::wxGetCwd();
516 if ( !volume
.empty() )
524 bool wxFileName::SetCwd()
526 return wxFileName::SetCwd( GetFullPath() );
529 bool wxFileName::SetCwd( const wxString
&cwd
)
531 return ::wxSetWorkingDirectory( cwd
);
534 void wxFileName::AssignHomeDir()
536 AssignDir(wxFileName::GetHomeDir());
539 wxString
wxFileName::GetHomeDir()
541 return ::wxGetHomeDir();
544 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
546 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
547 if ( tempname
.empty() )
549 // error, failed to get temp file name
560 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
562 wxString path
, dir
, name
;
564 // use the directory specified by the prefix
565 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
567 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
572 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
574 wxLogLastError(_T("GetTempPath"));
579 // GetTempFileName() fails if we pass it an empty string
583 else // we have a dir to create the file in
585 // ensure we use only the back slashes as GetTempFileName(), unlike all
586 // the other APIs, is picky and doesn't accept the forward ones
587 dir
.Replace(_T("/"), _T("\\"));
590 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
592 wxLogLastError(_T("GetTempFileName"));
597 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
603 #elif defined(__WXPM__)
604 // for now just create a file
606 // future enhancements can be to set some extended attributes for file
607 // systems OS/2 supports that have them (HPFS, FAT32) and security
609 static const wxChar
*szMktempSuffix
= wxT("XXX");
610 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
612 // Temporarily remove - MN
614 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
617 #else // !Windows, !OS/2
620 #if defined(__WXMAC__) && !defined(__DARWIN__)
621 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
623 dir
= wxGetenv(_T("TMP"));
626 dir
= wxGetenv(_T("TEMP"));
643 if ( !wxEndsWithPathSeparator(dir
) &&
644 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
646 path
+= wxFILE_SEP_PATH
;
651 #if defined(HAVE_MKSTEMP)
652 // scratch space for mkstemp()
653 path
+= _T("XXXXXX");
655 // we need to copy the path to the buffer in which mkstemp() can modify it
656 wxCharBuffer
buf( wxConvFile
.cWX2MB( path
) );
658 // cast is safe because the string length doesn't change
659 int fdTemp
= mkstemp( (char*)(const char*) buf
);
662 // this might be not necessary as mkstemp() on most systems should have
663 // already done it but it doesn't hurt neither...
666 else // mkstemp() succeeded
668 path
= wxConvFile
.cMB2WX( (const char*) buf
);
670 // avoid leaking the fd
673 fileTemp
->Attach(fdTemp
);
680 #else // !HAVE_MKSTEMP
684 path
+= _T("XXXXXX");
686 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
687 if ( !mktemp( (const char*) buf
) )
693 path
= wxConvFile
.cMB2WX( (const char*) buf
);
695 #else // !HAVE_MKTEMP (includes __DOS__)
696 // generate the unique file name ourselves
698 path
<< (unsigned int)getpid();
703 static const size_t numTries
= 1000;
704 for ( size_t n
= 0; n
< numTries
; n
++ )
706 // 3 hex digits is enough for numTries == 1000 < 4096
707 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
708 if ( !wxFile::Exists(pathTry
) )
717 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
722 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
724 #endif // Windows/!Windows
728 wxLogSysError(_("Failed to create a temporary file name"));
730 else if ( fileTemp
&& !fileTemp
->IsOpened() )
732 // open the file - of course, there is a race condition here, this is
733 // why we always prefer using mkstemp()...
735 // NB: GetTempFileName() under Windows creates the file, so using
736 // write_excl there would fail
737 if ( !fileTemp
->Open(path
,
738 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
743 wxS_IRUSR
| wxS_IWUSR
) )
745 // FIXME: If !ok here should we loop and try again with another
746 // file name? That is the standard recourse if open(O_EXCL)
747 // fails, though of course it should be protected against
748 // possible infinite looping too.
750 wxLogError(_("Failed to open temporary file."));
759 // ----------------------------------------------------------------------------
760 // directory operations
761 // ----------------------------------------------------------------------------
763 bool wxFileName::Mkdir( int perm
, int flags
)
765 return wxFileName::Mkdir( GetFullPath(), perm
, flags
);
768 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
770 if ( flags
& wxPATH_MKDIR_FULL
)
772 // split the path in components
774 filename
.AssignDir(dir
);
777 if ( filename
.HasVolume())
779 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
782 wxArrayString dirs
= filename
.GetDirs();
783 size_t count
= dirs
.GetCount();
784 for ( size_t i
= 0; i
< count
; i
++ )
787 #if defined(__WXMAC__) && !defined(__DARWIN__)
788 // relative pathnames are exactely the other way round under mac...
789 !filename
.IsAbsolute()
791 filename
.IsAbsolute()
794 currPath
+= wxFILE_SEP_PATH
;
797 if (!DirExists(currPath
))
799 if (!wxMkdir(currPath
, perm
))
801 // no need to try creating further directories
811 return ::wxMkdir( dir
, perm
);
814 bool wxFileName::Rmdir()
816 return wxFileName::Rmdir( GetFullPath() );
819 bool wxFileName::Rmdir( const wxString
&dir
)
821 return ::wxRmdir( dir
);
824 // ----------------------------------------------------------------------------
825 // path normalization
826 // ----------------------------------------------------------------------------
828 bool wxFileName::Normalize(int flags
,
832 // the existing path components
833 wxArrayString dirs
= GetDirs();
835 // the path to prepend in front to make the path absolute
838 format
= GetFormat(format
);
840 // make the path absolute
841 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
845 curDir
.AssignCwd(GetVolume());
849 curDir
.AssignDir(cwd
);
852 // the path may be not absolute because it doesn't have the volume name
853 // but in this case we shouldn't modify the directory components of it
854 // but just set the current volume
855 if ( !HasVolume() && curDir
.HasVolume() )
857 SetVolume(curDir
.GetVolume());
861 // yes, it was the case - we don't need curDir then
867 // handle ~ stuff under Unix only
868 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
870 if ( !dirs
.IsEmpty() )
872 wxString dir
= dirs
[0u];
873 if ( !dir
.empty() && dir
[0u] == _T('~') )
875 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
882 // transform relative path into abs one
885 wxArrayString dirsNew
= curDir
.GetDirs();
886 size_t count
= dirs
.GetCount();
887 for ( size_t n
= 0; n
< count
; n
++ )
889 dirsNew
.Add(dirs
[n
]);
895 // now deal with ".", ".." and the rest
897 size_t count
= dirs
.GetCount();
898 for ( size_t n
= 0; n
< count
; n
++ )
900 wxString dir
= dirs
[n
];
902 if ( flags
& wxPATH_NORM_DOTS
)
904 if ( dir
== wxT(".") )
910 if ( dir
== wxT("..") )
912 if ( m_dirs
.IsEmpty() )
914 wxLogError(_("The path '%s' contains too many \"..\"!"),
915 GetFullPath().c_str());
919 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
924 if ( flags
& wxPATH_NORM_ENV_VARS
)
926 dir
= wxExpandEnvVars(dir
);
929 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
937 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
939 // VZ: expand env vars here too?
945 // we do have the path now
947 // NB: need to do this before (maybe) calling Assign() below
950 #if defined(__WIN32__)
951 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
953 Assign(GetLongPath());
960 // ----------------------------------------------------------------------------
961 // absolute/relative paths
962 // ----------------------------------------------------------------------------
964 bool wxFileName::IsAbsolute(wxPathFormat format
) const
966 // if our path doesn't start with a path separator, it's not an absolute
971 if ( !GetVolumeSeparator(format
).empty() )
973 // this format has volumes and an absolute path must have one, it's not
974 // enough to have the full path to bean absolute file under Windows
975 if ( GetVolume().empty() )
982 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
984 wxFileName
fnBase(pathBase
, format
);
986 // get cwd only once - small time saving
987 wxString cwd
= wxGetCwd();
988 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
989 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
991 bool withCase
= IsCaseSensitive(format
);
993 // we can't do anything if the files live on different volumes
994 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1000 // same drive, so we don't need our volume
1003 // remove common directories starting at the top
1004 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1005 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1008 fnBase
.m_dirs
.RemoveAt(0);
1011 // add as many ".." as needed
1012 size_t count
= fnBase
.m_dirs
.GetCount();
1013 for ( size_t i
= 0; i
< count
; i
++ )
1015 m_dirs
.Insert(wxT(".."), 0u);
1018 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1020 // a directory made relative with respect to itself is '.' under Unix
1021 // and DOS, by definition (but we don't have to insert "./" for the
1023 if ( m_dirs
.IsEmpty() && IsDir() )
1025 m_dirs
.Add(_T('.'));
1035 // ----------------------------------------------------------------------------
1036 // filename kind tests
1037 // ----------------------------------------------------------------------------
1039 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1041 wxFileName fn1
= *this,
1044 // get cwd only once - small time saving
1045 wxString cwd
= wxGetCwd();
1046 fn1
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1047 fn2
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1049 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1052 // TODO: compare inodes for Unix, this works even when filenames are
1053 // different but files are the same (symlinks) (VZ)
1059 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1061 // only Unix filenames are truely case-sensitive
1062 return GetFormat(format
) == wxPATH_UNIX
;
1066 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
1070 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1071 (GetFormat(format
) == wxPATH_VMS
) )
1073 sepVol
= wxFILE_SEP_DSK
;
1081 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1084 switch ( GetFormat(format
) )
1087 // accept both as native APIs do but put the native one first as
1088 // this is the one we use in GetFullPath()
1089 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1093 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
1097 seps
= wxFILE_SEP_PATH_UNIX
;
1101 seps
= wxFILE_SEP_PATH_MAC
;
1105 seps
= wxFILE_SEP_PATH_VMS
;
1113 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1115 // wxString::Find() doesn't work as expected with NUL - it will always find
1116 // it, so it is almost surely a bug if this function is called with NUL arg
1117 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1119 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1122 // ----------------------------------------------------------------------------
1123 // path components manipulation
1124 // ----------------------------------------------------------------------------
1126 void wxFileName::AppendDir( const wxString
&dir
)
1131 void wxFileName::PrependDir( const wxString
&dir
)
1133 m_dirs
.Insert( dir
, 0 );
1136 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1138 m_dirs
.Insert( dir
, before
);
1141 void wxFileName::RemoveDir( int pos
)
1143 m_dirs
.Remove( (size_t)pos
);
1146 // ----------------------------------------------------------------------------
1148 // ----------------------------------------------------------------------------
1150 void wxFileName::SetFullName(const wxString
& fullname
)
1152 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1155 wxString
wxFileName::GetFullName() const
1157 wxString fullname
= m_name
;
1158 if ( !m_ext
.empty() )
1160 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1166 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1168 format
= GetFormat( format
);
1172 // return the volume with the path as well if requested
1173 if ( flags
& wxPATH_GET_VOLUME
)
1175 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1178 // the leading character
1183 fullpath
+= wxFILE_SEP_PATH_MAC
;
1188 fullpath
+= wxFILE_SEP_PATH_DOS
;
1192 wxFAIL_MSG( _T("unknown path format") );
1198 // normally the absolute file names starts with a slash with
1199 // one exception: file names like "~/foo.bar" don't have it
1200 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1202 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1208 // no leading character here but use this place to unset
1209 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense as,
1210 // if I understand correctly, there should never be a dot before
1211 // the closing bracket
1212 flags
&= ~wxPATH_GET_SEPARATOR
;
1215 // then concatenate all the path components using the path separator
1216 size_t dirCount
= m_dirs
.GetCount();
1219 if ( format
== wxPATH_VMS
)
1221 fullpath
+= wxT('[');
1224 for ( size_t i
= 0; i
< dirCount
; i
++ )
1229 if ( m_dirs
[i
] == wxT(".") )
1231 // skip appending ':', this shouldn't be done in this
1232 // case as "::" is interpreted as ".." under Unix
1236 // convert back from ".." to nothing
1237 if ( m_dirs
[i
] != wxT("..") )
1238 fullpath
+= m_dirs
[i
];
1242 wxFAIL_MSG( wxT("unexpected path format") );
1243 // still fall through
1247 fullpath
+= m_dirs
[i
];
1251 // TODO: What to do with ".." under VMS
1253 // convert back from ".." to nothing
1254 if ( m_dirs
[i
] != wxT("..") )
1255 fullpath
+= m_dirs
[i
];
1259 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1260 fullpath
+= GetPathSeparator(format
);
1263 if ( format
== wxPATH_VMS
)
1265 fullpath
+= wxT(']');
1272 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1274 // we already have a function to get the path
1275 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1278 // now just add the file name and extension to it
1279 fullpath
+= GetFullName();
1284 // Return the short form of the path (returns identity on non-Windows platforms)
1285 wxString
wxFileName::GetShortPath() const
1287 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1288 wxString
path(GetFullPath());
1290 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1294 ok
= ::GetShortPathName
1297 pathOut
.GetWriteBuf(sz
),
1300 pathOut
.UngetWriteBuf();
1307 return GetFullPath();
1311 // Return the long form of the path (returns identity on non-Windows platforms)
1312 wxString
wxFileName::GetLongPath() const
1315 path
= GetFullPath();
1317 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1318 bool success
= FALSE
;
1320 #if wxUSE_DYNAMIC_LOADER
1321 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1323 static bool s_triedToLoad
= FALSE
;
1325 if ( !s_triedToLoad
)
1327 // suppress the errors about missing GetLongPathName[AW]
1330 s_triedToLoad
= TRUE
;
1331 wxDynamicLibrary
dllKernel(_T("kernel32"));
1332 if ( dllKernel
.IsLoaded() )
1334 // may succeed or fail depending on the Windows version
1335 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1337 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1339 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1342 if ( s_pfnGetLongPathName
)
1344 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1345 bool ok
= dwSize
> 0;
1349 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1353 ok
= (*s_pfnGetLongPathName
)
1356 pathOut
.GetWriteBuf(sz
),
1359 pathOut
.UngetWriteBuf();
1370 #endif // wxUSE_DYNAMIC_LOADER
1374 // The OS didn't support GetLongPathName, or some other error.
1375 // We need to call FindFirstFile on each component in turn.
1377 WIN32_FIND_DATA findFileData
;
1381 pathOut
= GetVolume() +
1382 GetVolumeSeparator(wxPATH_DOS
) +
1383 GetPathSeparator(wxPATH_DOS
);
1385 pathOut
= wxEmptyString
;
1387 wxArrayString dirs
= GetDirs();
1388 dirs
.Add(GetFullName());
1392 size_t count
= dirs
.GetCount();
1393 for ( size_t i
= 0; i
< count
; i
++ )
1395 // We're using pathOut to collect the long-name path, but using a
1396 // temporary for appending the last path component which may be
1398 tmpPath
= pathOut
+ dirs
[i
];
1400 if ( tmpPath
.empty() )
1403 // can't see this being necessary? MF
1404 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1406 // Can't pass a drive and root dir to FindFirstFile,
1407 // so continue to next dir
1408 tmpPath
+= wxFILE_SEP_PATH
;
1413 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1414 if (hFind
== INVALID_HANDLE_VALUE
)
1416 // Error: most likely reason is that path doesn't exist, so
1417 // append any unprocessed parts and return
1418 for ( i
+= 1; i
< count
; i
++ )
1419 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1424 pathOut
+= findFileData
.cFileName
;
1425 if ( (i
< (count
-1)) )
1426 pathOut
+= wxFILE_SEP_PATH
;
1433 #endif // Win32/!Win32
1438 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1440 if (format
== wxPATH_NATIVE
)
1442 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1443 format
= wxPATH_DOS
;
1444 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1445 format
= wxPATH_MAC
;
1446 #elif defined(__VMS)
1447 format
= wxPATH_VMS
;
1449 format
= wxPATH_UNIX
;
1455 // ----------------------------------------------------------------------------
1456 // path splitting function
1457 // ----------------------------------------------------------------------------
1460 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1461 wxString
*pstrVolume
,
1465 wxPathFormat format
)
1467 format
= GetFormat(format
);
1469 wxString fullpath
= fullpathWithVolume
;
1471 // under VMS the end of the path is ']', not the path separator used to
1472 // separate the components
1473 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1474 : GetPathSeparators(format
);
1476 // special Windows UNC paths hack: transform \\share\path into share:path
1477 if ( format
== wxPATH_DOS
)
1479 if ( fullpath
.length() >= 4 &&
1480 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1481 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1483 fullpath
.erase(0, 2);
1485 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1486 if ( posFirstSlash
!= wxString::npos
)
1488 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1490 // UNC paths are always absolute, right? (FIXME)
1491 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1496 // We separate the volume here
1497 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1499 wxString sepVol
= GetVolumeSeparator(format
);
1501 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1502 if ( posFirstColon
!= wxString::npos
)
1506 *pstrVolume
= fullpath
.Left(posFirstColon
);
1509 // remove the volume name and the separator from the full path
1510 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1514 // find the positions of the last dot and last path separator in the path
1515 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1516 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1518 if ( (posLastDot
!= wxString::npos
) &&
1519 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1521 if ( (posLastDot
== 0) ||
1522 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1524 // under Unix and VMS, dot may be (and commonly is) the first
1525 // character of the filename, don't treat the entire filename as
1526 // extension in this case
1527 posLastDot
= wxString::npos
;
1531 // if we do have a dot and a slash, check that the dot is in the name part
1532 if ( (posLastDot
!= wxString::npos
) &&
1533 (posLastSlash
!= wxString::npos
) &&
1534 (posLastDot
< posLastSlash
) )
1536 // the dot is part of the path, not the start of the extension
1537 posLastDot
= wxString::npos
;
1540 // now fill in the variables provided by user
1543 if ( posLastSlash
== wxString::npos
)
1550 // take everything up to the path separator but take care to make
1551 // the path equal to something like '/', not empty, for the files
1552 // immediately under root directory
1553 size_t len
= posLastSlash
;
1555 // this rule does not apply to mac since we do not start with colons (sep)
1556 // except for relative paths
1557 if ( !len
&& format
!= wxPATH_MAC
)
1560 *pstrPath
= fullpath
.Left(len
);
1562 // special VMS hack: remove the initial bracket
1563 if ( format
== wxPATH_VMS
)
1565 if ( (*pstrPath
)[0u] == _T('[') )
1566 pstrPath
->erase(0, 1);
1573 // take all characters starting from the one after the last slash and
1574 // up to, but excluding, the last dot
1575 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1577 if ( posLastDot
== wxString::npos
)
1579 // take all until the end
1580 count
= wxString::npos
;
1582 else if ( posLastSlash
== wxString::npos
)
1586 else // have both dot and slash
1588 count
= posLastDot
- posLastSlash
- 1;
1591 *pstrName
= fullpath
.Mid(nStart
, count
);
1596 if ( posLastDot
== wxString::npos
)
1603 // take everything after the dot
1604 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1610 void wxFileName::SplitPath(const wxString
& fullpath
,
1614 wxPathFormat format
)
1617 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1621 path
->Prepend(wxGetVolumeString(volume
, format
));
1625 // ----------------------------------------------------------------------------
1627 // ----------------------------------------------------------------------------
1631 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1632 const wxDateTime
*dtMod
,
1633 const wxDateTime
*dtCreate
)
1635 #if defined(__WIN32__)
1638 // VZ: please let me know how to do this if you can
1639 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1643 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1646 FILETIME ftAccess
, ftCreate
, ftWrite
;
1649 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1651 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1653 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1655 if ( ::SetFileTime(fh
,
1656 dtCreate
? &ftCreate
: NULL
,
1657 dtAccess
? &ftAccess
: NULL
,
1658 dtMod
? &ftWrite
: NULL
) )
1664 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1665 if ( !dtAccess
&& !dtMod
)
1667 // can't modify the creation time anyhow, don't try
1671 // if dtAccess or dtMod is not specified, use the other one (which must be
1672 // non NULL because of the test above) for both times
1674 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1675 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1676 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
1680 #else // other platform
1683 wxLogSysError(_("Failed to modify file times for '%s'"),
1684 GetFullPath().c_str());
1689 bool wxFileName::Touch()
1691 #if defined(__UNIX_LIKE__)
1692 // under Unix touching file is simple: just pass NULL to utime()
1693 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
1698 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1701 #else // other platform
1702 wxDateTime dtNow
= wxDateTime::Now();
1704 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1708 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1710 wxDateTime
*dtCreate
) const
1712 #if defined(__WIN32__)
1713 // we must use different methods for the files and directories under
1714 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1715 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1718 FILETIME ftAccess
, ftCreate
, ftWrite
;
1721 // implemented in msw/dir.cpp
1722 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
1723 FILETIME
*, FILETIME
*, FILETIME
*);
1725 // we should pass the path without the trailing separator to
1726 // wxGetDirectoryTimes()
1727 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
1728 &ftAccess
, &ftCreate
, &ftWrite
);
1732 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1735 ok
= ::GetFileTime(fh
,
1736 dtCreate
? &ftCreate
: NULL
,
1737 dtAccess
? &ftAccess
: NULL
,
1738 dtMod
? &ftWrite
: NULL
) != 0;
1749 ConvertFileTimeToWx(dtCreate
, ftCreate
);
1751 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1753 ConvertFileTimeToWx(dtMod
, ftWrite
);
1757 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1759 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
1762 dtAccess
->Set(stBuf
.st_atime
);
1764 dtMod
->Set(stBuf
.st_mtime
);
1766 dtCreate
->Set(stBuf
.st_ctime
);
1770 #else // other platform
1773 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1774 GetFullPath().c_str());
1779 #endif // wxUSE_DATETIME
1783 const short kMacExtensionMaxLength
= 16 ;
1784 class MacDefaultExtensionRecord
1787 MacDefaultExtensionRecord()
1790 m_type
= m_creator
= NULL
;
1792 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
1794 wxStrcpy( m_ext
, from
.m_ext
) ;
1795 m_type
= from
.m_type
;
1796 m_creator
= from
.m_creator
;
1798 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
1800 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
1801 m_ext
[kMacExtensionMaxLength
] = 0 ;
1803 m_creator
= creator
;
1805 wxChar m_ext
[kMacExtensionMaxLength
] ;
1810 #include "wx/dynarray.h"
1811 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1813 bool gMacDefaultExtensionsInited
= false ;
1815 #include "wx/arrimpl.cpp"
1817 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
1819 MacDefaultExtensionArray gMacDefaultExtensions
;
1821 static void MacEnsureDefaultExtensionsLoaded()
1823 if ( !gMacDefaultExtensionsInited
)
1826 // load the default extensions
1827 MacDefaultExtensionRecord defaults
[1] =
1829 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
1832 // we could load the pc exchange prefs here too
1834 for ( size_t i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1836 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1838 gMacDefaultExtensionsInited
= true ;
1841 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1845 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1846 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1847 wxCHECK( err
== noErr
, false ) ;
1849 fndrInfo
.fdType
= type
;
1850 fndrInfo
.fdCreator
= creator
;
1851 FSpSetFInfo( &spec
, &fndrInfo
) ;
1855 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1859 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1860 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1861 wxCHECK( err
== noErr
, false ) ;
1863 *type
= fndrInfo
.fdType
;
1864 *creator
= fndrInfo
.fdCreator
;
1868 bool wxFileName::MacSetDefaultTypeAndCreator()
1870 wxUint32 type
, creator
;
1871 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1874 return MacSetTypeAndCreator( type
, creator
) ;
1879 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1881 MacEnsureDefaultExtensionsLoaded() ;
1882 wxString extl
= ext
.Lower() ;
1883 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1885 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1887 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1888 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1895 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1897 MacEnsureDefaultExtensionsLoaded() ;
1898 MacDefaultExtensionRecord rec
;
1900 rec
.m_creator
= creator
;
1901 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1902 gMacDefaultExtensions
.Add( rec
) ;