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 // Special Windows UNC paths hack, part 2: undo what we did in
250 // SplitPath() and make an UNC path if we have a drive which is not a
251 // single letter (hopefully the network shares can't be one letter only
252 // although I didn't find any authoritative docs on this)
253 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
255 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
257 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
259 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
267 // ============================================================================
269 // ============================================================================
271 // ----------------------------------------------------------------------------
272 // wxFileName construction
273 // ----------------------------------------------------------------------------
275 void wxFileName::Assign( const wxFileName
&filepath
)
277 m_volume
= filepath
.GetVolume();
278 m_dirs
= filepath
.GetDirs();
279 m_name
= filepath
.GetName();
280 m_ext
= filepath
.GetExt();
281 m_relative
= filepath
.m_relative
;
284 void wxFileName::Assign(const wxString
& volume
,
285 const wxString
& path
,
286 const wxString
& name
,
288 wxPathFormat format
)
290 SetPath( path
, format
);
297 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
303 wxPathFormat my_format
= GetFormat( format
);
304 wxString my_path
= path
;
306 // 1) Determine if the path is relative or absolute.
307 wxChar leadingChar
= my_path
[0u];
312 m_relative
= leadingChar
== wxT(':');
314 // We then remove a leading ":". The reason is in our
315 // storage form for relative paths:
316 // ":dir:file.txt" actually means "./dir/file.txt" in
317 // DOS notation and should get stored as
318 // (relative) (dir) (file.txt)
319 // "::dir:file.txt" actually means "../dir/file.txt"
320 // stored as (relative) (..) (dir) (file.txt)
321 // This is important only for the Mac as an empty dir
322 // actually means <UP>, whereas under DOS, double
323 // slashes can be ignored: "\\\\" is the same as "\\".
325 my_path
.erase( 0, 1 );
329 // TODO: what is the relative path format here?
334 // the paths of the form "~" or "~username" are absolute
335 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
339 m_relative
= !IsPathSeparator(leadingChar
, my_format
);
343 wxFAIL_MSG( wxT("error") );
347 // 2) Break up the path into its members. If the original path
348 // was just "/" or "\\", m_dirs will be empty. We know from
349 // the m_relative field, if this means "nothing" or "root dir".
351 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
353 while ( tn
.HasMoreTokens() )
355 wxString token
= tn
.GetNextToken();
357 // Remove empty token under DOS and Unix, interpret them
361 if (my_format
== wxPATH_MAC
)
362 m_dirs
.Add( wxT("..") );
371 else // no path at all
377 void wxFileName::Assign(const wxString
& fullpath
,
380 wxString volume
, path
, name
, ext
;
381 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
383 Assign(volume
, path
, name
, ext
, format
);
386 void wxFileName::Assign(const wxString
& fullpathOrig
,
387 const wxString
& fullname
,
390 // always recognize fullpath as directory, even if it doesn't end with a
392 wxString fullpath
= fullpathOrig
;
393 if ( !wxEndsWithPathSeparator(fullpath
) )
395 fullpath
+= GetPathSeparator(format
);
398 wxString volume
, path
, name
, ext
;
400 // do some consistency checks in debug mode: the name should be really just
401 // the filename and the path should be really just a path
403 wxString pathDummy
, nameDummy
, extDummy
;
405 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
407 wxASSERT_MSG( pathDummy
.empty(),
408 _T("the file name shouldn't contain the path") );
410 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
412 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
413 _T("the path shouldn't contain file name nor extension") );
415 #else // !__WXDEBUG__
416 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
417 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
418 #endif // __WXDEBUG__/!__WXDEBUG__
420 Assign(volume
, path
, name
, ext
, format
);
423 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
425 Assign(dir
, _T(""), format
);
428 void wxFileName::Clear()
434 m_ext
= wxEmptyString
;
438 wxFileName
wxFileName::FileName(const wxString
& file
)
440 return wxFileName(file
);
444 wxFileName
wxFileName::DirName(const wxString
& dir
)
451 // ----------------------------------------------------------------------------
453 // ----------------------------------------------------------------------------
455 bool wxFileName::FileExists()
457 return wxFileName::FileExists( GetFullPath() );
460 bool wxFileName::FileExists( const wxString
&file
)
462 return ::wxFileExists( file
);
465 bool wxFileName::DirExists()
467 return wxFileName::DirExists( GetFullPath() );
470 bool wxFileName::DirExists( const wxString
&dir
)
472 return ::wxDirExists( dir
);
475 // ----------------------------------------------------------------------------
476 // CWD and HOME stuff
477 // ----------------------------------------------------------------------------
479 void wxFileName::AssignCwd(const wxString
& volume
)
481 AssignDir(wxFileName::GetCwd(volume
));
485 wxString
wxFileName::GetCwd(const wxString
& volume
)
487 // if we have the volume, we must get the current directory on this drive
488 // and to do this we have to chdir to this volume - at least under Windows,
489 // I don't know how to get the current drive on another volume elsewhere
492 if ( !volume
.empty() )
495 SetCwd(volume
+ GetVolumeSeparator());
498 wxString cwd
= ::wxGetCwd();
500 if ( !volume
.empty() )
508 bool wxFileName::SetCwd()
510 return wxFileName::SetCwd( GetFullPath() );
513 bool wxFileName::SetCwd( const wxString
&cwd
)
515 return ::wxSetWorkingDirectory( cwd
);
518 void wxFileName::AssignHomeDir()
520 AssignDir(wxFileName::GetHomeDir());
523 wxString
wxFileName::GetHomeDir()
525 return ::wxGetHomeDir();
528 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
530 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
531 if ( tempname
.empty() )
533 // error, failed to get temp file name
544 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
546 wxString path
, dir
, name
;
548 // use the directory specified by the prefix
549 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
551 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
556 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
558 wxLogLastError(_T("GetTempPath"));
563 // GetTempFileName() fails if we pass it an empty string
567 else // we have a dir to create the file in
569 // ensure we use only the back slashes as GetTempFileName(), unlike all
570 // the other APIs, is picky and doesn't accept the forward ones
571 dir
.Replace(_T("/"), _T("\\"));
574 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
576 wxLogLastError(_T("GetTempFileName"));
581 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
587 #elif defined(__WXPM__)
588 // for now just create a file
590 // future enhancements can be to set some extended attributes for file
591 // systems OS/2 supports that have them (HPFS, FAT32) and security
593 static const wxChar
*szMktempSuffix
= wxT("XXX");
594 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
596 // Temporarily remove - MN
598 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
601 #else // !Windows, !OS/2
604 #if defined(__WXMAC__) && !defined(__DARWIN__)
605 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
607 dir
= wxGetenv(_T("TMP"));
610 dir
= wxGetenv(_T("TEMP"));
627 if ( !wxEndsWithPathSeparator(dir
) &&
628 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
630 path
+= wxFILE_SEP_PATH
;
635 #if defined(HAVE_MKSTEMP)
636 // scratch space for mkstemp()
637 path
+= _T("XXXXXX");
639 // can use the cast here because the length doesn't change and the string
641 int fdTemp
= mkstemp((char *)path
.mb_str());
644 // this might be not necessary as mkstemp() on most systems should have
645 // already done it but it doesn't hurt neither...
648 else // mkstemp() succeeded
650 // avoid leaking the fd
653 fileTemp
->Attach(fdTemp
);
660 #else // !HAVE_MKSTEMP
664 path
+= _T("XXXXXX");
666 if ( !mktemp((char *)path
.mb_str()) )
670 #else // !HAVE_MKTEMP (includes __DOS__)
671 // generate the unique file name ourselves
673 path
<< (unsigned int)getpid();
678 static const size_t numTries
= 1000;
679 for ( size_t n
= 0; n
< numTries
; n
++ )
681 // 3 hex digits is enough for numTries == 1000 < 4096
682 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
683 if ( !wxFile::Exists(pathTry
) )
692 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
697 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
699 #endif // Windows/!Windows
703 wxLogSysError(_("Failed to create a temporary file name"));
705 else if ( fileTemp
&& !fileTemp
->IsOpened() )
707 // open the file - of course, there is a race condition here, this is
708 // why we always prefer using mkstemp()...
710 // NB: GetTempFileName() under Windows creates the file, so using
711 // write_excl there would fail
712 if ( !fileTemp
->Open(path
,
713 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
718 wxS_IRUSR
| wxS_IWUSR
) )
720 // FIXME: If !ok here should we loop and try again with another
721 // file name? That is the standard recourse if open(O_EXCL)
722 // fails, though of course it should be protected against
723 // possible infinite looping too.
725 wxLogError(_("Failed to open temporary file."));
734 // ----------------------------------------------------------------------------
735 // directory operations
736 // ----------------------------------------------------------------------------
738 bool wxFileName::Mkdir( int perm
, int flags
)
740 return wxFileName::Mkdir( GetFullPath(), perm
, flags
);
743 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
745 if ( flags
& wxPATH_MKDIR_FULL
)
747 // split the path in components
749 filename
.AssignDir(dir
);
752 if ( filename
.HasVolume())
754 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
757 wxArrayString dirs
= filename
.GetDirs();
758 size_t count
= dirs
.GetCount();
759 for ( size_t i
= 0; i
< count
; i
++ )
761 if ( i
> 0 || filename
.IsAbsolute() )
762 currPath
+= wxFILE_SEP_PATH
;
765 if (!DirExists(currPath
))
767 if (!wxMkdir(currPath
, perm
))
769 // no need to try creating further directories
779 return ::wxMkdir( dir
, perm
);
782 bool wxFileName::Rmdir()
784 return wxFileName::Rmdir( GetFullPath() );
787 bool wxFileName::Rmdir( const wxString
&dir
)
789 return ::wxRmdir( dir
);
792 // ----------------------------------------------------------------------------
793 // path normalization
794 // ----------------------------------------------------------------------------
796 bool wxFileName::Normalize(int flags
,
800 // the existing path components
801 wxArrayString dirs
= GetDirs();
803 // the path to prepend in front to make the path absolute
806 format
= GetFormat(format
);
808 // make the path absolute
809 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
813 curDir
.AssignCwd(GetVolume());
817 curDir
.AssignDir(cwd
);
820 // the path may be not absolute because it doesn't have the volume name
821 // but in this case we shouldn't modify the directory components of it
822 // but just set the current volume
823 if ( !HasVolume() && curDir
.HasVolume() )
825 SetVolume(curDir
.GetVolume());
829 // yes, it was the case - we don't need curDir then
835 // handle ~ stuff under Unix only
836 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
838 if ( !dirs
.IsEmpty() )
840 wxString dir
= dirs
[0u];
841 if ( !dir
.empty() && dir
[0u] == _T('~') )
843 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
850 // transform relative path into abs one
853 wxArrayString dirsNew
= curDir
.GetDirs();
854 size_t count
= dirs
.GetCount();
855 for ( size_t n
= 0; n
< count
; n
++ )
857 dirsNew
.Add(dirs
[n
]);
863 // now deal with ".", ".." and the rest
865 size_t count
= dirs
.GetCount();
866 for ( size_t n
= 0; n
< count
; n
++ )
868 wxString dir
= dirs
[n
];
870 if ( flags
& wxPATH_NORM_DOTS
)
872 if ( dir
== wxT(".") )
878 if ( dir
== wxT("..") )
880 if ( m_dirs
.IsEmpty() )
882 wxLogError(_("The path '%s' contains too many \"..\"!"),
883 GetFullPath().c_str());
887 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
892 if ( flags
& wxPATH_NORM_ENV_VARS
)
894 dir
= wxExpandEnvVars(dir
);
897 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
905 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
907 // VZ: expand env vars here too?
913 #if defined(__WIN32__)
914 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
916 Assign(GetLongPath());
920 // we do have the path now
926 // ----------------------------------------------------------------------------
927 // absolute/relative paths
928 // ----------------------------------------------------------------------------
930 bool wxFileName::IsAbsolute(wxPathFormat format
) const
932 // if our path doesn't start with a path separator, it's not an absolute
937 if ( !GetVolumeSeparator(format
).empty() )
939 // this format has volumes and an absolute path must have one, it's not
940 // enough to have the full path to bean absolute file under Windows
941 if ( GetVolume().empty() )
948 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
950 wxFileName
fnBase(pathBase
, format
);
952 // get cwd only once - small time saving
953 wxString cwd
= wxGetCwd();
954 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
955 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
957 bool withCase
= IsCaseSensitive(format
);
959 // we can't do anything if the files live on different volumes
960 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
966 // same drive, so we don't need our volume
969 // remove common directories starting at the top
970 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
971 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
974 fnBase
.m_dirs
.RemoveAt(0);
977 // add as many ".." as needed
978 size_t count
= fnBase
.m_dirs
.GetCount();
979 for ( size_t i
= 0; i
< count
; i
++ )
981 m_dirs
.Insert(wxT(".."), 0u);
984 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
986 // a directory made relative with respect to itself is '.' under Unix
987 // and DOS, by definition (but we don't have to insert "./" for the
989 if ( m_dirs
.IsEmpty() && IsDir() )
1001 // ----------------------------------------------------------------------------
1002 // filename kind tests
1003 // ----------------------------------------------------------------------------
1005 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
1007 wxFileName fn1
= *this,
1010 // get cwd only once - small time saving
1011 wxString cwd
= wxGetCwd();
1012 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
1013 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
1015 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1018 // TODO: compare inodes for Unix, this works even when filenames are
1019 // different but files are the same (symlinks) (VZ)
1025 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1027 // only Unix filenames are truely case-sensitive
1028 return GetFormat(format
) == wxPATH_UNIX
;
1032 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
1036 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1037 (GetFormat(format
) == wxPATH_VMS
) )
1039 sepVol
= wxFILE_SEP_DSK
;
1047 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1050 switch ( GetFormat(format
) )
1053 // accept both as native APIs do but put the native one first as
1054 // this is the one we use in GetFullPath()
1055 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1059 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
1063 seps
= wxFILE_SEP_PATH_UNIX
;
1067 seps
= wxFILE_SEP_PATH_MAC
;
1071 seps
= wxFILE_SEP_PATH_VMS
;
1079 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1081 // wxString::Find() doesn't work as expected with NUL - it will always find
1082 // it, so it is almost surely a bug if this function is called with NUL arg
1083 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1085 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1088 // ----------------------------------------------------------------------------
1089 // path components manipulation
1090 // ----------------------------------------------------------------------------
1092 void wxFileName::AppendDir( const wxString
&dir
)
1097 void wxFileName::PrependDir( const wxString
&dir
)
1099 m_dirs
.Insert( dir
, 0 );
1102 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1104 m_dirs
.Insert( dir
, before
);
1107 void wxFileName::RemoveDir( int pos
)
1109 m_dirs
.Remove( (size_t)pos
);
1112 // ----------------------------------------------------------------------------
1114 // ----------------------------------------------------------------------------
1116 void wxFileName::SetFullName(const wxString
& fullname
)
1118 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1121 wxString
wxFileName::GetFullName() const
1123 wxString fullname
= m_name
;
1124 if ( !m_ext
.empty() )
1126 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1132 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1134 format
= GetFormat( format
);
1138 // return the volume with the path as well if requested
1139 if ( flags
& wxPATH_GET_VOLUME
)
1141 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1144 // the leading character
1145 if ( format
== wxPATH_MAC
)
1148 fullpath
+= wxFILE_SEP_PATH_MAC
;
1150 else if ( format
== wxPATH_DOS
)
1153 fullpath
+= wxFILE_SEP_PATH_DOS
;
1155 else if ( format
== wxPATH_UNIX
)
1158 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1161 // then concatenate all the path components using the path separator
1162 size_t dirCount
= m_dirs
.GetCount();
1165 if ( format
== wxPATH_VMS
)
1167 fullpath
+= wxT('[');
1170 for ( size_t i
= 0; i
< dirCount
; i
++ )
1172 // TODO: What to do with ".." under VMS
1178 if (m_dirs
[i
] == wxT("."))
1180 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1181 fullpath
+= m_dirs
[i
];
1182 fullpath
+= wxT(':');
1187 fullpath
+= m_dirs
[i
];
1188 fullpath
+= wxT('\\');
1193 fullpath
+= m_dirs
[i
];
1194 fullpath
+= wxT('/');
1199 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1200 fullpath
+= m_dirs
[i
];
1201 if (i
== dirCount
-1)
1202 fullpath
+= wxT(']');
1204 fullpath
+= wxT('.');
1209 wxFAIL_MSG( wxT("error") );
1215 if ( (flags
& wxPATH_GET_SEPARATOR
) && !fullpath
.empty() )
1217 fullpath
+= GetPathSeparator(format
);
1223 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1225 format
= GetFormat(format
);
1227 // first put the volume
1228 wxString fullpath
= wxGetVolumeString(m_volume
, format
);
1230 // the leading character
1231 if ( format
== wxPATH_MAC
)
1234 fullpath
+= wxFILE_SEP_PATH_MAC
;
1236 else if ( format
== wxPATH_DOS
)
1239 fullpath
+= wxFILE_SEP_PATH_DOS
;
1241 else if ( format
== wxPATH_UNIX
)
1245 // normally the absolute file names starts with a slash with one
1246 // exception: file names like "~/foo.bar" don't have it
1247 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1249 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1254 // then concatenate all the path components using the path separator
1255 size_t dirCount
= m_dirs
.GetCount();
1258 if ( format
== wxPATH_VMS
)
1260 fullpath
+= wxT('[');
1264 for ( size_t i
= 0; i
< dirCount
; i
++ )
1266 // TODO: What to do with ".." under VMS
1272 if (m_dirs
[i
] == wxT("."))
1274 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1275 fullpath
+= m_dirs
[i
];
1276 fullpath
+= wxT(':');
1281 fullpath
+= m_dirs
[i
];
1282 fullpath
+= wxT('\\');
1287 fullpath
+= m_dirs
[i
];
1288 fullpath
+= wxT('/');
1293 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1294 fullpath
+= m_dirs
[i
];
1295 if (i
== dirCount
-1)
1296 fullpath
+= wxT(']');
1298 fullpath
+= wxT('.');
1303 wxFAIL_MSG( wxT("error") );
1309 // finally add the file name and extension
1310 fullpath
+= GetFullName();
1315 // Return the short form of the path (returns identity on non-Windows platforms)
1316 wxString
wxFileName::GetShortPath() const
1318 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1319 wxString
path(GetFullPath());
1321 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1325 ok
= ::GetShortPathName
1328 pathOut
.GetWriteBuf(sz
),
1331 pathOut
.UngetWriteBuf();
1338 return GetFullPath();
1342 // Return the long form of the path (returns identity on non-Windows platforms)
1343 wxString
wxFileName::GetLongPath() const
1346 path
= GetFullPath();
1348 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1349 bool success
= FALSE
;
1351 #if wxUSE_DYNAMIC_LOADER
1352 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1354 static bool s_triedToLoad
= FALSE
;
1356 if ( !s_triedToLoad
)
1358 s_triedToLoad
= TRUE
;
1359 wxDynamicLibrary
dllKernel(_T("kernel32"));
1360 if ( dllKernel
.IsLoaded() )
1362 // may succeed or fail depending on the Windows version
1363 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1365 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1367 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1370 if ( s_pfnGetLongPathName
)
1372 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1373 bool ok
= dwSize
> 0;
1377 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1381 ok
= (*s_pfnGetLongPathName
)
1384 pathOut
.GetWriteBuf(sz
),
1387 pathOut
.UngetWriteBuf();
1397 #endif // wxUSE_DYNAMIC_LOADER
1401 // The OS didn't support GetLongPathName, or some other error.
1402 // We need to call FindFirstFile on each component in turn.
1404 WIN32_FIND_DATA findFileData
;
1406 pathOut
= wxEmptyString
;
1408 wxArrayString dirs
= GetDirs();
1409 dirs
.Add(GetFullName());
1413 size_t count
= dirs
.GetCount();
1414 for ( size_t i
= 0; i
< count
; i
++ )
1416 // We're using pathOut to collect the long-name path, but using a
1417 // temporary for appending the last path component which may be
1419 tmpPath
= pathOut
+ dirs
[i
];
1421 if ( tmpPath
.empty() )
1424 if ( tmpPath
.Last() == wxT(':') )
1426 // Can't pass a drive and root dir to FindFirstFile,
1427 // so continue to next dir
1428 tmpPath
+= wxFILE_SEP_PATH
;
1433 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1434 if (hFind
== INVALID_HANDLE_VALUE
)
1436 // Error: return immediately with the original path
1440 pathOut
+= findFileData
.cFileName
;
1441 if ( (i
< (count
-1)) )
1442 pathOut
+= wxFILE_SEP_PATH
;
1449 #endif // Win32/!Win32
1454 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1456 if (format
== wxPATH_NATIVE
)
1458 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1459 format
= wxPATH_DOS
;
1460 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1461 format
= wxPATH_MAC
;
1462 #elif defined(__VMS)
1463 format
= wxPATH_VMS
;
1465 format
= wxPATH_UNIX
;
1471 // ----------------------------------------------------------------------------
1472 // path splitting function
1473 // ----------------------------------------------------------------------------
1476 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1477 wxString
*pstrVolume
,
1481 wxPathFormat format
)
1483 format
= GetFormat(format
);
1485 wxString fullpath
= fullpathWithVolume
;
1487 // under VMS the end of the path is ']', not the path separator used to
1488 // separate the components
1489 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1490 : GetPathSeparators(format
);
1492 // special Windows UNC paths hack: transform \\share\path into share:path
1493 if ( format
== wxPATH_DOS
)
1495 if ( fullpath
.length() >= 4 &&
1496 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1497 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1499 fullpath
.erase(0, 2);
1501 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1502 if ( posFirstSlash
!= wxString::npos
)
1504 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1506 // UNC paths are always absolute, right? (FIXME)
1507 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1512 // We separate the volume here
1513 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1515 wxString sepVol
= GetVolumeSeparator(format
);
1517 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1518 if ( posFirstColon
!= wxString::npos
)
1522 *pstrVolume
= fullpath
.Left(posFirstColon
);
1525 // remove the volume name and the separator from the full path
1526 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1530 // find the positions of the last dot and last path separator in the path
1531 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1532 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1534 if ( (posLastDot
!= wxString::npos
) &&
1535 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1537 if ( (posLastDot
== 0) ||
1538 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1540 // under Unix and VMS, dot may be (and commonly is) the first
1541 // character of the filename, don't treat the entire filename as
1542 // extension in this case
1543 posLastDot
= wxString::npos
;
1547 // if we do have a dot and a slash, check that the dot is in the name part
1548 if ( (posLastDot
!= wxString::npos
) &&
1549 (posLastSlash
!= wxString::npos
) &&
1550 (posLastDot
< posLastSlash
) )
1552 // the dot is part of the path, not the start of the extension
1553 posLastDot
= wxString::npos
;
1556 // now fill in the variables provided by user
1559 if ( posLastSlash
== wxString::npos
)
1566 // take everything up to the path separator but take care to make
1567 // the path equal to something like '/', not empty, for the files
1568 // immediately under root directory
1569 size_t len
= posLastSlash
;
1571 // this rule does not apply to mac since we do not start with colons (sep)
1572 // except for relative paths
1573 if ( !len
&& format
!= wxPATH_MAC
)
1576 *pstrPath
= fullpath
.Left(len
);
1578 // special VMS hack: remove the initial bracket
1579 if ( format
== wxPATH_VMS
)
1581 if ( (*pstrPath
)[0u] == _T('[') )
1582 pstrPath
->erase(0, 1);
1589 // take all characters starting from the one after the last slash and
1590 // up to, but excluding, the last dot
1591 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1593 if ( posLastDot
== wxString::npos
)
1595 // take all until the end
1596 count
= wxString::npos
;
1598 else if ( posLastSlash
== wxString::npos
)
1602 else // have both dot and slash
1604 count
= posLastDot
- posLastSlash
- 1;
1607 *pstrName
= fullpath
.Mid(nStart
, count
);
1612 if ( posLastDot
== wxString::npos
)
1619 // take everything after the dot
1620 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1626 void wxFileName::SplitPath(const wxString
& fullpath
,
1630 wxPathFormat format
)
1633 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1637 path
->Prepend(wxGetVolumeString(volume
, format
));
1641 // ----------------------------------------------------------------------------
1643 // ----------------------------------------------------------------------------
1645 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1646 const wxDateTime
*dtMod
,
1647 const wxDateTime
*dtCreate
)
1649 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1650 if ( !dtAccess
&& !dtMod
)
1652 // can't modify the creation time anyhow, don't try
1656 // if dtAccess or dtMod is not specified, use the other one (which must be
1657 // non NULL because of the test above) for both times
1659 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1660 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1661 if ( utime(GetFullPath(), &utm
) == 0 )
1665 #elif defined(__WIN32__)
1666 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1669 FILETIME ftAccess
, ftCreate
, ftWrite
;
1672 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1674 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1676 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1678 if ( ::SetFileTime(fh
,
1679 dtCreate
? &ftCreate
: NULL
,
1680 dtAccess
? &ftAccess
: NULL
,
1681 dtMod
? &ftWrite
: NULL
) )
1686 #else // other platform
1689 wxLogSysError(_("Failed to modify file times for '%s'"),
1690 GetFullPath().c_str());
1695 bool wxFileName::Touch()
1697 #if defined(__UNIX_LIKE__)
1698 // under Unix touching file is simple: just pass NULL to utime()
1699 if ( utime(GetFullPath(), NULL
) == 0 )
1704 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1707 #else // other platform
1708 wxDateTime dtNow
= wxDateTime::Now();
1710 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1714 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1716 wxDateTime
*dtCreate
) const
1718 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1720 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1723 dtAccess
->Set(stBuf
.st_atime
);
1725 dtMod
->Set(stBuf
.st_mtime
);
1727 dtCreate
->Set(stBuf
.st_ctime
);
1731 #elif defined(__WIN32__)
1732 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1735 FILETIME ftAccess
, ftCreate
, ftWrite
;
1737 if ( ::GetFileTime(fh
,
1738 dtMod
? &ftCreate
: NULL
,
1739 dtAccess
? &ftAccess
: NULL
,
1740 dtCreate
? &ftWrite
: NULL
) )
1743 ConvertFileTimeToWx(dtMod
, ftCreate
);
1745 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1747 ConvertFileTimeToWx(dtCreate
, ftWrite
);
1752 #else // other platform
1755 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1756 GetFullPath().c_str());
1763 const short kMacExtensionMaxLength
= 16 ;
1766 char m_ext
[kMacExtensionMaxLength
] ;
1769 } MacDefaultExtensionRecord
;
1771 #include "wx/dynarray.h"
1772 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1773 #include "wx/arrimpl.cpp"
1774 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray
) ;
1776 MacDefaultExtensionArray gMacDefaultExtensions
;
1777 bool gMacDefaultExtensionsInited
= false ;
1779 static void MacEnsureDefaultExtensionsLoaded()
1781 if ( !gMacDefaultExtensionsInited
)
1783 // load the default extensions
1784 MacDefaultExtensionRecord defaults
[] =
1786 { "txt" , 'TEXT' , 'ttxt' } ,
1789 // we could load the pc exchange prefs here too
1791 for ( int i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1793 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1795 gMacDefaultExtensionsInited
= true ;
1798 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1802 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1803 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1804 wxCHECK( err
== noErr
, false ) ;
1806 fndrInfo
.fdType
= type
;
1807 fndrInfo
.fdCreator
= creator
;
1808 FSpSetFInfo( &spec
, &fndrInfo
) ;
1812 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1816 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1817 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1818 wxCHECK( err
== noErr
, false ) ;
1820 *type
= fndrInfo
.fdType
;
1821 *creator
= fndrInfo
.fdCreator
;
1825 bool wxFileName::MacSetDefaultTypeAndCreator()
1827 wxUint32 type
, creator
;
1828 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1831 return MacSetTypeAndCreator( type
, creator
) ;
1836 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1838 MacEnsureDefaultExtensionsLoaded() ;
1839 wxString extl
= ext
.Lower() ;
1840 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1842 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1844 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1845 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1852 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1854 MacEnsureDefaultExtensionsLoaded() ;
1855 MacDefaultExtensionRecord rec
;
1857 rec
.m_creator
= creator
;
1858 strncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1859 gMacDefaultExtensions
.Add( rec
) ;