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 // ----------------------------------------------------------------------------
63 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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
89 #include "wx/msw/wrapwin.h"
93 #include "wx/msw/private.h"
96 #if defined(__WXMAC__)
97 #include "wx/mac/private.h" // includes mac headers
100 // utime() is POSIX so should normally be available on all Unices
102 #include <sys/types.h>
104 #include <sys/stat.h>
114 #include <sys/types.h>
116 #include <sys/stat.h>
127 #include <sys/utime.h>
128 #include <sys/stat.h>
138 #define MAX_PATH _MAX_PATH
141 // ----------------------------------------------------------------------------
143 // ----------------------------------------------------------------------------
145 // small helper class which opens and closes the file - we use it just to get
146 // a file handle for the given file name to pass it to some Win32 API function
147 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
158 wxFileHandle(const wxString
& filename
, OpenMode mode
)
160 m_hFile
= ::CreateFile
163 mode
== Read
? GENERIC_READ
// access mask
166 NULL
, // no secutity attr
167 OPEN_EXISTING
, // creation disposition
169 NULL
// no template file
172 if ( m_hFile
== INVALID_HANDLE_VALUE
)
174 wxLogSysError(_("Failed to open '%s' for %s"),
176 mode
== Read
? _("reading") : _("writing"));
182 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
184 if ( !::CloseHandle(m_hFile
) )
186 wxLogSysError(_("Failed to close file handle"));
191 // return true only if the file could be opened successfully
192 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
195 operator HANDLE() const { return m_hFile
; }
203 // ----------------------------------------------------------------------------
205 // ----------------------------------------------------------------------------
207 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
209 // convert between wxDateTime and FILETIME which is a 64-bit value representing
210 // the number of 100-nanosecond intervals since January 1, 1601.
212 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
214 FILETIME ftcopy
= ft
;
216 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
218 wxLogLastError(_T("FileTimeToLocalFileTime"));
222 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
224 wxLogLastError(_T("FileTimeToSystemTime"));
227 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
228 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
231 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
234 st
.wDay
= dt
.GetDay();
235 st
.wMonth
= dt
.GetMonth() + 1;
236 st
.wYear
= dt
.GetYear();
237 st
.wHour
= dt
.GetHour();
238 st
.wMinute
= dt
.GetMinute();
239 st
.wSecond
= dt
.GetSecond();
240 st
.wMilliseconds
= dt
.GetMillisecond();
243 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
245 wxLogLastError(_T("SystemTimeToFileTime"));
248 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
250 wxLogLastError(_T("LocalFileTimeToFileTime"));
254 #endif // wxUSE_DATETIME && __WIN32__
256 // return a string with the volume par
257 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
261 if ( !volume
.empty() )
263 format
= wxFileName::GetFormat(format
);
265 // Special Windows UNC paths hack, part 2: undo what we did in
266 // SplitPath() and make an UNC path if we have a drive which is not a
267 // single letter (hopefully the network shares can't be one letter only
268 // although I didn't find any authoritative docs on this)
269 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
271 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
273 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
275 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
283 // ============================================================================
285 // ============================================================================
287 // ----------------------------------------------------------------------------
288 // wxFileName construction
289 // ----------------------------------------------------------------------------
291 void wxFileName::Assign( const wxFileName
&filepath
)
293 m_volume
= filepath
.GetVolume();
294 m_dirs
= filepath
.GetDirs();
295 m_name
= filepath
.GetName();
296 m_ext
= filepath
.GetExt();
297 m_relative
= filepath
.m_relative
;
300 void wxFileName::Assign(const wxString
& volume
,
301 const wxString
& path
,
302 const wxString
& name
,
304 wxPathFormat format
)
306 SetPath( path
, format
);
313 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
319 wxPathFormat my_format
= GetFormat( format
);
320 wxString my_path
= path
;
322 // 1) Determine if the path is relative or absolute.
323 wxChar leadingChar
= my_path
[0u];
328 m_relative
= leadingChar
== wxT(':');
330 // We then remove a leading ":". The reason is in our
331 // storage form for relative paths:
332 // ":dir:file.txt" actually means "./dir/file.txt" in
333 // DOS notation and should get stored as
334 // (relative) (dir) (file.txt)
335 // "::dir:file.txt" actually means "../dir/file.txt"
336 // stored as (relative) (..) (dir) (file.txt)
337 // This is important only for the Mac as an empty dir
338 // actually means <UP>, whereas under DOS, double
339 // slashes can be ignored: "\\\\" is the same as "\\".
341 my_path
.erase( 0, 1 );
345 // TODO: what is the relative path format here?
350 wxFAIL_MSG( _T("Unknown path format") );
351 // !! Fall through !!
354 // the paths of the form "~" or "~username" are absolute
355 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
359 m_relative
= !IsPathSeparator(leadingChar
, my_format
);
364 // 2) Break up the path into its members. If the original path
365 // was just "/" or "\\", m_dirs will be empty. We know from
366 // the m_relative field, if this means "nothing" or "root dir".
368 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
370 while ( tn
.HasMoreTokens() )
372 wxString token
= tn
.GetNextToken();
374 // Remove empty token under DOS and Unix, interpret them
378 if (my_format
== wxPATH_MAC
)
379 m_dirs
.Add( wxT("..") );
388 else // no path at all
394 void wxFileName::Assign(const wxString
& fullpath
,
397 wxString volume
, path
, name
, ext
;
398 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
400 Assign(volume
, path
, name
, ext
, format
);
403 void wxFileName::Assign(const wxString
& fullpathOrig
,
404 const wxString
& fullname
,
407 // always recognize fullpath as directory, even if it doesn't end with a
409 wxString fullpath
= fullpathOrig
;
410 if ( !wxEndsWithPathSeparator(fullpath
) )
412 fullpath
+= GetPathSeparator(format
);
415 wxString volume
, path
, name
, ext
;
417 // do some consistency checks in debug mode: the name should be really just
418 // the filename and the path should be really just a path
420 wxString pathDummy
, nameDummy
, extDummy
;
422 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
424 wxASSERT_MSG( pathDummy
.empty(),
425 _T("the file name shouldn't contain the path") );
427 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
429 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
430 _T("the path shouldn't contain file name nor extension") );
432 #else // !__WXDEBUG__
433 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
434 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
435 #endif // __WXDEBUG__/!__WXDEBUG__
437 Assign(volume
, path
, name
, ext
, format
);
440 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
442 Assign(dir
, _T(""), format
);
445 void wxFileName::Clear()
451 m_ext
= wxEmptyString
;
453 // we don't have any absolute path for now
458 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
460 return wxFileName(file
, format
);
464 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
467 fn
.AssignDir(dir
, format
);
471 // ----------------------------------------------------------------------------
473 // ----------------------------------------------------------------------------
475 bool wxFileName::FileExists() const
477 return wxFileName::FileExists( GetFullPath() );
480 bool wxFileName::FileExists( const wxString
&file
)
482 return ::wxFileExists( file
);
485 bool wxFileName::DirExists() const
487 return wxFileName::DirExists( GetFullPath() );
490 bool wxFileName::DirExists( const wxString
&dir
)
492 return ::wxDirExists( dir
);
495 // ----------------------------------------------------------------------------
496 // CWD and HOME stuff
497 // ----------------------------------------------------------------------------
499 void wxFileName::AssignCwd(const wxString
& volume
)
501 AssignDir(wxFileName::GetCwd(volume
));
505 wxString
wxFileName::GetCwd(const wxString
& volume
)
507 // if we have the volume, we must get the current directory on this drive
508 // and to do this we have to chdir to this volume - at least under Windows,
509 // I don't know how to get the current drive on another volume elsewhere
512 if ( !volume
.empty() )
515 SetCwd(volume
+ GetVolumeSeparator());
518 wxString cwd
= ::wxGetCwd();
520 if ( !volume
.empty() )
528 bool wxFileName::SetCwd()
530 return wxFileName::SetCwd( GetFullPath() );
533 bool wxFileName::SetCwd( const wxString
&cwd
)
535 return ::wxSetWorkingDirectory( cwd
);
538 void wxFileName::AssignHomeDir()
540 AssignDir(wxFileName::GetHomeDir());
543 wxString
wxFileName::GetHomeDir()
545 return ::wxGetHomeDir();
548 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
550 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
551 if ( tempname
.empty() )
553 // error, failed to get temp file name
564 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
566 wxString path
, dir
, name
;
568 // use the directory specified by the prefix
569 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
571 #if defined(__WXWINCE__)
574 // FIXME. Create \temp dir?
577 path
= dir
+ wxT("\\") + prefix
;
579 while (wxFileExists(path
))
581 path
= dir
+ wxT("\\") + prefix
;
586 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
590 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
592 wxLogLastError(_T("GetTempPath"));
597 // GetTempFileName() fails if we pass it an empty string
601 else // we have a dir to create the file in
603 // ensure we use only the back slashes as GetTempFileName(), unlike all
604 // the other APIs, is picky and doesn't accept the forward ones
605 dir
.Replace(_T("/"), _T("\\"));
608 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
610 wxLogLastError(_T("GetTempFileName"));
615 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
621 #elif defined(__WXPM__)
622 // for now just create a file
624 // future enhancements can be to set some extended attributes for file
625 // systems OS/2 supports that have them (HPFS, FAT32) and security
627 static const wxChar
*szMktempSuffix
= wxT("XXX");
628 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
630 // Temporarily remove - MN
632 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
635 #else // !Windows, !OS/2
638 #if defined(__WXMAC__) && !defined(__DARWIN__)
639 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
641 dir
= wxGetenv(_T("TMP"));
644 dir
= wxGetenv(_T("TEMP"));
661 if ( !wxEndsWithPathSeparator(dir
) &&
662 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
664 path
+= wxFILE_SEP_PATH
;
669 #if defined(HAVE_MKSTEMP)
670 // scratch space for mkstemp()
671 path
+= _T("XXXXXX");
673 // we need to copy the path to the buffer in which mkstemp() can modify it
674 wxCharBuffer
buf( wxConvFile
.cWX2MB( path
) );
676 // cast is safe because the string length doesn't change
677 int fdTemp
= mkstemp( (char*)(const char*) buf
);
680 // this might be not necessary as mkstemp() on most systems should have
681 // already done it but it doesn't hurt neither...
684 else // mkstemp() succeeded
686 path
= wxConvFile
.cMB2WX( (const char*) buf
);
688 // avoid leaking the fd
691 fileTemp
->Attach(fdTemp
);
698 #else // !HAVE_MKSTEMP
702 path
+= _T("XXXXXX");
704 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
705 if ( !mktemp( (const char*) buf
) )
711 path
= wxConvFile
.cMB2WX( (const char*) buf
);
713 #else // !HAVE_MKTEMP (includes __DOS__)
714 // generate the unique file name ourselves
715 #if !defined(__DOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
716 path
<< (unsigned int)getpid();
721 static const size_t numTries
= 1000;
722 for ( size_t n
= 0; n
< numTries
; n
++ )
724 // 3 hex digits is enough for numTries == 1000 < 4096
725 pathTry
= path
+ wxString::Format(_T("%.03x"), n
);
726 if ( !wxFile::Exists(pathTry
) )
735 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
740 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
742 #endif // Windows/!Windows
746 wxLogSysError(_("Failed to create a temporary file name"));
748 else if ( fileTemp
&& !fileTemp
->IsOpened() )
750 // open the file - of course, there is a race condition here, this is
751 // why we always prefer using mkstemp()...
753 // NB: GetTempFileName() under Windows creates the file, so using
754 // write_excl there would fail
755 if ( !fileTemp
->Open(path
,
756 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
761 wxS_IRUSR
| wxS_IWUSR
) )
763 // FIXME: If !ok here should we loop and try again with another
764 // file name? That is the standard recourse if open(O_EXCL)
765 // fails, though of course it should be protected against
766 // possible infinite looping too.
768 wxLogError(_("Failed to open temporary file."));
777 // ----------------------------------------------------------------------------
778 // directory operations
779 // ----------------------------------------------------------------------------
781 bool wxFileName::Mkdir( int perm
, int flags
)
783 return wxFileName::Mkdir( GetFullPath(), perm
, flags
);
786 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
788 if ( flags
& wxPATH_MKDIR_FULL
)
790 // split the path in components
792 filename
.AssignDir(dir
);
795 if ( filename
.HasVolume())
797 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
800 wxArrayString dirs
= filename
.GetDirs();
801 size_t count
= dirs
.GetCount();
802 for ( size_t i
= 0; i
< count
; i
++ )
805 #if defined(__WXMAC__) && !defined(__DARWIN__)
806 // relative pathnames are exactely the other way round under mac...
807 !filename
.IsAbsolute()
809 filename
.IsAbsolute()
812 currPath
+= wxFILE_SEP_PATH
;
815 if (!DirExists(currPath
))
817 if (!wxMkdir(currPath
, perm
))
819 // no need to try creating further directories
829 return ::wxMkdir( dir
, perm
);
832 bool wxFileName::Rmdir()
834 return wxFileName::Rmdir( GetFullPath() );
837 bool wxFileName::Rmdir( const wxString
&dir
)
839 return ::wxRmdir( dir
);
842 // ----------------------------------------------------------------------------
843 // path normalization
844 // ----------------------------------------------------------------------------
846 bool wxFileName::Normalize(int flags
,
850 // the existing path components
851 wxArrayString dirs
= GetDirs();
853 // the path to prepend in front to make the path absolute
856 format
= GetFormat(format
);
858 // make the path absolute
859 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
863 curDir
.AssignCwd(GetVolume());
867 curDir
.AssignDir(cwd
);
870 // the path may be not absolute because it doesn't have the volume name
871 // but in this case we shouldn't modify the directory components of it
872 // but just set the current volume
873 if ( !HasVolume() && curDir
.HasVolume() )
875 SetVolume(curDir
.GetVolume());
879 // yes, it was the case - we don't need curDir then
885 // handle ~ stuff under Unix only
886 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
888 if ( !dirs
.IsEmpty() )
890 wxString dir
= dirs
[0u];
891 if ( !dir
.empty() && dir
[0u] == _T('~') )
893 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
900 // transform relative path into abs one
903 wxArrayString dirsNew
= curDir
.GetDirs();
904 size_t count
= dirs
.GetCount();
905 for ( size_t n
= 0; n
< count
; n
++ )
907 dirsNew
.Add(dirs
[n
]);
913 // now deal with ".", ".." and the rest
915 size_t count
= dirs
.GetCount();
916 for ( size_t n
= 0; n
< count
; n
++ )
918 wxString dir
= dirs
[n
];
920 if ( flags
& wxPATH_NORM_DOTS
)
922 if ( dir
== wxT(".") )
928 if ( dir
== wxT("..") )
930 if ( m_dirs
.IsEmpty() )
932 wxLogError(_("The path '%s' contains too many \"..\"!"),
933 GetFullPath().c_str());
937 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
942 if ( flags
& wxPATH_NORM_ENV_VARS
)
944 dir
= wxExpandEnvVars(dir
);
947 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
955 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
957 // VZ: expand env vars here too?
963 // we do have the path now
965 // NB: need to do this before (maybe) calling Assign() below
968 #if defined(__WIN32__)
969 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
971 Assign(GetLongPath());
978 // ----------------------------------------------------------------------------
979 // absolute/relative paths
980 // ----------------------------------------------------------------------------
982 bool wxFileName::IsAbsolute(wxPathFormat format
) const
984 // if our path doesn't start with a path separator, it's not an absolute
989 if ( !GetVolumeSeparator(format
).empty() )
991 // this format has volumes and an absolute path must have one, it's not
992 // enough to have the full path to bean absolute file under Windows
993 if ( GetVolume().empty() )
1000 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1002 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1004 // get cwd only once - small time saving
1005 wxString cwd
= wxGetCwd();
1006 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1007 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1009 bool withCase
= IsCaseSensitive(format
);
1011 // we can't do anything if the files live on different volumes
1012 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1018 // same drive, so we don't need our volume
1021 // remove common directories starting at the top
1022 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1023 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1026 fnBase
.m_dirs
.RemoveAt(0);
1029 // add as many ".." as needed
1030 size_t count
= fnBase
.m_dirs
.GetCount();
1031 for ( size_t i
= 0; i
< count
; i
++ )
1033 m_dirs
.Insert(wxT(".."), 0u);
1036 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1038 // a directory made relative with respect to itself is '.' under Unix
1039 // and DOS, by definition (but we don't have to insert "./" for the
1041 if ( m_dirs
.IsEmpty() && IsDir() )
1043 m_dirs
.Add(_T('.'));
1053 // ----------------------------------------------------------------------------
1054 // filename kind tests
1055 // ----------------------------------------------------------------------------
1057 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1059 wxFileName fn1
= *this,
1062 // get cwd only once - small time saving
1063 wxString cwd
= wxGetCwd();
1064 fn1
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1065 fn2
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1067 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1070 // TODO: compare inodes for Unix, this works even when filenames are
1071 // different but files are the same (symlinks) (VZ)
1077 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1079 // only Unix filenames are truely case-sensitive
1080 return GetFormat(format
) == wxPATH_UNIX
;
1084 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1086 // Inits to forbidden characters that are common to (almost) all platforms.
1087 wxString strForbiddenChars
= wxT("*?");
1089 // If asserts, wxPathFormat has been changed. In case of a new path format
1090 // addition, the following code might have to be updated.
1091 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1092 switch ( GetFormat(format
) )
1095 wxFAIL_MSG( wxT("Unknown path format") );
1096 // !! Fall through !!
1102 // On a Mac even names with * and ? are allowed (Tested with OS
1103 // 9.2.1 and OS X 10.2.5)
1104 strForbiddenChars
= wxEmptyString
;
1108 strForbiddenChars
+= wxT("\\/:\"<>|");
1115 return strForbiddenChars
;
1119 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
1123 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1124 (GetFormat(format
) == wxPATH_VMS
) )
1126 sepVol
= wxFILE_SEP_DSK
;
1134 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1137 switch ( GetFormat(format
) )
1140 // accept both as native APIs do but put the native one first as
1141 // this is the one we use in GetFullPath()
1142 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1146 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1150 seps
= wxFILE_SEP_PATH_UNIX
;
1154 seps
= wxFILE_SEP_PATH_MAC
;
1158 seps
= wxFILE_SEP_PATH_VMS
;
1166 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1168 // wxString::Find() doesn't work as expected with NUL - it will always find
1169 // it, so it is almost surely a bug if this function is called with NUL arg
1170 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1172 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1175 // ----------------------------------------------------------------------------
1176 // path components manipulation
1177 // ----------------------------------------------------------------------------
1179 void wxFileName::AppendDir( const wxString
&dir
)
1184 void wxFileName::PrependDir( const wxString
&dir
)
1186 m_dirs
.Insert( dir
, 0 );
1189 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1191 m_dirs
.Insert( dir
, before
);
1194 void wxFileName::RemoveDir( int pos
)
1196 m_dirs
.RemoveAt( (size_t)pos
);
1199 // ----------------------------------------------------------------------------
1201 // ----------------------------------------------------------------------------
1203 void wxFileName::SetFullName(const wxString
& fullname
)
1205 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1208 wxString
wxFileName::GetFullName() const
1210 wxString fullname
= m_name
;
1211 if ( !m_ext
.empty() )
1213 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1219 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1221 format
= GetFormat( format
);
1225 // return the volume with the path as well if requested
1226 if ( flags
& wxPATH_GET_VOLUME
)
1228 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1231 // the leading character
1236 fullpath
+= wxFILE_SEP_PATH_MAC
;
1241 fullpath
+= wxFILE_SEP_PATH_DOS
;
1245 wxFAIL_MSG( wxT("Unknown path format") );
1251 // normally the absolute file names starts with a slash with
1252 // one exception: file names like "~/foo.bar" don't have it
1253 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1255 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1261 // no leading character here but use this place to unset
1262 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense as,
1263 // if I understand correctly, there should never be a dot before
1264 // the closing bracket
1265 flags
&= ~wxPATH_GET_SEPARATOR
;
1268 // then concatenate all the path components using the path separator
1269 size_t dirCount
= m_dirs
.GetCount();
1272 if ( format
== wxPATH_VMS
)
1274 fullpath
+= wxT('[');
1277 for ( size_t i
= 0; i
< dirCount
; i
++ )
1282 if ( m_dirs
[i
] == wxT(".") )
1284 // skip appending ':', this shouldn't be done in this
1285 // case as "::" is interpreted as ".." under Unix
1289 // convert back from ".." to nothing
1290 if ( m_dirs
[i
] != wxT("..") )
1291 fullpath
+= m_dirs
[i
];
1295 wxFAIL_MSG( wxT("Unexpected path format") );
1296 // still fall through
1300 fullpath
+= m_dirs
[i
];
1304 // TODO: What to do with ".." under VMS
1306 // convert back from ".." to nothing
1307 if ( m_dirs
[i
] != wxT("..") )
1308 fullpath
+= m_dirs
[i
];
1312 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1313 fullpath
+= GetPathSeparator(format
);
1316 if ( format
== wxPATH_VMS
)
1318 fullpath
+= wxT(']');
1325 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1327 // we already have a function to get the path
1328 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1331 // now just add the file name and extension to it
1332 fullpath
+= GetFullName();
1337 // Return the short form of the path (returns identity on non-Windows platforms)
1338 wxString
wxFileName::GetShortPath() const
1340 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1341 wxString
path(GetFullPath());
1343 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1347 ok
= ::GetShortPathName
1350 wxStringBuffer(pathOut
, sz
),
1359 return GetFullPath();
1363 // Return the long form of the path (returns identity on non-Windows platforms)
1364 wxString
wxFileName::GetLongPath() const
1367 path
= GetFullPath();
1369 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1370 bool success
= false;
1372 #if wxUSE_DYNAMIC_LOADER
1373 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1375 static bool s_triedToLoad
= false;
1377 if ( !s_triedToLoad
)
1379 // suppress the errors about missing GetLongPathName[AW]
1382 s_triedToLoad
= true;
1383 wxDynamicLibrary
dllKernel(_T("kernel32"));
1384 if ( dllKernel
.IsLoaded() )
1386 // may succeed or fail depending on the Windows version
1387 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1389 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1391 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1394 if ( s_pfnGetLongPathName
)
1396 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1397 bool ok
= dwSize
> 0;
1401 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1405 ok
= (*s_pfnGetLongPathName
)
1408 wxStringBuffer(pathOut
, sz
),
1420 #endif // wxUSE_DYNAMIC_LOADER
1424 // The OS didn't support GetLongPathName, or some other error.
1425 // We need to call FindFirstFile on each component in turn.
1427 WIN32_FIND_DATA findFileData
;
1431 pathOut
= GetVolume() +
1432 GetVolumeSeparator(wxPATH_DOS
) +
1433 GetPathSeparator(wxPATH_DOS
);
1435 pathOut
= wxEmptyString
;
1437 wxArrayString dirs
= GetDirs();
1438 dirs
.Add(GetFullName());
1442 size_t count
= dirs
.GetCount();
1443 for ( size_t i
= 0; i
< count
; i
++ )
1445 // We're using pathOut to collect the long-name path, but using a
1446 // temporary for appending the last path component which may be
1448 tmpPath
= pathOut
+ dirs
[i
];
1450 if ( tmpPath
.empty() )
1453 // can't see this being necessary? MF
1454 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1456 // Can't pass a drive and root dir to FindFirstFile,
1457 // so continue to next dir
1458 tmpPath
+= wxFILE_SEP_PATH
;
1463 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1464 if (hFind
== INVALID_HANDLE_VALUE
)
1466 // Error: most likely reason is that path doesn't exist, so
1467 // append any unprocessed parts and return
1468 for ( i
+= 1; i
< count
; i
++ )
1469 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1474 pathOut
+= findFileData
.cFileName
;
1475 if ( (i
< (count
-1)) )
1476 pathOut
+= wxFILE_SEP_PATH
;
1483 #endif // Win32/!Win32
1488 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1490 if (format
== wxPATH_NATIVE
)
1492 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1493 format
= wxPATH_DOS
;
1494 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1495 format
= wxPATH_MAC
;
1496 #elif defined(__VMS)
1497 format
= wxPATH_VMS
;
1499 format
= wxPATH_UNIX
;
1505 // ----------------------------------------------------------------------------
1506 // path splitting function
1507 // ----------------------------------------------------------------------------
1510 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1511 wxString
*pstrVolume
,
1515 wxPathFormat format
)
1517 format
= GetFormat(format
);
1519 wxString fullpath
= fullpathWithVolume
;
1521 // under VMS the end of the path is ']', not the path separator used to
1522 // separate the components
1523 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1524 : GetPathSeparators(format
);
1526 // special Windows UNC paths hack: transform \\share\path into share:path
1527 if ( format
== wxPATH_DOS
)
1529 if ( fullpath
.length() >= 4 &&
1530 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1531 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1533 fullpath
.erase(0, 2);
1535 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1536 if ( posFirstSlash
!= wxString::npos
)
1538 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1540 // UNC paths are always absolute, right? (FIXME)
1541 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1546 // We separate the volume here
1547 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1549 wxString sepVol
= GetVolumeSeparator(format
);
1551 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1552 if ( posFirstColon
!= wxString::npos
)
1556 *pstrVolume
= fullpath
.Left(posFirstColon
);
1559 // remove the volume name and the separator from the full path
1560 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1564 // find the positions of the last dot and last path separator in the path
1565 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1566 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1568 if ( (posLastDot
!= wxString::npos
) &&
1569 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1571 if ( (posLastDot
== 0) ||
1572 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1574 // under Unix and VMS, dot may be (and commonly is) the first
1575 // character of the filename, don't treat the entire filename as
1576 // extension in this case
1577 posLastDot
= wxString::npos
;
1581 // if we do have a dot and a slash, check that the dot is in the name part
1582 if ( (posLastDot
!= wxString::npos
) &&
1583 (posLastSlash
!= wxString::npos
) &&
1584 (posLastDot
< posLastSlash
) )
1586 // the dot is part of the path, not the start of the extension
1587 posLastDot
= wxString::npos
;
1590 // now fill in the variables provided by user
1593 if ( posLastSlash
== wxString::npos
)
1600 // take everything up to the path separator but take care to make
1601 // the path equal to something like '/', not empty, for the files
1602 // immediately under root directory
1603 size_t len
= posLastSlash
;
1605 // this rule does not apply to mac since we do not start with colons (sep)
1606 // except for relative paths
1607 if ( !len
&& format
!= wxPATH_MAC
)
1610 *pstrPath
= fullpath
.Left(len
);
1612 // special VMS hack: remove the initial bracket
1613 if ( format
== wxPATH_VMS
)
1615 if ( (*pstrPath
)[0u] == _T('[') )
1616 pstrPath
->erase(0, 1);
1623 // take all characters starting from the one after the last slash and
1624 // up to, but excluding, the last dot
1625 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1627 if ( posLastDot
== wxString::npos
)
1629 // take all until the end
1630 count
= wxString::npos
;
1632 else if ( posLastSlash
== wxString::npos
)
1636 else // have both dot and slash
1638 count
= posLastDot
- posLastSlash
- 1;
1641 *pstrName
= fullpath
.Mid(nStart
, count
);
1646 if ( posLastDot
== wxString::npos
)
1653 // take everything after the dot
1654 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1660 void wxFileName::SplitPath(const wxString
& fullpath
,
1664 wxPathFormat format
)
1667 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1671 path
->Prepend(wxGetVolumeString(volume
, format
));
1675 // ----------------------------------------------------------------------------
1677 // ----------------------------------------------------------------------------
1681 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1682 const wxDateTime
*dtMod
,
1683 const wxDateTime
*dtCreate
)
1685 #if defined(__WIN32__)
1688 // VZ: please let me know how to do this if you can
1689 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1693 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1696 FILETIME ftAccess
, ftCreate
, ftWrite
;
1699 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1701 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1703 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1705 if ( ::SetFileTime(fh
,
1706 dtCreate
? &ftCreate
: NULL
,
1707 dtAccess
? &ftAccess
: NULL
,
1708 dtMod
? &ftWrite
: NULL
) )
1714 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1715 if ( !dtAccess
&& !dtMod
)
1717 // can't modify the creation time anyhow, don't try
1721 // if dtAccess or dtMod is not specified, use the other one (which must be
1722 // non NULL because of the test above) for both times
1724 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1725 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1726 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
1730 #else // other platform
1733 wxLogSysError(_("Failed to modify file times for '%s'"),
1734 GetFullPath().c_str());
1739 bool wxFileName::Touch()
1741 #if defined(__UNIX_LIKE__)
1742 // under Unix touching file is simple: just pass NULL to utime()
1743 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
1748 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1751 #else // other platform
1752 wxDateTime dtNow
= wxDateTime::Now();
1754 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1758 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1760 wxDateTime
*dtCreate
) const
1762 #if defined(__WIN32__)
1763 // we must use different methods for the files and directories under
1764 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1765 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1768 FILETIME ftAccess
, ftCreate
, ftWrite
;
1771 // implemented in msw/dir.cpp
1772 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
1773 FILETIME
*, FILETIME
*, FILETIME
*);
1775 // we should pass the path without the trailing separator to
1776 // wxGetDirectoryTimes()
1777 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
1778 &ftAccess
, &ftCreate
, &ftWrite
);
1782 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1785 ok
= ::GetFileTime(fh
,
1786 dtCreate
? &ftCreate
: NULL
,
1787 dtAccess
? &ftAccess
: NULL
,
1788 dtMod
? &ftWrite
: NULL
) != 0;
1799 ConvertFileTimeToWx(dtCreate
, ftCreate
);
1801 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1803 ConvertFileTimeToWx(dtMod
, ftWrite
);
1807 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1809 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
1812 dtAccess
->Set(stBuf
.st_atime
);
1814 dtMod
->Set(stBuf
.st_mtime
);
1816 dtCreate
->Set(stBuf
.st_ctime
);
1820 #else // other platform
1823 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1824 GetFullPath().c_str());
1829 #endif // wxUSE_DATETIME
1833 const short kMacExtensionMaxLength
= 16 ;
1834 class MacDefaultExtensionRecord
1837 MacDefaultExtensionRecord()
1840 m_type
= m_creator
= NULL
;
1842 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
1844 wxStrcpy( m_ext
, from
.m_ext
) ;
1845 m_type
= from
.m_type
;
1846 m_creator
= from
.m_creator
;
1848 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
1850 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
1851 m_ext
[kMacExtensionMaxLength
] = 0 ;
1853 m_creator
= creator
;
1855 wxChar m_ext
[kMacExtensionMaxLength
] ;
1860 #include "wx/dynarray.h"
1861 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1863 bool gMacDefaultExtensionsInited
= false ;
1865 #include "wx/arrimpl.cpp"
1867 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
1869 MacDefaultExtensionArray gMacDefaultExtensions
;
1871 static void MacEnsureDefaultExtensionsLoaded()
1873 if ( !gMacDefaultExtensionsInited
)
1876 // load the default extensions
1877 MacDefaultExtensionRecord defaults
[1] =
1879 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
1882 // we could load the pc exchange prefs here too
1884 for ( size_t i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1886 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1888 gMacDefaultExtensionsInited
= true ;
1891 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1895 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1896 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1897 wxCHECK( err
== noErr
, false ) ;
1899 fndrInfo
.fdType
= type
;
1900 fndrInfo
.fdCreator
= creator
;
1901 FSpSetFInfo( &spec
, &fndrInfo
) ;
1905 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1909 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1910 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1911 wxCHECK( err
== noErr
, false ) ;
1913 *type
= fndrInfo
.fdType
;
1914 *creator
= fndrInfo
.fdCreator
;
1918 bool wxFileName::MacSetDefaultTypeAndCreator()
1920 wxUint32 type
, creator
;
1921 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1924 return MacSetTypeAndCreator( type
, creator
) ;
1929 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1931 MacEnsureDefaultExtensionsLoaded() ;
1932 wxString extl
= ext
.Lower() ;
1933 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1935 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1937 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1938 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1945 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1947 MacEnsureDefaultExtensionsLoaded() ;
1948 MacDefaultExtensionRecord rec
;
1950 rec
.m_creator
= creator
;
1951 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1952 gMacDefaultExtensions
.Add( rec
) ;