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>
139 #define MAX_PATH _MAX_PATH
142 // ----------------------------------------------------------------------------
144 // ----------------------------------------------------------------------------
146 // small helper class which opens and closes the file - we use it just to get
147 // a file handle for the given file name to pass it to some Win32 API function
148 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
159 wxFileHandle(const wxString
& filename
, OpenMode mode
)
161 m_hFile
= ::CreateFile
164 mode
== Read
? GENERIC_READ
// access mask
167 NULL
, // no secutity attr
168 OPEN_EXISTING
, // creation disposition
170 NULL
// no template file
173 if ( m_hFile
== INVALID_HANDLE_VALUE
)
175 wxLogSysError(_("Failed to open '%s' for %s"),
177 mode
== Read
? _("reading") : _("writing"));
183 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
185 if ( !::CloseHandle(m_hFile
) )
187 wxLogSysError(_("Failed to close file handle"));
192 // return true only if the file could be opened successfully
193 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
196 operator HANDLE() const { return m_hFile
; }
204 // ----------------------------------------------------------------------------
206 // ----------------------------------------------------------------------------
208 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
210 // convert between wxDateTime and FILETIME which is a 64-bit value representing
211 // the number of 100-nanosecond intervals since January 1, 1601.
213 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
215 FILETIME ftcopy
= ft
;
217 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
219 wxLogLastError(_T("FileTimeToLocalFileTime"));
223 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
225 wxLogLastError(_T("FileTimeToSystemTime"));
228 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
229 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
232 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
235 st
.wDay
= dt
.GetDay();
236 st
.wMonth
= dt
.GetMonth() + 1;
237 st
.wYear
= dt
.GetYear();
238 st
.wHour
= dt
.GetHour();
239 st
.wMinute
= dt
.GetMinute();
240 st
.wSecond
= dt
.GetSecond();
241 st
.wMilliseconds
= dt
.GetMillisecond();
244 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
246 wxLogLastError(_T("SystemTimeToFileTime"));
249 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
251 wxLogLastError(_T("LocalFileTimeToFileTime"));
255 #endif // wxUSE_DATETIME && __WIN32__
257 // return a string with the volume par
258 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
262 if ( !volume
.empty() )
264 format
= wxFileName::GetFormat(format
);
266 // Special Windows UNC paths hack, part 2: undo what we did in
267 // SplitPath() and make an UNC path if we have a drive which is not a
268 // single letter (hopefully the network shares can't be one letter only
269 // although I didn't find any authoritative docs on this)
270 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
272 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
274 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
276 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
284 // ============================================================================
286 // ============================================================================
288 // ----------------------------------------------------------------------------
289 // wxFileName construction
290 // ----------------------------------------------------------------------------
292 void wxFileName::Assign( const wxFileName
&filepath
)
294 m_volume
= filepath
.GetVolume();
295 m_dirs
= filepath
.GetDirs();
296 m_name
= filepath
.GetName();
297 m_ext
= filepath
.GetExt();
298 m_relative
= filepath
.m_relative
;
301 void wxFileName::Assign(const wxString
& volume
,
302 const wxString
& path
,
303 const wxString
& name
,
305 wxPathFormat format
)
307 SetPath( path
, format
);
314 void wxFileName::SetPath( const wxString
&path
, wxPathFormat format
)
320 wxPathFormat my_format
= GetFormat( format
);
321 wxString my_path
= path
;
323 // 1) Determine if the path is relative or absolute.
324 wxChar leadingChar
= my_path
[0u];
329 m_relative
= leadingChar
== wxT(':');
331 // We then remove a leading ":". The reason is in our
332 // storage form for relative paths:
333 // ":dir:file.txt" actually means "./dir/file.txt" in
334 // DOS notation and should get stored as
335 // (relative) (dir) (file.txt)
336 // "::dir:file.txt" actually means "../dir/file.txt"
337 // stored as (relative) (..) (dir) (file.txt)
338 // This is important only for the Mac as an empty dir
339 // actually means <UP>, whereas under DOS, double
340 // slashes can be ignored: "\\\\" is the same as "\\".
342 my_path
.erase( 0, 1 );
346 // TODO: what is the relative path format here?
351 wxFAIL_MSG( _T("Unknown path format") );
352 // !! Fall through !!
355 // the paths of the form "~" or "~username" are absolute
356 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
360 m_relative
= !IsPathSeparator(leadingChar
, my_format
);
365 // 2) Break up the path into its members. If the original path
366 // was just "/" or "\\", m_dirs will be empty. We know from
367 // the m_relative field, if this means "nothing" or "root dir".
369 wxStringTokenizer
tn( my_path
, GetPathSeparators(my_format
) );
371 while ( tn
.HasMoreTokens() )
373 wxString token
= tn
.GetNextToken();
375 // Remove empty token under DOS and Unix, interpret them
379 if (my_format
== wxPATH_MAC
)
380 m_dirs
.Add( wxT("..") );
389 else // no path at all
395 void wxFileName::Assign(const wxString
& fullpath
,
398 wxString volume
, path
, name
, ext
;
399 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, format
);
401 Assign(volume
, path
, name
, ext
, format
);
404 void wxFileName::Assign(const wxString
& fullpathOrig
,
405 const wxString
& fullname
,
408 // always recognize fullpath as directory, even if it doesn't end with a
410 wxString fullpath
= fullpathOrig
;
411 if ( !wxEndsWithPathSeparator(fullpath
) )
413 fullpath
+= GetPathSeparator(format
);
416 wxString volume
, path
, name
, ext
;
418 // do some consistency checks in debug mode: the name should be really just
419 // the filename and the path should be really just a path
421 wxString pathDummy
, nameDummy
, extDummy
;
423 SplitPath(fullname
, &pathDummy
, &name
, &ext
, format
);
425 wxASSERT_MSG( pathDummy
.empty(),
426 _T("the file name shouldn't contain the path") );
428 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
430 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
431 _T("the path shouldn't contain file name nor extension") );
433 #else // !__WXDEBUG__
434 SplitPath(fullname
, NULL
/* no path */, &name
, &ext
, format
);
435 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
436 #endif // __WXDEBUG__/!__WXDEBUG__
438 Assign(volume
, path
, name
, ext
, format
);
441 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
443 Assign(dir
, _T(""), format
);
446 void wxFileName::Clear()
452 m_ext
= wxEmptyString
;
454 // we don't have any absolute path for now
459 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
461 return wxFileName(file
, format
);
465 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
468 fn
.AssignDir(dir
, format
);
472 // ----------------------------------------------------------------------------
474 // ----------------------------------------------------------------------------
476 bool wxFileName::FileExists() const
478 return wxFileName::FileExists( GetFullPath() );
481 bool wxFileName::FileExists( const wxString
&file
)
483 return ::wxFileExists( file
);
486 bool wxFileName::DirExists() const
488 return wxFileName::DirExists( GetFullPath() );
491 bool wxFileName::DirExists( const wxString
&dir
)
493 return ::wxDirExists( dir
);
496 // ----------------------------------------------------------------------------
497 // CWD and HOME stuff
498 // ----------------------------------------------------------------------------
500 void wxFileName::AssignCwd(const wxString
& volume
)
502 AssignDir(wxFileName::GetCwd(volume
));
506 wxString
wxFileName::GetCwd(const wxString
& volume
)
508 // if we have the volume, we must get the current directory on this drive
509 // and to do this we have to chdir to this volume - at least under Windows,
510 // I don't know how to get the current drive on another volume elsewhere
513 if ( !volume
.empty() )
516 SetCwd(volume
+ GetVolumeSeparator());
519 wxString cwd
= ::wxGetCwd();
521 if ( !volume
.empty() )
529 bool wxFileName::SetCwd()
531 return wxFileName::SetCwd( GetFullPath() );
534 bool wxFileName::SetCwd( const wxString
&cwd
)
536 return ::wxSetWorkingDirectory( cwd
);
539 void wxFileName::AssignHomeDir()
541 AssignDir(wxFileName::GetHomeDir());
544 wxString
wxFileName::GetHomeDir()
546 return ::wxGetHomeDir();
549 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
551 wxString tempname
= CreateTempFileName(prefix
, fileTemp
);
552 if ( tempname
.empty() )
554 // error, failed to get temp file name
565 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
567 wxString path
, dir
, name
;
569 // use the directory specified by the prefix
570 SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
572 #if defined(__WXWINCE__)
575 // FIXME. Create \temp dir?
578 path
= dir
+ wxT("\\") + prefix
;
580 while (wxFileExists(path
))
582 path
= dir
+ wxT("\\") + prefix
;
587 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
591 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
593 wxLogLastError(_T("GetTempPath"));
598 // GetTempFileName() fails if we pass it an empty string
602 else // we have a dir to create the file in
604 // ensure we use only the back slashes as GetTempFileName(), unlike all
605 // the other APIs, is picky and doesn't accept the forward ones
606 dir
.Replace(_T("/"), _T("\\"));
609 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
611 wxLogLastError(_T("GetTempFileName"));
616 if ( !::GetTempFileName(NULL
, prefix
, 0, wxStringBuffer(path
, 1025)) )
622 #elif defined(__WXPM__)
623 // for now just create a file
625 // future enhancements can be to set some extended attributes for file
626 // systems OS/2 supports that have them (HPFS, FAT32) and security
628 static const wxChar
*szMktempSuffix
= wxT("XXX");
629 path
<< dir
<< _T('/') << name
<< szMktempSuffix
;
631 // Temporarily remove - MN
633 ::DosCreateDir(wxStringBuffer(path
, MAX_PATH
), NULL
);
636 #else // !Windows, !OS/2
639 #if defined(__WXMAC__) && !defined(__DARWIN__)
640 dir
= wxMacFindFolder( (short) kOnSystemDisk
, kTemporaryFolderType
, kCreateFolder
) ;
642 dir
= wxGetenv(_T("TMP"));
645 dir
= wxGetenv(_T("TEMP"));
662 if ( !wxEndsWithPathSeparator(dir
) &&
663 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
665 path
+= wxFILE_SEP_PATH
;
670 #if defined(HAVE_MKSTEMP)
671 // scratch space for mkstemp()
672 path
+= _T("XXXXXX");
674 // we need to copy the path to the buffer in which mkstemp() can modify it
675 wxCharBuffer
buf( wxConvFile
.cWX2MB( path
) );
677 // cast is safe because the string length doesn't change
678 int fdTemp
= mkstemp( (char*)(const char*) buf
);
681 // this might be not necessary as mkstemp() on most systems should have
682 // already done it but it doesn't hurt neither...
685 else // mkstemp() succeeded
687 path
= wxConvFile
.cMB2WX( (const char*) buf
);
689 // avoid leaking the fd
692 fileTemp
->Attach(fdTemp
);
699 #else // !HAVE_MKSTEMP
703 path
+= _T("XXXXXX");
705 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
706 if ( !mktemp( (const char*) buf
) )
712 path
= wxConvFile
.cMB2WX( (const char*) buf
);
714 #else // !HAVE_MKTEMP (includes __DOS__)
715 // generate the unique file name ourselves
716 #if !defined(__DOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
717 path
<< (unsigned int)getpid();
722 static const size_t numTries
= 1000;
723 for ( size_t n
= 0; n
< numTries
; n
++ )
725 // 3 hex digits is enough for numTries == 1000 < 4096
726 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
727 if ( !wxFile::Exists(pathTry
) )
736 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
741 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
743 #endif // Windows/!Windows
747 wxLogSysError(_("Failed to create a temporary file name"));
749 else if ( fileTemp
&& !fileTemp
->IsOpened() )
751 // open the file - of course, there is a race condition here, this is
752 // why we always prefer using mkstemp()...
754 // NB: GetTempFileName() under Windows creates the file, so using
755 // write_excl there would fail
756 if ( !fileTemp
->Open(path
,
757 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
762 wxS_IRUSR
| wxS_IWUSR
) )
764 // FIXME: If !ok here should we loop and try again with another
765 // file name? That is the standard recourse if open(O_EXCL)
766 // fails, though of course it should be protected against
767 // possible infinite looping too.
769 wxLogError(_("Failed to open temporary file."));
778 // ----------------------------------------------------------------------------
779 // directory operations
780 // ----------------------------------------------------------------------------
782 bool wxFileName::Mkdir( int perm
, int flags
)
784 return wxFileName::Mkdir( GetFullPath(), perm
, flags
);
787 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
789 if ( flags
& wxPATH_MKDIR_FULL
)
791 // split the path in components
793 filename
.AssignDir(dir
);
796 if ( filename
.HasVolume())
798 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
801 wxArrayString dirs
= filename
.GetDirs();
802 size_t count
= dirs
.GetCount();
803 for ( size_t i
= 0; i
< count
; i
++ )
806 #if defined(__WXMAC__) && !defined(__DARWIN__)
807 // relative pathnames are exactely the other way round under mac...
808 !filename
.IsAbsolute()
810 filename
.IsAbsolute()
813 currPath
+= wxFILE_SEP_PATH
;
816 if (!DirExists(currPath
))
818 if (!wxMkdir(currPath
, perm
))
820 // no need to try creating further directories
830 return ::wxMkdir( dir
, perm
);
833 bool wxFileName::Rmdir()
835 return wxFileName::Rmdir( GetFullPath() );
838 bool wxFileName::Rmdir( const wxString
&dir
)
840 return ::wxRmdir( dir
);
843 // ----------------------------------------------------------------------------
844 // path normalization
845 // ----------------------------------------------------------------------------
847 bool wxFileName::Normalize(int flags
,
851 // deal with env vars renaming first as this may seriously change the path
852 if ( flags
& wxPATH_NORM_ENV_VARS
)
854 wxString pathOrig
= GetFullPath(format
);
855 wxString path
= wxExpandEnvVars(pathOrig
);
856 if ( path
!= pathOrig
)
863 // the existing path components
864 wxArrayString dirs
= GetDirs();
866 // the path to prepend in front to make the path absolute
869 format
= GetFormat(format
);
871 // make the path absolute
872 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
876 curDir
.AssignCwd(GetVolume());
880 curDir
.AssignDir(cwd
);
883 // the path may be not absolute because it doesn't have the volume name
884 // but in this case we shouldn't modify the directory components of it
885 // but just set the current volume
886 if ( !HasVolume() && curDir
.HasVolume() )
888 SetVolume(curDir
.GetVolume());
892 // yes, it was the case - we don't need curDir then
898 // handle ~ stuff under Unix only
899 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
901 if ( !dirs
.IsEmpty() )
903 wxString dir
= dirs
[0u];
904 if ( !dir
.empty() && dir
[0u] == _T('~') )
906 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
913 // transform relative path into abs one
916 wxArrayString dirsNew
= curDir
.GetDirs();
917 size_t count
= dirs
.GetCount();
918 for ( size_t n
= 0; n
< count
; n
++ )
920 dirsNew
.Add(dirs
[n
]);
926 // now deal with ".", ".." and the rest
928 size_t count
= dirs
.GetCount();
929 for ( size_t n
= 0; n
< count
; n
++ )
931 wxString dir
= dirs
[n
];
933 if ( flags
& wxPATH_NORM_DOTS
)
935 if ( dir
== wxT(".") )
941 if ( dir
== wxT("..") )
943 if ( m_dirs
.IsEmpty() )
945 wxLogError(_("The path '%s' contains too many \"..\"!"),
946 GetFullPath().c_str());
950 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
955 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
963 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
965 // VZ: expand env vars here too?
971 // we do have the path now
973 // NB: need to do this before (maybe) calling Assign() below
976 #if defined(__WIN32__)
977 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
979 Assign(GetLongPath());
986 // ----------------------------------------------------------------------------
987 // absolute/relative paths
988 // ----------------------------------------------------------------------------
990 bool wxFileName::IsAbsolute(wxPathFormat format
) const
992 // if our path doesn't start with a path separator, it's not an absolute
997 if ( !GetVolumeSeparator(format
).empty() )
999 // this format has volumes and an absolute path must have one, it's not
1000 // enough to have the full path to bean absolute file under Windows
1001 if ( GetVolume().empty() )
1008 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1010 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1012 // get cwd only once - small time saving
1013 wxString cwd
= wxGetCwd();
1014 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1015 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1017 bool withCase
= IsCaseSensitive(format
);
1019 // we can't do anything if the files live on different volumes
1020 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1026 // same drive, so we don't need our volume
1029 // remove common directories starting at the top
1030 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1031 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1034 fnBase
.m_dirs
.RemoveAt(0);
1037 // add as many ".." as needed
1038 size_t count
= fnBase
.m_dirs
.GetCount();
1039 for ( size_t i
= 0; i
< count
; i
++ )
1041 m_dirs
.Insert(wxT(".."), 0u);
1044 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1046 // a directory made relative with respect to itself is '.' under Unix
1047 // and DOS, by definition (but we don't have to insert "./" for the
1049 if ( m_dirs
.IsEmpty() && IsDir() )
1051 m_dirs
.Add(_T('.'));
1061 // ----------------------------------------------------------------------------
1062 // filename kind tests
1063 // ----------------------------------------------------------------------------
1065 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1067 wxFileName fn1
= *this,
1070 // get cwd only once - small time saving
1071 wxString cwd
= wxGetCwd();
1072 fn1
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1073 fn2
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1075 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1078 // TODO: compare inodes for Unix, this works even when filenames are
1079 // different but files are the same (symlinks) (VZ)
1085 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1087 // only Unix filenames are truely case-sensitive
1088 return GetFormat(format
) == wxPATH_UNIX
;
1092 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1094 // Inits to forbidden characters that are common to (almost) all platforms.
1095 wxString strForbiddenChars
= wxT("*?");
1097 // If asserts, wxPathFormat has been changed. In case of a new path format
1098 // addition, the following code might have to be updated.
1099 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1100 switch ( GetFormat(format
) )
1103 wxFAIL_MSG( wxT("Unknown path format") );
1104 // !! Fall through !!
1110 // On a Mac even names with * and ? are allowed (Tested with OS
1111 // 9.2.1 and OS X 10.2.5)
1112 strForbiddenChars
= wxEmptyString
;
1116 strForbiddenChars
+= wxT("\\/:\"<>|");
1123 return strForbiddenChars
;
1127 wxString
wxFileName::GetVolumeSeparator(wxPathFormat format
)
1131 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1132 (GetFormat(format
) == wxPATH_VMS
) )
1134 sepVol
= wxFILE_SEP_DSK
;
1142 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1145 switch ( GetFormat(format
) )
1148 // accept both as native APIs do but put the native one first as
1149 // this is the one we use in GetFullPath()
1150 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1154 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1158 seps
= wxFILE_SEP_PATH_UNIX
;
1162 seps
= wxFILE_SEP_PATH_MAC
;
1166 seps
= wxFILE_SEP_PATH_VMS
;
1174 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1176 // wxString::Find() doesn't work as expected with NUL - it will always find
1177 // it, so it is almost surely a bug if this function is called with NUL arg
1178 wxASSERT_MSG( ch
!= _T('\0'), _T("shouldn't be called with NUL") );
1180 return GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1183 // ----------------------------------------------------------------------------
1184 // path components manipulation
1185 // ----------------------------------------------------------------------------
1187 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1191 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1196 const size_t len
= dir
.length();
1197 for ( size_t n
= 0; n
< len
; n
++ )
1199 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1201 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1210 void wxFileName::AppendDir( const wxString
&dir
)
1212 if ( IsValidDirComponent(dir
) )
1216 void wxFileName::PrependDir( const wxString
&dir
)
1221 void wxFileName::InsertDir( int before
, const wxString
&dir
)
1223 if ( IsValidDirComponent(dir
) )
1224 m_dirs
.Insert( dir
, before
);
1227 void wxFileName::RemoveDir( int pos
)
1229 m_dirs
.RemoveAt( (size_t)pos
);
1232 // ----------------------------------------------------------------------------
1234 // ----------------------------------------------------------------------------
1236 void wxFileName::SetFullName(const wxString
& fullname
)
1238 SplitPath(fullname
, NULL
/* no path */, &m_name
, &m_ext
);
1241 wxString
wxFileName::GetFullName() const
1243 wxString fullname
= m_name
;
1244 if ( !m_ext
.empty() )
1246 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1252 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1254 format
= GetFormat( format
);
1258 // return the volume with the path as well if requested
1259 if ( flags
& wxPATH_GET_VOLUME
)
1261 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1264 // the leading character
1269 fullpath
+= wxFILE_SEP_PATH_MAC
;
1274 fullpath
+= wxFILE_SEP_PATH_DOS
;
1278 wxFAIL_MSG( wxT("Unknown path format") );
1284 // normally the absolute file names start with a slash
1285 // with one exception: the ones like "~/foo.bar" don't
1287 if ( m_dirs
[0u] != _T('~') )
1289 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1295 // no leading character here but use this place to unset
1296 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1297 // as, if I understand correctly, there should never be a dot
1298 // before the closing bracket
1299 flags
&= ~wxPATH_GET_SEPARATOR
;
1302 if ( m_dirs
.empty() )
1304 // there is nothing more
1308 // then concatenate all the path components using the path separator
1309 if ( format
== wxPATH_VMS
)
1311 fullpath
+= wxT('[');
1314 const size_t dirCount
= m_dirs
.GetCount();
1315 for ( size_t i
= 0; i
< dirCount
; i
++ )
1320 if ( m_dirs
[i
] == wxT(".") )
1322 // skip appending ':', this shouldn't be done in this
1323 // case as "::" is interpreted as ".." under Unix
1327 // convert back from ".." to nothing
1328 if ( m_dirs
[i
] != wxT("..") )
1329 fullpath
+= m_dirs
[i
];
1333 wxFAIL_MSG( wxT("Unexpected path format") );
1334 // still fall through
1338 fullpath
+= m_dirs
[i
];
1342 // TODO: What to do with ".." under VMS
1344 // convert back from ".." to nothing
1345 if ( m_dirs
[i
] != wxT("..") )
1346 fullpath
+= m_dirs
[i
];
1350 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1351 fullpath
+= GetPathSeparator(format
);
1354 if ( format
== wxPATH_VMS
)
1356 fullpath
+= wxT(']');
1362 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1364 // we already have a function to get the path
1365 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1368 // now just add the file name and extension to it
1369 fullpath
+= GetFullName();
1374 // Return the short form of the path (returns identity on non-Windows platforms)
1375 wxString
wxFileName::GetShortPath() const
1377 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1378 wxString
path(GetFullPath());
1380 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1384 ok
= ::GetShortPathName
1387 wxStringBuffer(pathOut
, sz
),
1396 return GetFullPath();
1400 // Return the long form of the path (returns identity on non-Windows platforms)
1401 wxString
wxFileName::GetLongPath() const
1404 path
= GetFullPath();
1406 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1407 bool success
= false;
1409 #if wxUSE_DYNAMIC_LOADER
1410 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1412 static bool s_triedToLoad
= false;
1414 if ( !s_triedToLoad
)
1416 // suppress the errors about missing GetLongPathName[AW]
1419 s_triedToLoad
= true;
1420 wxDynamicLibrary
dllKernel(_T("kernel32"));
1421 if ( dllKernel
.IsLoaded() )
1423 // may succeed or fail depending on the Windows version
1424 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1426 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameW"));
1428 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
) dllKernel
.GetSymbol(_T("GetLongPathNameA"));
1431 if ( s_pfnGetLongPathName
)
1433 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1434 bool ok
= dwSize
> 0;
1438 DWORD sz
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1442 ok
= (*s_pfnGetLongPathName
)
1445 wxStringBuffer(pathOut
, sz
),
1457 #endif // wxUSE_DYNAMIC_LOADER
1461 // The OS didn't support GetLongPathName, or some other error.
1462 // We need to call FindFirstFile on each component in turn.
1464 WIN32_FIND_DATA findFileData
;
1468 pathOut
= GetVolume() +
1469 GetVolumeSeparator(wxPATH_DOS
) +
1470 GetPathSeparator(wxPATH_DOS
);
1472 pathOut
= wxEmptyString
;
1474 wxArrayString dirs
= GetDirs();
1475 dirs
.Add(GetFullName());
1479 size_t count
= dirs
.GetCount();
1480 for ( size_t i
= 0; i
< count
; i
++ )
1482 // We're using pathOut to collect the long-name path, but using a
1483 // temporary for appending the last path component which may be
1485 tmpPath
= pathOut
+ dirs
[i
];
1487 if ( tmpPath
.empty() )
1490 // can't see this being necessary? MF
1491 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1493 // Can't pass a drive and root dir to FindFirstFile,
1494 // so continue to next dir
1495 tmpPath
+= wxFILE_SEP_PATH
;
1500 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1501 if (hFind
== INVALID_HANDLE_VALUE
)
1503 // Error: most likely reason is that path doesn't exist, so
1504 // append any unprocessed parts and return
1505 for ( i
+= 1; i
< count
; i
++ )
1506 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1511 pathOut
+= findFileData
.cFileName
;
1512 if ( (i
< (count
-1)) )
1513 pathOut
+= wxFILE_SEP_PATH
;
1520 #endif // Win32/!Win32
1525 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1527 if (format
== wxPATH_NATIVE
)
1529 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1530 format
= wxPATH_DOS
;
1531 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1532 format
= wxPATH_MAC
;
1533 #elif defined(__VMS)
1534 format
= wxPATH_VMS
;
1536 format
= wxPATH_UNIX
;
1542 // ----------------------------------------------------------------------------
1543 // path splitting function
1544 // ----------------------------------------------------------------------------
1547 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
1548 wxString
*pstrVolume
,
1552 wxPathFormat format
)
1554 format
= GetFormat(format
);
1556 wxString fullpath
= fullpathWithVolume
;
1558 // under VMS the end of the path is ']', not the path separator used to
1559 // separate the components
1560 wxString sepPath
= format
== wxPATH_VMS
? wxString(_T(']'))
1561 : GetPathSeparators(format
);
1563 // special Windows UNC paths hack: transform \\share\path into share:path
1564 if ( format
== wxPATH_DOS
)
1566 if ( fullpath
.length() >= 4 &&
1567 fullpath
[0u] == wxFILE_SEP_PATH_DOS
&&
1568 fullpath
[1u] == wxFILE_SEP_PATH_DOS
)
1570 fullpath
.erase(0, 2);
1572 size_t posFirstSlash
= fullpath
.find_first_of(sepPath
);
1573 if ( posFirstSlash
!= wxString::npos
)
1575 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1577 // UNC paths are always absolute, right? (FIXME)
1578 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1583 // We separate the volume here
1584 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1586 wxString sepVol
= GetVolumeSeparator(format
);
1588 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
1589 if ( posFirstColon
!= wxString::npos
)
1593 *pstrVolume
= fullpath
.Left(posFirstColon
);
1596 // remove the volume name and the separator from the full path
1597 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
1601 // find the positions of the last dot and last path separator in the path
1602 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
1603 size_t posLastSlash
= fullpath
.find_last_of(sepPath
);
1605 if ( (posLastDot
!= wxString::npos
) &&
1606 ((format
== wxPATH_UNIX
) || (format
== wxPATH_VMS
)) )
1608 if ( (posLastDot
== 0) ||
1609 (fullpath
[posLastDot
- 1] == sepPath
[0u] ) )
1611 // under Unix and VMS, dot may be (and commonly is) the first
1612 // character of the filename, don't treat the entire filename as
1613 // extension in this case
1614 posLastDot
= wxString::npos
;
1618 // if we do have a dot and a slash, check that the dot is in the name part
1619 if ( (posLastDot
!= wxString::npos
) &&
1620 (posLastSlash
!= wxString::npos
) &&
1621 (posLastDot
< posLastSlash
) )
1623 // the dot is part of the path, not the start of the extension
1624 posLastDot
= wxString::npos
;
1627 // now fill in the variables provided by user
1630 if ( posLastSlash
== wxString::npos
)
1637 // take everything up to the path separator but take care to make
1638 // the path equal to something like '/', not empty, for the files
1639 // immediately under root directory
1640 size_t len
= posLastSlash
;
1642 // this rule does not apply to mac since we do not start with colons (sep)
1643 // except for relative paths
1644 if ( !len
&& format
!= wxPATH_MAC
)
1647 *pstrPath
= fullpath
.Left(len
);
1649 // special VMS hack: remove the initial bracket
1650 if ( format
== wxPATH_VMS
)
1652 if ( (*pstrPath
)[0u] == _T('[') )
1653 pstrPath
->erase(0, 1);
1660 // take all characters starting from the one after the last slash and
1661 // up to, but excluding, the last dot
1662 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
1664 if ( posLastDot
== wxString::npos
)
1666 // take all until the end
1667 count
= wxString::npos
;
1669 else if ( posLastSlash
== wxString::npos
)
1673 else // have both dot and slash
1675 count
= posLastDot
- posLastSlash
- 1;
1678 *pstrName
= fullpath
.Mid(nStart
, count
);
1683 if ( posLastDot
== wxString::npos
)
1690 // take everything after the dot
1691 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
1697 void wxFileName::SplitPath(const wxString
& fullpath
,
1701 wxPathFormat format
)
1704 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
1708 path
->Prepend(wxGetVolumeString(volume
, format
));
1712 // ----------------------------------------------------------------------------
1714 // ----------------------------------------------------------------------------
1718 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
1719 const wxDateTime
*dtMod
,
1720 const wxDateTime
*dtCreate
)
1722 #if defined(__WIN32__)
1725 // VZ: please let me know how to do this if you can
1726 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1730 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
1733 FILETIME ftAccess
, ftCreate
, ftWrite
;
1736 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
1738 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
1740 ConvertWxToFileTime(&ftWrite
, *dtMod
);
1742 if ( ::SetFileTime(fh
,
1743 dtCreate
? &ftCreate
: NULL
,
1744 dtAccess
? &ftAccess
: NULL
,
1745 dtMod
? &ftWrite
: NULL
) )
1751 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1752 if ( !dtAccess
&& !dtMod
)
1754 // can't modify the creation time anyhow, don't try
1758 // if dtAccess or dtMod is not specified, use the other one (which must be
1759 // non NULL because of the test above) for both times
1761 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
1762 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
1763 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
1767 #else // other platform
1770 wxLogSysError(_("Failed to modify file times for '%s'"),
1771 GetFullPath().c_str());
1776 bool wxFileName::Touch()
1778 #if defined(__UNIX_LIKE__)
1779 // under Unix touching file is simple: just pass NULL to utime()
1780 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
1785 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1788 #else // other platform
1789 wxDateTime dtNow
= wxDateTime::Now();
1791 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
1795 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
1797 wxDateTime
*dtCreate
) const
1799 #if defined(__WIN32__)
1800 // we must use different methods for the files and directories under
1801 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1802 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1805 FILETIME ftAccess
, ftCreate
, ftWrite
;
1808 // implemented in msw/dir.cpp
1809 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
1810 FILETIME
*, FILETIME
*, FILETIME
*);
1812 // we should pass the path without the trailing separator to
1813 // wxGetDirectoryTimes()
1814 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
1815 &ftAccess
, &ftCreate
, &ftWrite
);
1819 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
1822 ok
= ::GetFileTime(fh
,
1823 dtCreate
? &ftCreate
: NULL
,
1824 dtAccess
? &ftAccess
: NULL
,
1825 dtMod
? &ftWrite
: NULL
) != 0;
1836 ConvertFileTimeToWx(dtCreate
, ftCreate
);
1838 ConvertFileTimeToWx(dtAccess
, ftAccess
);
1840 ConvertFileTimeToWx(dtMod
, ftWrite
);
1844 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1846 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
1849 dtAccess
->Set(stBuf
.st_atime
);
1851 dtMod
->Set(stBuf
.st_mtime
);
1853 dtCreate
->Set(stBuf
.st_ctime
);
1857 #else // other platform
1860 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1861 GetFullPath().c_str());
1866 #endif // wxUSE_DATETIME
1870 const short kMacExtensionMaxLength
= 16 ;
1871 class MacDefaultExtensionRecord
1874 MacDefaultExtensionRecord()
1877 m_type
= m_creator
= NULL
;
1879 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
1881 wxStrcpy( m_ext
, from
.m_ext
) ;
1882 m_type
= from
.m_type
;
1883 m_creator
= from
.m_creator
;
1885 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
1887 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
1888 m_ext
[kMacExtensionMaxLength
] = 0 ;
1890 m_creator
= creator
;
1892 wxChar m_ext
[kMacExtensionMaxLength
] ;
1897 #include "wx/dynarray.h"
1898 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
1900 bool gMacDefaultExtensionsInited
= false ;
1902 #include "wx/arrimpl.cpp"
1904 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
1906 MacDefaultExtensionArray gMacDefaultExtensions
;
1908 static void MacEnsureDefaultExtensionsLoaded()
1910 if ( !gMacDefaultExtensionsInited
)
1913 // load the default extensions
1914 MacDefaultExtensionRecord defaults
[1] =
1916 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
1919 // we could load the pc exchange prefs here too
1921 for ( size_t i
= 0 ; i
< WXSIZEOF( defaults
) ; ++i
)
1923 gMacDefaultExtensions
.Add( defaults
[i
] ) ;
1925 gMacDefaultExtensionsInited
= true ;
1928 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
1932 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1933 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1934 wxCHECK( err
== noErr
, false ) ;
1936 fndrInfo
.fdType
= type
;
1937 fndrInfo
.fdCreator
= creator
;
1938 FSpSetFInfo( &spec
, &fndrInfo
) ;
1942 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
1946 wxMacFilename2FSSpec(GetFullPath(),&spec
) ;
1947 OSErr err
= FSpGetFInfo( &spec
, &fndrInfo
) ;
1948 wxCHECK( err
== noErr
, false ) ;
1950 *type
= fndrInfo
.fdType
;
1951 *creator
= fndrInfo
.fdCreator
;
1955 bool wxFileName::MacSetDefaultTypeAndCreator()
1957 wxUint32 type
, creator
;
1958 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
1961 return MacSetTypeAndCreator( type
, creator
) ;
1966 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
1968 MacEnsureDefaultExtensionsLoaded() ;
1969 wxString extl
= ext
.Lower() ;
1970 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
1972 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
1974 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
1975 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
1982 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
1984 MacEnsureDefaultExtensionsLoaded() ;
1985 MacDefaultExtensionRecord rec
;
1987 rec
.m_creator
= creator
;
1988 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
1989 gMacDefaultExtensions
.Add( rec
) ;