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 specification
51 . separator between directory and subdirectory
52 ] between directory and file
55 // ============================================================================
57 // ============================================================================
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
63 // For compilers that support precompilation, includes "wx.h".
64 #include "wx/wxprec.h"
72 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
74 #include "wx/dynarray.h"
81 #include "wx/filename.h"
82 #include "wx/private/filename.h"
83 #include "wx/tokenzr.h"
84 #include "wx/config.h" // for wxExpandEnvVars
85 #include "wx/dynlib.h"
87 #if defined(__WIN32__) && defined(__MINGW32__)
88 #include "wx/msw/gccpriv.h"
92 #include "wx/msw/private.h"
95 #if defined(__WXMAC__)
96 #include "wx/mac/private.h" // includes mac headers
99 // utime() is POSIX so should normally be available on all Unices
101 #include <sys/types.h>
103 #include <sys/stat.h>
113 #include <sys/types.h>
115 #include <sys/stat.h>
126 #include <sys/utime.h>
127 #include <sys/stat.h>
138 #define MAX_PATH _MAX_PATH
142 wxULongLong wxInvalidSize
= (unsigned)-1;
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
149 // small helper class which opens and closes the file - we use it just to get
150 // a file handle for the given file name to pass it to some Win32 API function
151 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
162 wxFileHandle(const wxString
& filename
, OpenMode mode
)
164 m_hFile
= ::CreateFile
166 filename
.fn_str(), // name
167 mode
== Read
? GENERIC_READ
// access mask
169 FILE_SHARE_READ
| // sharing mode
170 FILE_SHARE_WRITE
, // (allow everything)
171 NULL
, // no secutity attr
172 OPEN_EXISTING
, // creation disposition
174 NULL
// no template file
177 if ( m_hFile
== INVALID_HANDLE_VALUE
)
180 wxLogSysError(_("Failed to open '%s' for reading"),
183 wxLogSysError(_("Failed to open '%s' for writing"),
190 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
192 if ( !::CloseHandle(m_hFile
) )
194 wxLogSysError(_("Failed to close file handle"));
199 // return true only if the file could be opened successfully
200 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
203 operator HANDLE() const { return m_hFile
; }
211 // ----------------------------------------------------------------------------
213 // ----------------------------------------------------------------------------
215 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
217 // convert between wxDateTime and FILETIME which is a 64-bit value representing
218 // the number of 100-nanosecond intervals since January 1, 1601.
220 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
222 FILETIME ftcopy
= ft
;
224 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
226 wxLogLastError(_T("FileTimeToLocalFileTime"));
230 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
232 wxLogLastError(_T("FileTimeToSystemTime"));
235 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
236 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
239 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
242 st
.wDay
= dt
.GetDay();
243 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
244 st
.wYear
= (WORD
)dt
.GetYear();
245 st
.wHour
= dt
.GetHour();
246 st
.wMinute
= dt
.GetMinute();
247 st
.wSecond
= dt
.GetSecond();
248 st
.wMilliseconds
= dt
.GetMillisecond();
251 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
253 wxLogLastError(_T("SystemTimeToFileTime"));
256 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
258 wxLogLastError(_T("LocalFileTimeToFileTime"));
262 #endif // wxUSE_DATETIME && __WIN32__
264 // return a string with the volume par
265 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
269 if ( !volume
.empty() )
271 format
= wxFileName::GetFormat(format
);
273 // Special Windows UNC paths hack, part 2: undo what we did in
274 // SplitPath() and make an UNC path if we have a drive which is not a
275 // single letter (hopefully the network shares can't be one letter only
276 // although I didn't find any authoritative docs on this)
277 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
279 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
281 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
283 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
291 // return true if the format used is the DOS/Windows one and the string looks
293 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
295 return format
== wxPATH_DOS
&&
296 path
.length() >= 4 && // "\\a" can't be a UNC path
297 path
[0u] == wxFILE_SEP_PATH_DOS
&&
298 path
[1u] == wxFILE_SEP_PATH_DOS
&&
299 path
[2u] != wxFILE_SEP_PATH_DOS
;
302 // ============================================================================
304 // ============================================================================
306 // ----------------------------------------------------------------------------
307 // wxFileName construction
308 // ----------------------------------------------------------------------------
310 void wxFileName::Assign( const wxFileName
&filepath
)
312 m_volume
= filepath
.GetVolume();
313 m_dirs
= filepath
.GetDirs();
314 m_name
= filepath
.GetName();
315 m_ext
= filepath
.GetExt();
316 m_relative
= filepath
.m_relative
;
317 m_hasExt
= filepath
.m_hasExt
;
320 void wxFileName::Assign(const wxString
& volume
,
321 const wxString
& path
,
322 const wxString
& name
,
327 // we should ignore paths which look like UNC shares because we already
328 // have the volume here and the UNC notation (\\server\path) is only valid
329 // for paths which don't start with a volume, so prevent SetPath() from
330 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
332 // note also that this is a rather ugly way to do what we want (passing
333 // some kind of flag telling to ignore UNC paths to SetPath() would be
334 // better) but this is the safest thing to do to avoid breaking backwards
335 // compatibility in 2.8
336 if ( IsUNCPath(path
, format
) )
338 // remove one of the 2 leading backslashes to ensure that it's not
339 // recognized as an UNC path by SetPath()
340 wxString
pathNonUNC(path
, 1, wxString::npos
);
341 SetPath(pathNonUNC
, format
);
343 else // no UNC complications
345 SetPath(path
, format
);
355 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
359 if ( pathOrig
.empty() )
367 format
= GetFormat( format
);
369 // 0) deal with possible volume part first
372 SplitVolume(pathOrig
, &volume
, &path
, format
);
373 if ( !volume
.empty() )
380 // 1) Determine if the path is relative or absolute.
381 wxChar leadingChar
= path
[0u];
386 m_relative
= leadingChar
== wxT(':');
388 // We then remove a leading ":". The reason is in our
389 // storage form for relative paths:
390 // ":dir:file.txt" actually means "./dir/file.txt" in
391 // DOS notation and should get stored as
392 // (relative) (dir) (file.txt)
393 // "::dir:file.txt" actually means "../dir/file.txt"
394 // stored as (relative) (..) (dir) (file.txt)
395 // This is important only for the Mac as an empty dir
396 // actually means <UP>, whereas under DOS, double
397 // slashes can be ignored: "\\\\" is the same as "\\".
403 // TODO: what is the relative path format here?
408 wxFAIL_MSG( _T("Unknown path format") );
409 // !! Fall through !!
412 // the paths of the form "~" or "~username" are absolute
413 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
417 m_relative
= !IsPathSeparator(leadingChar
, format
);
422 // 2) Break up the path into its members. If the original path
423 // was just "/" or "\\", m_dirs will be empty. We know from
424 // the m_relative field, if this means "nothing" or "root dir".
426 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
428 while ( tn
.HasMoreTokens() )
430 wxString token
= tn
.GetNextToken();
432 // Remove empty token under DOS and Unix, interpret them
436 if (format
== wxPATH_MAC
)
437 m_dirs
.Add( wxT("..") );
447 void wxFileName::Assign(const wxString
& fullpath
,
450 wxString volume
, path
, name
, ext
;
452 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
454 Assign(volume
, path
, name
, ext
, hasExt
, format
);
457 void wxFileName::Assign(const wxString
& fullpathOrig
,
458 const wxString
& fullname
,
461 // always recognize fullpath as directory, even if it doesn't end with a
463 wxString fullpath
= fullpathOrig
;
464 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
466 fullpath
+= GetPathSeparator(format
);
469 wxString volume
, path
, name
, ext
;
472 // do some consistency checks in debug mode: the name should be really just
473 // the filename and the path should be really just a path
475 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
477 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
479 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
480 _T("the file name shouldn't contain the path") );
482 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
484 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
485 _T("the path shouldn't contain file name nor extension") );
487 #else // !__WXDEBUG__
488 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
489 &name
, &ext
, &hasExt
, format
);
490 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
491 #endif // __WXDEBUG__/!__WXDEBUG__
493 Assign(volume
, path
, name
, ext
, hasExt
, format
);
496 void wxFileName::Assign(const wxString
& pathOrig
,
497 const wxString
& name
,
503 SplitVolume(pathOrig
, &volume
, &path
, format
);
505 Assign(volume
, path
, name
, ext
, format
);
508 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
510 Assign(dir
, wxEmptyString
, format
);
513 void wxFileName::Clear()
519 m_ext
= wxEmptyString
;
521 // we don't have any absolute path for now
529 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
531 return wxFileName(file
, format
);
535 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
538 fn
.AssignDir(dir
, format
);
542 // ----------------------------------------------------------------------------
544 // ----------------------------------------------------------------------------
546 bool wxFileName::FileExists() const
548 return wxFileName::FileExists( GetFullPath() );
551 bool wxFileName::FileExists( const wxString
&file
)
553 return ::wxFileExists( file
);
556 bool wxFileName::DirExists() const
558 return wxFileName::DirExists( GetPath() );
561 bool wxFileName::DirExists( const wxString
&dir
)
563 return ::wxDirExists( dir
);
566 // ----------------------------------------------------------------------------
567 // CWD and HOME stuff
568 // ----------------------------------------------------------------------------
570 void wxFileName::AssignCwd(const wxString
& volume
)
572 AssignDir(wxFileName::GetCwd(volume
));
576 wxString
wxFileName::GetCwd(const wxString
& volume
)
578 // if we have the volume, we must get the current directory on this drive
579 // and to do this we have to chdir to this volume - at least under Windows,
580 // I don't know how to get the current drive on another volume elsewhere
583 if ( !volume
.empty() )
586 SetCwd(volume
+ GetVolumeSeparator());
589 wxString cwd
= ::wxGetCwd();
591 if ( !volume
.empty() )
599 bool wxFileName::SetCwd()
601 return wxFileName::SetCwd( GetPath() );
604 bool wxFileName::SetCwd( const wxString
&cwd
)
606 return ::wxSetWorkingDirectory( cwd
);
609 void wxFileName::AssignHomeDir()
611 AssignDir(wxFileName::GetHomeDir());
614 wxString
wxFileName::GetHomeDir()
616 return ::wxGetHomeDir();
620 // ----------------------------------------------------------------------------
621 // CreateTempFileName
622 // ----------------------------------------------------------------------------
624 #if wxUSE_FILE || wxUSE_FFILE
627 #if !defined wx_fdopen && defined HAVE_FDOPEN
628 #define wx_fdopen fdopen
631 // NB: GetTempFileName() under Windows creates the file, so using
632 // O_EXCL there would fail
634 #define wxOPEN_EXCL 0
636 #define wxOPEN_EXCL O_EXCL
640 #ifdef wxOpenOSFHandle
641 #define WX_HAVE_DELETE_ON_CLOSE
642 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
644 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
646 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
648 DWORD disposition
= OPEN_ALWAYS
;
650 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
651 FILE_FLAG_DELETE_ON_CLOSE
;
653 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
654 disposition
, attributes
, NULL
);
656 return wxOpenOSFHandle(h
, wxO_BINARY
);
658 #endif // wxOpenOSFHandle
661 // Helper to open the file
663 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
665 #ifdef WX_HAVE_DELETE_ON_CLOSE
667 return wxOpenWithDeleteOnClose(path
);
670 *deleteOnClose
= false;
672 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
677 // Helper to open the file and attach it to the wxFFile
679 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
682 *deleteOnClose
= false;
683 return file
->Open(path
, _T("w+b"));
685 int fd
= wxTempOpen(path
, deleteOnClose
);
688 file
->Attach(wx_fdopen(fd
, "w+b"));
689 return file
->IsOpened();
692 #endif // wxUSE_FFILE
696 #define WXFILEARGS(x, y) y
698 #define WXFILEARGS(x, y) x
700 #define WXFILEARGS(x, y) x, y
704 // Implementation of wxFileName::CreateTempFileName().
706 static wxString
wxCreateTempImpl(
707 const wxString
& prefix
,
708 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
709 bool *deleteOnClose
= NULL
)
711 #if wxUSE_FILE && wxUSE_FFILE
712 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
714 wxString path
, dir
, name
;
715 bool wantDeleteOnClose
= false;
719 // set the result to false initially
720 wantDeleteOnClose
= *deleteOnClose
;
721 *deleteOnClose
= false;
725 // easier if it alwasys points to something
726 deleteOnClose
= &wantDeleteOnClose
;
729 // use the directory specified by the prefix
730 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
734 dir
= wxFileName::GetTempDir();
737 #if defined(__WXWINCE__)
738 path
= dir
+ wxT("\\") + name
;
740 while (wxFileName::FileExists(path
))
742 path
= dir
+ wxT("\\") + name
;
747 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
748 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
749 wxStringBuffer(path
, MAX_PATH
+ 1)) )
751 wxLogLastError(_T("GetTempFileName"));
759 if ( !wxEndsWithPathSeparator(dir
) &&
760 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
762 path
+= wxFILE_SEP_PATH
;
767 #if defined(HAVE_MKSTEMP)
768 // scratch space for mkstemp()
769 path
+= _T("XXXXXX");
771 // we need to copy the path to the buffer in which mkstemp() can modify it
772 wxCharBuffer
buf(path
.fn_str());
774 // cast is safe because the string length doesn't change
775 int fdTemp
= mkstemp( (char*)(const char*) buf
);
778 // this might be not necessary as mkstemp() on most systems should have
779 // already done it but it doesn't hurt neither...
782 else // mkstemp() succeeded
784 path
= wxConvFile
.cMB2WX( (const char*) buf
);
787 // avoid leaking the fd
790 fileTemp
->Attach(fdTemp
);
799 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
801 ffileTemp
->Open(path
, _T("r+b"));
812 #else // !HAVE_MKSTEMP
816 path
+= _T("XXXXXX");
818 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
819 if ( !mktemp( (char*)(const char*) buf
) )
825 path
= wxConvFile
.cMB2WX( (const char*) buf
);
827 #else // !HAVE_MKTEMP (includes __DOS__)
828 // generate the unique file name ourselves
829 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
830 path
<< (unsigned int)getpid();
835 static const size_t numTries
= 1000;
836 for ( size_t n
= 0; n
< numTries
; n
++ )
838 // 3 hex digits is enough for numTries == 1000 < 4096
839 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
840 if ( !wxFileName::FileExists(pathTry
) )
849 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
851 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
853 #endif // Windows/!Windows
857 wxLogSysError(_("Failed to create a temporary file name"));
863 // open the file - of course, there is a race condition here, this is
864 // why we always prefer using mkstemp()...
866 if ( fileTemp
&& !fileTemp
->IsOpened() )
868 *deleteOnClose
= wantDeleteOnClose
;
869 int fd
= wxTempOpen(path
, deleteOnClose
);
871 fileTemp
->Attach(fd
);
878 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
880 *deleteOnClose
= wantDeleteOnClose
;
881 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
887 // FIXME: If !ok here should we loop and try again with another
888 // file name? That is the standard recourse if open(O_EXCL)
889 // fails, though of course it should be protected against
890 // possible infinite looping too.
892 wxLogError(_("Failed to open temporary file."));
902 static bool wxCreateTempImpl(
903 const wxString
& prefix
,
904 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
907 bool deleteOnClose
= true;
909 *name
= wxCreateTempImpl(prefix
,
910 WXFILEARGS(fileTemp
, ffileTemp
),
913 bool ok
= !name
->empty();
918 else if (ok
&& wxRemoveFile(*name
))
926 static void wxAssignTempImpl(
928 const wxString
& prefix
,
929 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
932 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
934 if ( tempname
.empty() )
936 // error, failed to get temp file name
941 fn
->Assign(tempname
);
946 void wxFileName::AssignTempFileName(const wxString
& prefix
)
948 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
952 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
954 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
957 #endif // wxUSE_FILE || wxUSE_FFILE
962 wxString
wxCreateTempFileName(const wxString
& prefix
,
966 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
969 bool wxCreateTempFile(const wxString
& prefix
,
973 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
976 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
978 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
983 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
985 return wxCreateTempFileName(prefix
, fileTemp
);
993 wxString
wxCreateTempFileName(const wxString
& prefix
,
997 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1000 bool wxCreateTempFile(const wxString
& prefix
,
1004 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1008 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1010 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1015 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1017 return wxCreateTempFileName(prefix
, fileTemp
);
1020 #endif // wxUSE_FFILE
1023 // ----------------------------------------------------------------------------
1024 // directory operations
1025 // ----------------------------------------------------------------------------
1027 wxString
wxFileName::GetTempDir()
1030 dir
= wxGetenv(_T("TMPDIR"));
1033 dir
= wxGetenv(_T("TMP"));
1036 dir
= wxGetenv(_T("TEMP"));
1040 #if defined(__WXWINCE__)
1043 // FIXME. Create \temp dir?
1044 if (DirExists(wxT("\\temp")))
1045 dir
= wxT("\\temp");
1047 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1051 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1053 wxLogLastError(_T("GetTempPath"));
1058 // GetTempFileName() fails if we pass it an empty string
1067 #if defined(__DOS__) || defined(__OS2__)
1069 #elif defined(__WXMAC__)
1070 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1080 bool wxFileName::Mkdir( int perm
, int flags
)
1082 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1085 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1087 if ( flags
& wxPATH_MKDIR_FULL
)
1089 // split the path in components
1090 wxFileName filename
;
1091 filename
.AssignDir(dir
);
1094 if ( filename
.HasVolume())
1096 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1099 wxArrayString dirs
= filename
.GetDirs();
1100 size_t count
= dirs
.GetCount();
1101 for ( size_t i
= 0; i
< count
; i
++ )
1104 #if defined(__WXMAC__) && !defined(__DARWIN__)
1105 // relative pathnames are exactely the other way round under mac...
1106 !filename
.IsAbsolute()
1108 filename
.IsAbsolute()
1111 currPath
+= wxFILE_SEP_PATH
;
1112 currPath
+= dirs
[i
];
1114 if (!DirExists(currPath
))
1116 if (!wxMkdir(currPath
, perm
))
1118 // no need to try creating further directories
1128 return ::wxMkdir( dir
, perm
);
1131 bool wxFileName::Rmdir()
1133 return wxFileName::Rmdir( GetPath() );
1136 bool wxFileName::Rmdir( const wxString
&dir
)
1138 return ::wxRmdir( dir
);
1141 // ----------------------------------------------------------------------------
1142 // path normalization
1143 // ----------------------------------------------------------------------------
1145 bool wxFileName::Normalize(int flags
,
1146 const wxString
& cwd
,
1147 wxPathFormat format
)
1149 // deal with env vars renaming first as this may seriously change the path
1150 if ( flags
& wxPATH_NORM_ENV_VARS
)
1152 wxString pathOrig
= GetFullPath(format
);
1153 wxString path
= wxExpandEnvVars(pathOrig
);
1154 if ( path
!= pathOrig
)
1161 // the existing path components
1162 wxArrayString dirs
= GetDirs();
1164 // the path to prepend in front to make the path absolute
1167 format
= GetFormat(format
);
1169 // set up the directory to use for making the path absolute later
1170 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1174 curDir
.AssignCwd(GetVolume());
1176 else // cwd provided
1178 curDir
.AssignDir(cwd
);
1182 // handle ~ stuff under Unix only
1183 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
1185 if ( !dirs
.IsEmpty() )
1187 wxString dir
= dirs
[0u];
1188 if ( !dir
.empty() && dir
[0u] == _T('~') )
1190 // to make the path absolute use the home directory
1191 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1193 // if we are expanding the tilde, then this path
1194 // *should* be already relative (since we checked for
1195 // the tilde only in the first char of the first dir);
1196 // if m_relative==false, it's because it was initialized
1197 // from a string which started with /~; in that case
1198 // we reach this point but then need m_relative=true
1199 // for relative->absolute expansion later
1207 // transform relative path into abs one
1208 if ( curDir
.IsOk() )
1210 // this path may be relative because it doesn't have the volume name
1211 // and still have m_relative=true; in this case we shouldn't modify
1212 // our directory components but just set the current volume
1213 if ( !HasVolume() && curDir
.HasVolume() )
1215 SetVolume(curDir
.GetVolume());
1219 // yes, it was the case - we don't need curDir then
1224 // finally, prepend curDir to the dirs array
1225 wxArrayString dirsNew
= curDir
.GetDirs();
1226 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1228 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1229 // return for some reason an absolute path, then curDir maybe not be absolute!
1230 if ( curDir
.IsAbsolute(format
) )
1232 // we have prepended an absolute path and thus we are now an absolute
1236 // else if (flags & wxPATH_NORM_ABSOLUTE):
1237 // should we warn the user that we didn't manage to make the path absolute?
1240 // now deal with ".", ".." and the rest
1242 size_t count
= dirs
.GetCount();
1243 for ( size_t n
= 0; n
< count
; n
++ )
1245 wxString dir
= dirs
[n
];
1247 if ( flags
& wxPATH_NORM_DOTS
)
1249 if ( dir
== wxT(".") )
1255 if ( dir
== wxT("..") )
1257 if ( m_dirs
.IsEmpty() )
1259 wxLogError(_("The path '%s' contains too many \"..\"!"),
1260 GetFullPath().c_str());
1264 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1269 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1277 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1278 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1281 if (GetShortcutTarget(GetFullPath(format
), filename
))
1283 // Repeat this since we may now have a new path
1284 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1286 filename
.MakeLower();
1294 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1296 // VZ: expand env vars here too?
1298 m_volume
.MakeLower();
1303 #if defined(__WIN32__)
1304 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1306 Assign(GetLongPath());
1313 // ----------------------------------------------------------------------------
1314 // get the shortcut target
1315 // ----------------------------------------------------------------------------
1317 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1318 // The .lnk file is a plain text file so it should be easy to
1319 // make it work. Hint from Google Groups:
1320 // "If you open up a lnk file, you'll see a
1321 // number, followed by a pound sign (#), followed by more text. The
1322 // number is the number of characters that follows the pound sign. The
1323 // characters after the pound sign are the command line (which _can_
1324 // include arguments) to be executed. Any path (e.g. \windows\program
1325 // files\myapp.exe) that includes spaces needs to be enclosed in
1326 // quotation marks."
1328 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1329 // The following lines are necessary under WinCE
1330 // #include "wx/msw/private.h"
1331 // #include <ole2.h>
1333 #if defined(__WXWINCE__)
1334 #include <shlguid.h>
1337 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1338 wxString
& targetFilename
,
1339 wxString
* arguments
)
1341 wxString path
, file
, ext
;
1342 wxSplitPath(shortcutPath
, & path
, & file
, & ext
);
1346 bool success
= false;
1348 // Assume it's not a shortcut if it doesn't end with lnk
1349 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1352 // create a ShellLink object
1353 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1354 IID_IShellLink
, (LPVOID
*) &psl
);
1356 if (SUCCEEDED(hres
))
1359 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1360 if (SUCCEEDED(hres
))
1362 WCHAR wsz
[MAX_PATH
];
1364 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1367 hres
= ppf
->Load(wsz
, 0);
1370 if (SUCCEEDED(hres
))
1373 // Wrong prototype in early versions
1374 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1375 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1377 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1379 targetFilename
= wxString(buf
);
1380 success
= (shortcutPath
!= targetFilename
);
1382 psl
->GetArguments(buf
, 2048);
1384 if (!args
.empty() && arguments
)
1396 #endif // __WIN32__ && !__WXWINCE__
1399 // ----------------------------------------------------------------------------
1400 // absolute/relative paths
1401 // ----------------------------------------------------------------------------
1403 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1405 // if our path doesn't start with a path separator, it's not an absolute
1410 if ( !GetVolumeSeparator(format
).empty() )
1412 // this format has volumes and an absolute path must have one, it's not
1413 // enough to have the full path to bean absolute file under Windows
1414 if ( GetVolume().empty() )
1421 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1423 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1425 // get cwd only once - small time saving
1426 wxString cwd
= wxGetCwd();
1427 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1428 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1430 bool withCase
= IsCaseSensitive(format
);
1432 // we can't do anything if the files live on different volumes
1433 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1439 // same drive, so we don't need our volume
1442 // remove common directories starting at the top
1443 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1444 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1447 fnBase
.m_dirs
.RemoveAt(0);
1450 // add as many ".." as needed
1451 size_t count
= fnBase
.m_dirs
.GetCount();
1452 for ( size_t i
= 0; i
< count
; i
++ )
1454 m_dirs
.Insert(wxT(".."), 0u);
1457 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1459 // a directory made relative with respect to itself is '.' under Unix
1460 // and DOS, by definition (but we don't have to insert "./" for the
1462 if ( m_dirs
.IsEmpty() && IsDir() )
1464 m_dirs
.Add(_T('.'));
1474 // ----------------------------------------------------------------------------
1475 // filename kind tests
1476 // ----------------------------------------------------------------------------
1478 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1480 wxFileName fn1
= *this,
1483 // get cwd only once - small time saving
1484 wxString cwd
= wxGetCwd();
1485 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1486 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1488 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1491 // TODO: compare inodes for Unix, this works even when filenames are
1492 // different but files are the same (symlinks) (VZ)
1498 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1500 // only Unix filenames are truely case-sensitive
1501 return GetFormat(format
) == wxPATH_UNIX
;
1505 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1507 // Inits to forbidden characters that are common to (almost) all platforms.
1508 wxString strForbiddenChars
= wxT("*?");
1510 // If asserts, wxPathFormat has been changed. In case of a new path format
1511 // addition, the following code might have to be updated.
1512 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1513 switch ( GetFormat(format
) )
1516 wxFAIL_MSG( wxT("Unknown path format") );
1517 // !! Fall through !!
1523 // On a Mac even names with * and ? are allowed (Tested with OS
1524 // 9.2.1 and OS X 10.2.5)
1525 strForbiddenChars
= wxEmptyString
;
1529 strForbiddenChars
+= wxT("\\/:\"<>|");
1536 return strForbiddenChars
;
1540 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1543 return wxEmptyString
;
1547 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1548 (GetFormat(format
) == wxPATH_VMS
) )
1550 sepVol
= wxFILE_SEP_DSK
;
1559 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1562 switch ( GetFormat(format
) )
1565 // accept both as native APIs do but put the native one first as
1566 // this is the one we use in GetFullPath()
1567 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1571 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1575 seps
= wxFILE_SEP_PATH_UNIX
;
1579 seps
= wxFILE_SEP_PATH_MAC
;
1583 seps
= wxFILE_SEP_PATH_VMS
;
1591 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1593 format
= GetFormat(format
);
1595 // under VMS the end of the path is ']', not the path separator used to
1596 // separate the components
1597 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1601 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1603 // wxString::Find() doesn't work as expected with NUL - it will always find
1604 // it, so test for it separately
1605 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1608 // ----------------------------------------------------------------------------
1609 // path components manipulation
1610 // ----------------------------------------------------------------------------
1612 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1616 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1621 const size_t len
= dir
.length();
1622 for ( size_t n
= 0; n
< len
; n
++ )
1624 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1626 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1635 void wxFileName::AppendDir( const wxString
& dir
)
1637 if ( IsValidDirComponent(dir
) )
1641 void wxFileName::PrependDir( const wxString
& dir
)
1646 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1648 if ( IsValidDirComponent(dir
) )
1649 m_dirs
.Insert(dir
, before
);
1652 void wxFileName::RemoveDir(size_t pos
)
1654 m_dirs
.RemoveAt(pos
);
1657 // ----------------------------------------------------------------------------
1659 // ----------------------------------------------------------------------------
1661 void wxFileName::SetFullName(const wxString
& fullname
)
1663 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1664 &m_name
, &m_ext
, &m_hasExt
);
1667 wxString
wxFileName::GetFullName() const
1669 wxString fullname
= m_name
;
1672 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1678 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1680 format
= GetFormat( format
);
1684 // return the volume with the path as well if requested
1685 if ( flags
& wxPATH_GET_VOLUME
)
1687 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1690 // the leading character
1695 fullpath
+= wxFILE_SEP_PATH_MAC
;
1700 fullpath
+= wxFILE_SEP_PATH_DOS
;
1704 wxFAIL_MSG( wxT("Unknown path format") );
1710 // normally the absolute file names start with a slash
1711 // with one exception: the ones like "~/foo.bar" don't
1713 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1715 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1721 // no leading character here but use this place to unset
1722 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1723 // as, if I understand correctly, there should never be a dot
1724 // before the closing bracket
1725 flags
&= ~wxPATH_GET_SEPARATOR
;
1728 if ( m_dirs
.empty() )
1730 // there is nothing more
1734 // then concatenate all the path components using the path separator
1735 if ( format
== wxPATH_VMS
)
1737 fullpath
+= wxT('[');
1740 const size_t dirCount
= m_dirs
.GetCount();
1741 for ( size_t i
= 0; i
< dirCount
; i
++ )
1746 if ( m_dirs
[i
] == wxT(".") )
1748 // skip appending ':', this shouldn't be done in this
1749 // case as "::" is interpreted as ".." under Unix
1753 // convert back from ".." to nothing
1754 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1755 fullpath
+= m_dirs
[i
];
1759 wxFAIL_MSG( wxT("Unexpected path format") );
1760 // still fall through
1764 fullpath
+= m_dirs
[i
];
1768 // TODO: What to do with ".." under VMS
1770 // convert back from ".." to nothing
1771 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1772 fullpath
+= m_dirs
[i
];
1776 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1777 fullpath
+= GetPathSeparator(format
);
1780 if ( format
== wxPATH_VMS
)
1782 fullpath
+= wxT(']');
1788 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1790 // we already have a function to get the path
1791 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1794 // now just add the file name and extension to it
1795 fullpath
+= GetFullName();
1800 // Return the short form of the path (returns identity on non-Windows platforms)
1801 wxString
wxFileName::GetShortPath() const
1803 wxString
path(GetFullPath());
1805 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1806 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
1810 if ( ::GetShortPathName
1813 wxStringBuffer(pathOut
, sz
),
1825 // Return the long form of the path (returns identity on non-Windows platforms)
1826 wxString
wxFileName::GetLongPath() const
1829 path
= GetFullPath();
1831 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1833 #if wxUSE_DYNAMIC_LOADER
1834 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1836 // this is MT-safe as in the worst case we're going to resolve the function
1837 // twice -- but as the result is the same in both threads, it's ok
1838 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1839 if ( !s_pfnGetLongPathName
)
1841 static bool s_triedToLoad
= false;
1843 if ( !s_triedToLoad
)
1845 s_triedToLoad
= true;
1847 wxDynamicLibrary
dllKernel(_T("kernel32"));
1849 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1854 #endif // Unicode/ANSI
1856 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1858 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1859 dllKernel
.GetSymbol(GetLongPathName
);
1862 // note that kernel32.dll can be unloaded, it stays in memory
1863 // anyhow as all Win32 programs link to it and so it's safe to call
1864 // GetLongPathName() even after unloading it
1868 if ( s_pfnGetLongPathName
)
1870 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
1873 if ( (*s_pfnGetLongPathName
)
1876 wxStringBuffer(pathOut
, dwSize
),
1884 #endif // wxUSE_DYNAMIC_LOADER
1886 // The OS didn't support GetLongPathName, or some other error.
1887 // We need to call FindFirstFile on each component in turn.
1889 WIN32_FIND_DATA findFileData
;
1893 pathOut
= GetVolume() +
1894 GetVolumeSeparator(wxPATH_DOS
) +
1895 GetPathSeparator(wxPATH_DOS
);
1897 pathOut
= wxEmptyString
;
1899 wxArrayString dirs
= GetDirs();
1900 dirs
.Add(GetFullName());
1904 size_t count
= dirs
.GetCount();
1905 for ( size_t i
= 0; i
< count
; i
++ )
1907 // We're using pathOut to collect the long-name path, but using a
1908 // temporary for appending the last path component which may be
1910 tmpPath
= pathOut
+ dirs
[i
];
1912 if ( tmpPath
.empty() )
1915 // can't see this being necessary? MF
1916 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1918 // Can't pass a drive and root dir to FindFirstFile,
1919 // so continue to next dir
1920 tmpPath
+= wxFILE_SEP_PATH
;
1925 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
1926 if (hFind
== INVALID_HANDLE_VALUE
)
1928 // Error: most likely reason is that path doesn't exist, so
1929 // append any unprocessed parts and return
1930 for ( i
+= 1; i
< count
; i
++ )
1931 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1936 pathOut
+= findFileData
.cFileName
;
1937 if ( (i
< (count
-1)) )
1938 pathOut
+= wxFILE_SEP_PATH
;
1944 #endif // Win32/!Win32
1949 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1951 if (format
== wxPATH_NATIVE
)
1953 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1954 format
= wxPATH_DOS
;
1955 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1956 format
= wxPATH_MAC
;
1957 #elif defined(__VMS)
1958 format
= wxPATH_VMS
;
1960 format
= wxPATH_UNIX
;
1966 // ----------------------------------------------------------------------------
1967 // path splitting function
1968 // ----------------------------------------------------------------------------
1972 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
1973 wxString
*pstrVolume
,
1975 wxPathFormat format
)
1977 format
= GetFormat(format
);
1979 wxString fullpath
= fullpathWithVolume
;
1981 // special Windows UNC paths hack: transform \\share\path into share:path
1982 if ( IsUNCPath(fullpath
, format
) )
1984 fullpath
.erase(0, 2);
1986 size_t posFirstSlash
=
1987 fullpath
.find_first_of(GetPathTerminators(format
));
1988 if ( posFirstSlash
!= wxString::npos
)
1990 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1992 // UNC paths are always absolute, right? (FIXME)
1993 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1997 // We separate the volume here
1998 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2000 wxString sepVol
= GetVolumeSeparator(format
);
2002 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2003 if ( posFirstColon
!= wxString::npos
)
2007 *pstrVolume
= fullpath
.Left(posFirstColon
);
2010 // remove the volume name and the separator from the full path
2011 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2016 *pstrPath
= fullpath
;
2020 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2021 wxString
*pstrVolume
,
2026 wxPathFormat format
)
2028 format
= GetFormat(format
);
2031 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2033 // find the positions of the last dot and last path separator in the path
2034 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2035 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2037 // check whether this dot occurs at the very beginning of a path component
2038 if ( (posLastDot
!= wxString::npos
) &&
2040 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2041 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
2043 // dot may be (and commonly -- at least under Unix -- is) the first
2044 // character of the filename, don't treat the entire filename as
2045 // extension in this case
2046 posLastDot
= wxString::npos
;
2049 // if we do have a dot and a slash, check that the dot is in the name part
2050 if ( (posLastDot
!= wxString::npos
) &&
2051 (posLastSlash
!= wxString::npos
) &&
2052 (posLastDot
< posLastSlash
) )
2054 // the dot is part of the path, not the start of the extension
2055 posLastDot
= wxString::npos
;
2058 // now fill in the variables provided by user
2061 if ( posLastSlash
== wxString::npos
)
2068 // take everything up to the path separator but take care to make
2069 // the path equal to something like '/', not empty, for the files
2070 // immediately under root directory
2071 size_t len
= posLastSlash
;
2073 // this rule does not apply to mac since we do not start with colons (sep)
2074 // except for relative paths
2075 if ( !len
&& format
!= wxPATH_MAC
)
2078 *pstrPath
= fullpath
.Left(len
);
2080 // special VMS hack: remove the initial bracket
2081 if ( format
== wxPATH_VMS
)
2083 if ( (*pstrPath
)[0u] == _T('[') )
2084 pstrPath
->erase(0, 1);
2091 // take all characters starting from the one after the last slash and
2092 // up to, but excluding, the last dot
2093 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2095 if ( posLastDot
== wxString::npos
)
2097 // take all until the end
2098 count
= wxString::npos
;
2100 else if ( posLastSlash
== wxString::npos
)
2104 else // have both dot and slash
2106 count
= posLastDot
- posLastSlash
- 1;
2109 *pstrName
= fullpath
.Mid(nStart
, count
);
2112 // finally deal with the extension here: we have an added complication that
2113 // extension may be empty (but present) as in "foo." where trailing dot
2114 // indicates the empty extension at the end -- and hence we must remember
2115 // that we have it independently of pstrExt
2116 if ( posLastDot
== wxString::npos
)
2126 // take everything after the dot
2128 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2135 void wxFileName::SplitPath(const wxString
& fullpath
,
2139 wxPathFormat format
)
2142 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2146 path
->Prepend(wxGetVolumeString(volume
, format
));
2150 // ----------------------------------------------------------------------------
2152 // ----------------------------------------------------------------------------
2156 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2157 const wxDateTime
*dtMod
,
2158 const wxDateTime
*dtCreate
)
2160 #if defined(__WIN32__)
2163 // VZ: please let me know how to do this if you can
2164 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
2168 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
2171 FILETIME ftAccess
, ftCreate
, ftWrite
;
2174 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2176 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2178 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2180 if ( ::SetFileTime(fh
,
2181 dtCreate
? &ftCreate
: NULL
,
2182 dtAccess
? &ftAccess
: NULL
,
2183 dtMod
? &ftWrite
: NULL
) )
2189 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2190 wxUnusedVar(dtCreate
);
2192 if ( !dtAccess
&& !dtMod
)
2194 // can't modify the creation time anyhow, don't try
2198 // if dtAccess or dtMod is not specified, use the other one (which must be
2199 // non NULL because of the test above) for both times
2201 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2202 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2203 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2207 #else // other platform
2208 wxUnusedVar(dtAccess
);
2210 wxUnusedVar(dtCreate
);
2213 wxLogSysError(_("Failed to modify file times for '%s'"),
2214 GetFullPath().c_str());
2219 bool wxFileName::Touch()
2221 #if defined(__UNIX_LIKE__)
2222 // under Unix touching file is simple: just pass NULL to utime()
2223 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2228 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2231 #else // other platform
2232 wxDateTime dtNow
= wxDateTime::Now();
2234 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2238 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2240 wxDateTime
*dtCreate
) const
2242 #if defined(__WIN32__)
2243 // we must use different methods for the files and directories under
2244 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2245 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2248 FILETIME ftAccess
, ftCreate
, ftWrite
;
2251 // implemented in msw/dir.cpp
2252 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2253 FILETIME
*, FILETIME
*, FILETIME
*);
2255 // we should pass the path without the trailing separator to
2256 // wxGetDirectoryTimes()
2257 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2258 &ftAccess
, &ftCreate
, &ftWrite
);
2262 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2265 ok
= ::GetFileTime(fh
,
2266 dtCreate
? &ftCreate
: NULL
,
2267 dtAccess
? &ftAccess
: NULL
,
2268 dtMod
? &ftWrite
: NULL
) != 0;
2279 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2281 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2283 ConvertFileTimeToWx(dtMod
, ftWrite
);
2287 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2288 // no need to test for IsDir() here
2290 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2293 dtAccess
->Set(stBuf
.st_atime
);
2295 dtMod
->Set(stBuf
.st_mtime
);
2297 dtCreate
->Set(stBuf
.st_ctime
);
2301 #else // other platform
2302 wxUnusedVar(dtAccess
);
2304 wxUnusedVar(dtCreate
);
2307 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2308 GetFullPath().c_str());
2313 #endif // wxUSE_DATETIME
2316 // ----------------------------------------------------------------------------
2317 // file size functions
2318 // ----------------------------------------------------------------------------
2321 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2323 if (!wxFileExists(filename
))
2324 return wxInvalidSize
;
2326 #if defined(__WXPALMOS__)
2328 return wxInvalidSize
;
2329 #elif defined(__WIN32__)
2330 wxFileHandle
f(filename
, wxFileHandle::Read
);
2332 return wxInvalidSize
;
2334 DWORD lpFileSizeHigh
;
2335 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2336 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2337 return wxInvalidSize
;
2339 return wxULongLong(lpFileSizeHigh
, ret
);
2340 #else // ! __WIN32__
2342 #ifndef wxNEED_WX_UNISTD_H
2343 if (wxStat( filename
.fn_str() , &st
) != 0)
2345 if (wxStat( filename
, &st
) != 0)
2347 return wxInvalidSize
;
2348 return wxULongLong(st
.st_size
);
2353 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2354 const wxString
&nullsize
,
2357 static const double KILOBYTESIZE
= 1024.0;
2358 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2359 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2360 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2362 if (bs
== 0 || bs
== wxInvalidSize
)
2365 double bytesize
= bs
.ToDouble();
2366 if (bytesize
< KILOBYTESIZE
)
2367 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2368 if (bytesize
< MEGABYTESIZE
)
2369 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2370 if (bytesize
< GIGABYTESIZE
)
2371 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2372 if (bytesize
< TERABYTESIZE
)
2373 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2375 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2378 wxULongLong
wxFileName::GetSize() const
2380 return GetSize(GetFullPath());
2383 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2385 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2389 // ----------------------------------------------------------------------------
2390 // Mac-specific functions
2391 // ----------------------------------------------------------------------------
2395 const short kMacExtensionMaxLength
= 16 ;
2396 class MacDefaultExtensionRecord
2399 MacDefaultExtensionRecord()
2402 m_type
= m_creator
= 0 ;
2404 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
2406 wxStrcpy( m_ext
, from
.m_ext
) ;
2407 m_type
= from
.m_type
;
2408 m_creator
= from
.m_creator
;
2410 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
2412 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
2413 m_ext
[kMacExtensionMaxLength
] = 0 ;
2415 m_creator
= creator
;
2417 wxChar m_ext
[kMacExtensionMaxLength
] ;
2422 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
2424 bool gMacDefaultExtensionsInited
= false ;
2426 #include "wx/arrimpl.cpp"
2428 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
2430 MacDefaultExtensionArray gMacDefaultExtensions
;
2432 // load the default extensions
2433 MacDefaultExtensionRecord gDefaults
[] =
2435 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2436 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2437 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2440 static void MacEnsureDefaultExtensionsLoaded()
2442 if ( !gMacDefaultExtensionsInited
)
2444 // we could load the pc exchange prefs here too
2445 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2447 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2449 gMacDefaultExtensionsInited
= true ;
2453 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2456 FSCatalogInfo catInfo
;
2459 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2461 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2463 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2464 finfo
->fileType
= type
;
2465 finfo
->fileCreator
= creator
;
2466 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2473 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2476 FSCatalogInfo catInfo
;
2479 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2481 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2483 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2484 *type
= finfo
->fileType
;
2485 *creator
= finfo
->fileCreator
;
2492 bool wxFileName::MacSetDefaultTypeAndCreator()
2494 wxUint32 type
, creator
;
2495 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2498 return MacSetTypeAndCreator( type
, creator
) ;
2503 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2505 MacEnsureDefaultExtensionsLoaded() ;
2506 wxString extl
= ext
.Lower() ;
2507 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2509 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2511 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2512 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2519 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2521 MacEnsureDefaultExtensionsLoaded() ;
2522 MacDefaultExtensionRecord rec
;
2524 rec
.m_creator
= creator
;
2525 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
2526 gMacDefaultExtensions
.Add( rec
) ;