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
+= GetPathSeparators(format
)[0u];
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
, bool full
)
740 return wxFileName::Mkdir( GetFullPath(), perm
, full
);
743 bool wxFileName::Mkdir( const wxString
&dir
, int perm
, bool full
)
747 wxFileName
filename(dir
);
748 wxArrayString dirs
= filename
.GetDirs();
749 dirs
.Add(filename
.GetName());
751 size_t count
= dirs
.GetCount();
755 for ( i
= 0; i
< count
; i
++ )
759 if (currPath
.Last() == wxT(':'))
761 // Can't create a root directory so continue to next dir
762 currPath
+= wxFILE_SEP_PATH
;
766 if (!DirExists(currPath
))
767 if (!wxMkdir(currPath
, perm
))
770 if ( (i
< (count
-1)) )
771 currPath
+= wxFILE_SEP_PATH
;
774 return (noErrors
== 0);
778 return ::wxMkdir( dir
, perm
);
781 bool wxFileName::Rmdir()
783 return wxFileName::Rmdir( GetFullPath() );
786 bool wxFileName::Rmdir( const wxString
&dir
)
788 return ::wxRmdir( dir
);
791 // ----------------------------------------------------------------------------
792 // path normalization
793 // ----------------------------------------------------------------------------
795 bool wxFileName::Normalize(int flags
,
799 // the existing path components
800 wxArrayString dirs
= GetDirs();
802 // the path to prepend in front to make the path absolute
805 format
= GetFormat(format
);
807 // make the path absolute
808 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
812 curDir
.AssignCwd(GetVolume());
816 curDir
.AssignDir(cwd
);
819 // the path may be not absolute because it doesn't have the volume name
820 // but in this case we shouldn't modify the directory components of it
821 // but just set the current volume
822 if ( !HasVolume() && curDir
.HasVolume() )
824 SetVolume(curDir
.GetVolume());
828 // yes, it was the case - we don't need curDir then
834 // handle ~ stuff under Unix only
835 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
837 if ( !dirs
.IsEmpty() )
839 wxString dir
= dirs
[0u];
840 if ( !dir
.empty() && dir
[0u] == _T('~') )
842 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
849 // transform relative path into abs one
852 wxArrayString dirsNew
= curDir
.GetDirs();
853 size_t count
= dirs
.GetCount();
854 for ( size_t n
= 0; n
< count
; n
++ )
856 dirsNew
.Add(dirs
[n
]);
862 // now deal with ".", ".." and the rest
864 size_t count
= dirs
.GetCount();
865 for ( size_t n
= 0; n
< count
; n
++ )
867 wxString dir
= dirs
[n
];
869 if ( flags
& wxPATH_NORM_DOTS
)
871 if ( dir
== wxT(".") )
877 if ( dir
== wxT("..") )
879 if ( m_dirs
.IsEmpty() )
881 wxLogError(_("The path '%s' contains too many \"..\"!"),
882 GetFullPath().c_str());
886 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
891 if ( flags
& wxPATH_NORM_ENV_VARS
)
893 dir
= wxExpandEnvVars(dir
);
896 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
904 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
906 // VZ: expand env vars here too?
912 #if defined(__WIN32__)
913 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
915 Assign(GetLongPath());
919 // we do have the path now
925 // ----------------------------------------------------------------------------
926 // absolute/relative paths
927 // ----------------------------------------------------------------------------
929 bool wxFileName::IsAbsolute(wxPathFormat format
) const
931 // if our path doesn't start with a path separator, it's not an absolute
936 if ( !GetVolumeSeparator(format
).empty() )
938 // this format has volumes and an absolute path must have one, it's not
939 // enough to have the full path to bean absolute file under Windows
940 if ( GetVolume().empty() )
947 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
949 wxFileName
fnBase(pathBase
, format
);
951 // get cwd only once - small time saving
952 wxString cwd
= wxGetCwd();
953 Normalize(wxPATH_NORM_ALL
, cwd
, format
);
954 fnBase
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
956 bool withCase
= IsCaseSensitive(format
);
958 // we can't do anything if the files live on different volumes
959 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
965 // same drive, so we don't need our volume
968 // remove common directories starting at the top
969 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
970 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
973 fnBase
.m_dirs
.RemoveAt(0);
976 // add as many ".." as needed
977 size_t count
= fnBase
.m_dirs
.GetCount();
978 for ( size_t i
= 0; i
< count
; i
++ )
980 m_dirs
.Insert(wxT(".."), 0u);
983 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
985 // a directory made relative with respect to itself is '.' under Unix
986 // and DOS, by definition (but we don't have to insert "./" for the
988 if ( m_dirs
.IsEmpty() && IsDir() )
1000 // ----------------------------------------------------------------------------
1001 // filename kind tests
1002 // ----------------------------------------------------------------------------
1004 bool wxFileName::SameAs(const wxFileName
&filepath
, wxPathFormat format
)
1006 wxFileName fn1
= *this,
1009 // get cwd only once - small time saving
1010 wxString cwd
= wxGetCwd();
1011 fn1
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
1012 fn2
.Normalize(wxPATH_NORM_ALL
, cwd
, format
);
1014 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1017 // TODO: compare inodes for Unix, this works even when filenames are
1018 // different but files are the same (symlinks) (VZ)
1024 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1026 // only Unix filenames are truely case-sensitive
1027 return GetFormat(format
) == wxPATH_UNIX
;
1031 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
1035 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1036 (GetFormat(format
) == wxPATH_VMS
) )
1038 sepVol
= wxFILE_SEP_DSK
;
1046 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1049 switch ( GetFormat(format
) )
1052 // accept both as native APIs do but put the native one first as
1053 // this is the one we use in GetFullPath()
1054 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1058 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
1062 seps
= wxFILE_SEP_PATH_UNIX
;
1066 seps
= wxFILE_SEP_PATH_MAC
;
1070 seps
= wxFILE_SEP_PATH_VMS
;
1078 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1080 // wxString::Find() doesn't work as expected with NUL - it will always find
1081 // it, so it is almost surely a bug if this function is called with NUL arg
1082 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1084 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1087 // ----------------------------------------------------------------------------
1088 // path components manipulation
1089 // ----------------------------------------------------------------------------
1091 void wxFileName::AppendDir( const wxString
&dir
)
1096 void wxFileName::PrependDir( const wxString
&dir
)
1098 m_dirs
.Insert( dir
, 0 );
1101 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1103 m_dirs
.Insert( dir
, before
);
1106 void wxFileName::RemoveDir( int pos
)
1108 m_dirs
.Remove( (size_t)pos
);
1111 // ----------------------------------------------------------------------------
1113 // ----------------------------------------------------------------------------
1115 void wxFileName::SetFullName(const wxString
& fullname
)
1117 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1120 wxString
wxFileName::GetFullName() const
1122 wxString fullname
= m_name
;
1123 if ( !m_ext
.empty() )
1125 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1131 wxString
wxFileName::GetPath( bool add_separator
, wxPathFormat format
) const
1133 format
= GetFormat( format
);
1137 // the leading character
1138 if ( format
== wxPATH_MAC
&& m_relative
)
1140 fullpath
+= wxFILE_SEP_PATH_MAC
;
1142 else if ( format
== wxPATH_DOS
)
1145 fullpath
+= wxFILE_SEP_PATH_DOS
;
1147 else if ( format
== wxPATH_UNIX
)
1150 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1153 // then concatenate all the path components using the path separator
1154 size_t dirCount
= m_dirs
.GetCount();
1157 if ( format
== wxPATH_VMS
)
1159 fullpath
+= wxT('[');
1163 for ( size_t i
= 0; i
< dirCount
; i
++ )
1165 // TODO: What to do with ".." under VMS
1171 if (m_dirs
[i
] == wxT("."))
1173 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1174 fullpath
+= m_dirs
[i
];
1175 fullpath
+= wxT(':');
1180 fullpath
+= m_dirs
[i
];
1181 fullpath
+= wxT('\\');
1186 fullpath
+= m_dirs
[i
];
1187 fullpath
+= wxT('/');
1192 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1193 fullpath
+= m_dirs
[i
];
1194 if (i
== dirCount
-1)
1195 fullpath
+= wxT(']');
1197 fullpath
+= wxT('.');
1202 wxFAIL_MSG( wxT("error") );
1208 if ( add_separator
&& !fullpath
.empty() )
1210 fullpath
+= GetPathSeparators(format
)[0u];
1216 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1218 format
= GetFormat(format
);
1220 // first put the volume
1221 wxString fullpath
= wxGetVolumeString(m_volume
, format
);
1223 // the leading character
1224 if ( format
== wxPATH_MAC
)
1227 fullpath
+= wxFILE_SEP_PATH_MAC
;
1229 else if ( format
== wxPATH_DOS
)
1232 fullpath
+= wxFILE_SEP_PATH_DOS
;
1234 else if ( format
== wxPATH_UNIX
)
1238 // normally the absolute file names starts with a slash with one
1239 // exception: file names like "~/foo.bar" don't have it
1240 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1242 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1247 // then concatenate all the path components using the path separator
1248 size_t dirCount
= m_dirs
.GetCount();
1251 if ( format
== wxPATH_VMS
)
1253 fullpath
+= wxT('[');
1257 for ( size_t i
= 0; i
< dirCount
; i
++ )
1259 // TODO: What to do with ".." under VMS
1265 if (m_dirs
[i
] == wxT("."))
1267 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1268 fullpath
+= m_dirs
[i
];
1269 fullpath
+= wxT(':');
1274 fullpath
+= m_dirs
[i
];
1275 fullpath
+= wxT('\\');
1280 fullpath
+= m_dirs
[i
];
1281 fullpath
+= wxT('/');
1286 if (m_dirs
[i
] != wxT("..")) // convert back from ".." to nothing
1287 fullpath
+= m_dirs
[i
];
1288 if (i
== dirCount
-1)
1289 fullpath
+= wxT(']');
1291 fullpath
+= wxT('.');
1296 wxFAIL_MSG( wxT("error") );
1302 // finally add the file name and extension
1303 fullpath
+= GetFullName();
1308 // Return the short form of the path (returns identity on non-Windows platforms)
1309 wxString
wxFileName::GetShortPath() const
1311 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
1312 wxString
path(GetFullPath());
1314 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1318 ok
= ::GetShortPathName
1321 pathOut
.GetWriteBuf(sz
),
1324 pathOut
.UngetWriteBuf();
1331 return GetFullPath();
1335 // Return the long form of the path (returns identity on non-Windows platforms)
1336 wxString
wxFileName::GetLongPath() const
1339 path
= GetFullPath();
1341 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1342 bool success
= FALSE
;
1344 #if wxUSE_DYNAMIC_LOADER
1345 typedef DWORD (*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1347 static bool s_triedToLoad
= FALSE
;
1349 if ( !s_triedToLoad
)
1351 s_triedToLoad
= TRUE
;
1352 wxDynamicLibrary
dllKernel(_T("kernel32"));
1353 if ( dllKernel
.IsLoaded() )
1355 // may succeed or fail depending on the Windows version
1356 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1358 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1360 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1363 if ( s_pfnGetLongPathName
)
1365 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1366 bool ok
= dwSize
> 0;
1370 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1374 ok
= (*s_pfnGetLongPathName
)
1377 pathOut
.GetWriteBuf(sz
),
1380 pathOut
.UngetWriteBuf();
1390 #endif // wxUSE_DYNAMIC_LOADER
1394 // The OS didn't support GetLongPathName, or some other error.
1395 // We need to call FindFirstFile on each component in turn.
1397 WIN32_FIND_DATA findFileData
;
1399 pathOut
= wxEmptyString
;
1401 wxArrayString dirs
= GetDirs();
1402 dirs
.Add(GetFullName());
1406 size_t count
= dirs
.GetCount();
1407 for ( size_t i
= 0; i
< count
; i
++ )
1409 // We're using pathOut to collect the long-name path, but using a
1410 // temporary for appending the last path component which may be
1412 tmpPath
= pathOut
+ dirs
[i
];
1414 if ( tmpPath
.empty() )
1417 if ( tmpPath
.Last() == wxT(':') )
1419 // Can't pass a drive and root dir to FindFirstFile,
1420 // so continue to next dir
1421 tmpPath
+= wxFILE_SEP_PATH
;
1426 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1427 if (hFind
== INVALID_HANDLE_VALUE
)
1429 // Error: return immediately with the original path
1433 pathOut
+= findFileData
.cFileName
;
1434 if ( (i
< (count
-1)) )
1435 pathOut
+= wxFILE_SEP_PATH
;
1442 #endif // Win32/!Win32
1447 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1449 if (format
== wxPATH_NATIVE
)
1451 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1452 format
= wxPATH_DOS
;
1453 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1454 format
= wxPATH_MAC
;
1455 #elif defined(__VMS)
1456 format
= wxPATH_VMS
;
1458 format
= wxPATH_UNIX
;
1464 // ----------------------------------------------------------------------------
1465 // path splitting function
1466 // ----------------------------------------------------------------------------
1469 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1470 wxString
*pstrVolume
,
1474 wxPathFormat format
)
1476 format
= GetFormat(format
);
1478 wxString fullpath
= fullpathWithVolume
;
1480 // under VMS the end of the path is ']', not the path separator used to
1481 // separate the components
1482 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1483 : GetPathSeparators(format
);
1485 // special Windows UNC paths hack: transform \\share\path into share:path
1486 if ( format
== wxPATH_DOS
)
1488 if ( fullpath
.length() >= 4 &&
1489 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1490 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1492 fullpath
.erase(0, 2);
1494 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1495 if ( posFirstSlash
!= wxString::npos
)
1497 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1499 // UNC paths are always absolute, right? (FIXME)
1500 fullpath
.insert(posFirstSlash
+ 1, wxFILE_SEP_PATH_DOS
);
1505 // We separate the volume here
1506 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1508 wxString sepVol
= GetVolumeSeparator(format
);
1510 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1511 if ( posFirstColon
!= wxString::npos
)
1515 *pstrVolume
= fullpath
.Left(posFirstColon
);
1518 // remove the volume name and the separator from the full path
1519 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1523 // find the positions of the last dot and last path separator in the path
1524 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1525 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1527 if ( (posLastDot
!= wxString::npos
) &&
1528 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1530 if ( (posLastDot
== 0) ||
1531 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1533 // under Unix and VMS, dot may be (and commonly is) the first
1534 // character of the filename, don't treat the entire filename as
1535 // extension in this case
1536 posLastDot
= wxString::npos
;
1540 // if we do have a dot and a slash, check that the dot is in the name part
1541 if ( (posLastDot
!= wxString::npos
) &&
1542 (posLastSlash
!= wxString::npos
) &&
1543 (posLastDot
< posLastSlash
) )
1545 // the dot is part of the path, not the start of the extension
1546 posLastDot
= wxString::npos
;
1549 // now fill in the variables provided by user
1552 if ( posLastSlash
== wxString::npos
)
1559 // take everything up to the path separator but take care to make
1560 // the path equal to something like '/', not empty, for the files
1561 // immediately under root directory
1562 size_t len
= posLastSlash
;
1564 // this rule does not apply to mac since we do not start with colons (sep)
1565 // except for relative paths
1566 if ( !len
&& format
!= wxPATH_MAC
)
1569 *pstrPath
= fullpath
.Left(len
);
1571 // special VMS hack: remove the initial bracket
1572 if ( format
== wxPATH_VMS
)
1574 if ( (*pstrPath
)[0u] == _T('[') )
1575 pstrPath
->erase(0, 1);
1582 // take all characters starting from the one after the last slash and
1583 // up to, but excluding, the last dot
1584 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1586 if ( posLastDot
== wxString::npos
)
1588 // take all until the end
1589 count
= wxString::npos
;
1591 else if ( posLastSlash
== wxString::npos
)
1595 else // have both dot and slash
1597 count
= posLastDot
- posLastSlash
- 1;
1600 *pstrName
= fullpath
.Mid(nStart
, count
);
1605 if ( posLastDot
== wxString::npos
)
1612 // take everything after the dot
1613 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1619 void wxFileName::SplitPath(const wxString
& fullpath
,
1623 wxPathFormat format
)
1626 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1630 path
->Prepend(wxGetVolumeString(volume
, format
));
1634 // ----------------------------------------------------------------------------
1636 // ----------------------------------------------------------------------------
1638 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1639 const wxDateTime
*dtMod
,
1640 const wxDateTime
*dtCreate
)
1642 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1643 if ( !dtAccess
&& !dtMod
)
1645 // can't modify the creation time anyhow, don't try
1649 // if dtAccess or dtMod is not specified, use the other one (which must be
1650 // non NULL because of the test above) for both times
1652 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1653 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1654 if ( utime(GetFullPath(), &utm
) == 0 )
1658 #elif defined(__WIN32__)
1659 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1662 FILETIME ftAccess
, ftCreate
, ftWrite
;
1665 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1667 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1669 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1671 if ( ::SetFileTime(fh
,
1672 dtCreate
? &ftCreate
: NULL
,
1673 dtAccess
? &ftAccess
: NULL
,
1674 dtMod
? &ftWrite
: NULL
) )
1679 #else // other platform
1682 wxLogSysError(_("Failed to modify file times for '%s'"),
1683 GetFullPath().c_str());
1688 bool wxFileName::Touch()
1690 #if defined(__UNIX_LIKE__)
1691 // under Unix touching file is simple: just pass NULL to utime()
1692 if ( utime(GetFullPath(), NULL
) == 0 )
1697 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1700 #else // other platform
1701 wxDateTime dtNow
= wxDateTime::Now();
1703 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1707 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1709 wxDateTime
*dtCreate
) const
1711 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1713 if ( wxStat(GetFullPath(), &stBuf
) == 0 )
1716 dtAccess
->Set(stBuf
.st_atime
);
1718 dtMod
->Set(stBuf
.st_mtime
);
1720 dtCreate
->Set(stBuf
.st_ctime
);
1724 #elif defined(__WIN32__)
1725 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1728 FILETIME ftAccess
, ftCreate
, ftWrite
;
1730 if ( ::GetFileTime(fh
,
1731 dtMod
? &ftCreate
: NULL
,
1732 dtAccess
? &ftAccess
: NULL
,
1733 dtCreate
? &ftWrite
: NULL
) )
1736 ConvertFileTimeToWx(dtMod
, ftCreate
);
1738 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1740 ConvertFileTimeToWx(dtCreate
, ftWrite
);
1745 #else // other platform
1748 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1749 GetFullPath().c_str());
1756 const short kMacExtensionMaxLength
= 16 ;
1759 char m_ext
[kMacExtensionMaxLength
] ;
1762 } MacDefaultExtensionRecord
;
1764 #include "wx/dynarray.h"
1765 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1766 #include "wx/arrimpl.cpp"
1767 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray
) ;
1769 MacDefaultExtensionArray gMacDefaultExtensions
;
1770 bool gMacDefaultExtensionsInited
= false ;
1772 static void MacEnsureDefaultExtensionsLoaded()
1774 if ( !gMacDefaultExtensionsInited
)
1776 // load the default extensions
1777 MacDefaultExtensionRecord defaults
[] =
1779 { "txt" , 'TEXT' , 'ttxt' } ,
1782 // we could load the pc exchange prefs here too
1784 for ( int i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1786 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1788 gMacDefaultExtensionsInited
= true ;
1791 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1795 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1796 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1797 wxCHECK( err
== noErr
, false ) ;
1799 fndrInfo
.fdType
= type
;
1800 fndrInfo
.fdCreator
= creator
;
1801 FSpSetFInfo( &spec
, &fndrInfo
) ;
1805 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1809 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1810 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1811 wxCHECK( err
== noErr
, false ) ;
1813 *type
= fndrInfo
.fdType
;
1814 *creator
= fndrInfo
.fdCreator
;
1818 bool wxFileName::MacSetDefaultTypeAndCreator()
1820 wxUint32 type
, creator
;
1821 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1824 return MacSetTypeAndCreator( type
, creator
) ;
1829 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1831 MacEnsureDefaultExtensionsLoaded() ;
1832 wxString extl
= ext
.Lower() ;
1833 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1835 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1837 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1838 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1845 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1847 MacEnsureDefaultExtensionsLoaded() ;
1848 MacDefaultExtensionRecord rec
;
1850 rec
.m_creator
= creator
;
1851 strncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1852 gMacDefaultExtensions
.Add( rec
) ;