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"
80 #include "wx/filename.h"
81 #include "wx/private/filename.h"
82 #include "wx/tokenzr.h"
83 #include "wx/config.h" // for wxExpandEnvVars
84 #include "wx/dynlib.h"
86 #if defined(__WIN32__) && defined(__MINGW32__)
87 #include "wx/msw/gccpriv.h"
91 #include "wx/msw/private.h"
94 #if defined(__WXMAC__)
95 #include "wx/mac/private.h" // includes mac headers
98 // utime() is POSIX so should normally be available on all Unices
100 #include <sys/types.h>
102 #include <sys/stat.h>
112 #include <sys/types.h>
114 #include <sys/stat.h>
125 #include <sys/utime.h>
126 #include <sys/stat.h>
137 #define MAX_PATH _MAX_PATH
141 wxULongLong wxInvalidSize
= (unsigned)-1;
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
148 // small helper class which opens and closes the file - we use it just to get
149 // a file handle for the given file name to pass it to some Win32 API function
150 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
161 wxFileHandle(const wxString
& filename
, OpenMode mode
)
163 m_hFile
= ::CreateFile
166 mode
== Read
? GENERIC_READ
// access mask
168 FILE_SHARE_READ
| // sharing mode
169 FILE_SHARE_WRITE
, // (allow everything)
170 NULL
, // no secutity attr
171 OPEN_EXISTING
, // creation disposition
173 NULL
// no template file
176 if ( m_hFile
== INVALID_HANDLE_VALUE
)
179 wxLogSysError(_("Failed to open '%s' for reading"),
182 wxLogSysError(_("Failed to open '%s' for writing"),
189 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
191 if ( !::CloseHandle(m_hFile
) )
193 wxLogSysError(_("Failed to close file handle"));
198 // return true only if the file could be opened successfully
199 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
202 operator HANDLE() const { return m_hFile
; }
210 // ----------------------------------------------------------------------------
212 // ----------------------------------------------------------------------------
214 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
216 // convert between wxDateTime and FILETIME which is a 64-bit value representing
217 // the number of 100-nanosecond intervals since January 1, 1601.
219 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
221 FILETIME ftcopy
= ft
;
223 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
225 wxLogLastError(_T("FileTimeToLocalFileTime"));
229 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
231 wxLogLastError(_T("FileTimeToSystemTime"));
234 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
235 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
238 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
241 st
.wDay
= dt
.GetDay();
242 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
243 st
.wYear
= (WORD
)dt
.GetYear();
244 st
.wHour
= dt
.GetHour();
245 st
.wMinute
= dt
.GetMinute();
246 st
.wSecond
= dt
.GetSecond();
247 st
.wMilliseconds
= dt
.GetMillisecond();
250 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
252 wxLogLastError(_T("SystemTimeToFileTime"));
255 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
257 wxLogLastError(_T("LocalFileTimeToFileTime"));
261 #endif // wxUSE_DATETIME && __WIN32__
263 // return a string with the volume par
264 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
268 if ( !volume
.empty() )
270 format
= wxFileName::GetFormat(format
);
272 // Special Windows UNC paths hack, part 2: undo what we did in
273 // SplitPath() and make an UNC path if we have a drive which is not a
274 // single letter (hopefully the network shares can't be one letter only
275 // although I didn't find any authoritative docs on this)
276 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
278 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
280 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
282 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
290 // return true if the format used is the DOS/Windows one and the string looks
292 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
294 return format
== wxPATH_DOS
&&
295 path
.length() >= 4 && // "\\a" can't be a UNC path
296 path
[0u] == wxFILE_SEP_PATH_DOS
&&
297 path
[1u] == wxFILE_SEP_PATH_DOS
&&
298 path
[2u] != wxFILE_SEP_PATH_DOS
;
301 // ============================================================================
303 // ============================================================================
305 // ----------------------------------------------------------------------------
306 // wxFileName construction
307 // ----------------------------------------------------------------------------
309 void wxFileName::Assign( const wxFileName
&filepath
)
311 m_volume
= filepath
.GetVolume();
312 m_dirs
= filepath
.GetDirs();
313 m_name
= filepath
.GetName();
314 m_ext
= filepath
.GetExt();
315 m_relative
= filepath
.m_relative
;
316 m_hasExt
= filepath
.m_hasExt
;
319 void wxFileName::Assign(const wxString
& volume
,
320 const wxString
& path
,
321 const wxString
& name
,
326 // we should ignore paths which look like UNC shares because we already
327 // have the volume here and the UNC notation (\\server\path) is only valid
328 // for paths which don't start with a volume, so prevent SetPath() from
329 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
331 // note also that this is a rather ugly way to do what we want (passing
332 // some kind of flag telling to ignore UNC paths to SetPath() would be
333 // better) but this is the safest thing to do to avoid breaking backwards
334 // compatibility in 2.8
335 if ( IsUNCPath(path
, format
) )
337 // remove one of the 2 leading backslashes to ensure that it's not
338 // recognized as an UNC path by SetPath()
339 wxString
pathNonUNC(path
, 1, wxString::npos
);
340 SetPath(pathNonUNC
, format
);
342 else // no UNC complications
344 SetPath(path
, format
);
354 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
358 if ( pathOrig
.empty() )
366 format
= GetFormat( format
);
368 // 0) deal with possible volume part first
371 SplitVolume(pathOrig
, &volume
, &path
, format
);
372 if ( !volume
.empty() )
379 // 1) Determine if the path is relative or absolute.
380 wxChar leadingChar
= path
[0u];
385 m_relative
= leadingChar
== wxT(':');
387 // We then remove a leading ":". The reason is in our
388 // storage form for relative paths:
389 // ":dir:file.txt" actually means "./dir/file.txt" in
390 // DOS notation and should get stored as
391 // (relative) (dir) (file.txt)
392 // "::dir:file.txt" actually means "../dir/file.txt"
393 // stored as (relative) (..) (dir) (file.txt)
394 // This is important only for the Mac as an empty dir
395 // actually means <UP>, whereas under DOS, double
396 // slashes can be ignored: "\\\\" is the same as "\\".
402 // TODO: what is the relative path format here?
407 wxFAIL_MSG( _T("Unknown path format") );
408 // !! Fall through !!
411 // the paths of the form "~" or "~username" are absolute
412 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
416 m_relative
= !IsPathSeparator(leadingChar
, format
);
421 // 2) Break up the path into its members. If the original path
422 // was just "/" or "\\", m_dirs will be empty. We know from
423 // the m_relative field, if this means "nothing" or "root dir".
425 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
427 while ( tn
.HasMoreTokens() )
429 wxString token
= tn
.GetNextToken();
431 // Remove empty token under DOS and Unix, interpret them
435 if (format
== wxPATH_MAC
)
436 m_dirs
.Add( wxT("..") );
446 void wxFileName::Assign(const wxString
& fullpath
,
449 wxString volume
, path
, name
, ext
;
451 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
453 Assign(volume
, path
, name
, ext
, hasExt
, format
);
456 void wxFileName::Assign(const wxString
& fullpathOrig
,
457 const wxString
& fullname
,
460 // always recognize fullpath as directory, even if it doesn't end with a
462 wxString fullpath
= fullpathOrig
;
463 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
465 fullpath
+= GetPathSeparator(format
);
468 wxString volume
, path
, name
, ext
;
471 // do some consistency checks in debug mode: the name should be really just
472 // the filename and the path should be really just a path
474 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
476 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
478 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
479 _T("the file name shouldn't contain the path") );
481 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
483 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
484 _T("the path shouldn't contain file name nor extension") );
486 #else // !__WXDEBUG__
487 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
488 &name
, &ext
, &hasExt
, format
);
489 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
490 #endif // __WXDEBUG__/!__WXDEBUG__
492 Assign(volume
, path
, name
, ext
, hasExt
, format
);
495 void wxFileName::Assign(const wxString
& pathOrig
,
496 const wxString
& name
,
502 SplitVolume(pathOrig
, &volume
, &path
, format
);
504 Assign(volume
, path
, name
, ext
, format
);
507 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
509 Assign(dir
, wxEmptyString
, format
);
512 void wxFileName::Clear()
518 m_ext
= wxEmptyString
;
520 // we don't have any absolute path for now
528 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
530 return wxFileName(file
, format
);
534 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
537 fn
.AssignDir(dir
, format
);
541 // ----------------------------------------------------------------------------
543 // ----------------------------------------------------------------------------
545 bool wxFileName::FileExists() const
547 return wxFileName::FileExists( GetFullPath() );
550 bool wxFileName::FileExists( const wxString
&file
)
552 return ::wxFileExists( file
);
555 bool wxFileName::DirExists() const
557 return wxFileName::DirExists( GetPath() );
560 bool wxFileName::DirExists( const wxString
&dir
)
562 return ::wxDirExists( dir
);
565 // ----------------------------------------------------------------------------
566 // CWD and HOME stuff
567 // ----------------------------------------------------------------------------
569 void wxFileName::AssignCwd(const wxString
& volume
)
571 AssignDir(wxFileName::GetCwd(volume
));
575 wxString
wxFileName::GetCwd(const wxString
& volume
)
577 // if we have the volume, we must get the current directory on this drive
578 // and to do this we have to chdir to this volume - at least under Windows,
579 // I don't know how to get the current drive on another volume elsewhere
582 if ( !volume
.empty() )
585 SetCwd(volume
+ GetVolumeSeparator());
588 wxString cwd
= ::wxGetCwd();
590 if ( !volume
.empty() )
598 bool wxFileName::SetCwd()
600 return wxFileName::SetCwd( GetPath() );
603 bool wxFileName::SetCwd( const wxString
&cwd
)
605 return ::wxSetWorkingDirectory( cwd
);
608 void wxFileName::AssignHomeDir()
610 AssignDir(wxFileName::GetHomeDir());
613 wxString
wxFileName::GetHomeDir()
615 return ::wxGetHomeDir();
619 // ----------------------------------------------------------------------------
620 // CreateTempFileName
621 // ----------------------------------------------------------------------------
623 #if wxUSE_FILE || wxUSE_FFILE
626 #if !defined wx_fdopen && defined HAVE_FDOPEN
627 #define wx_fdopen fdopen
630 // NB: GetTempFileName() under Windows creates the file, so using
631 // O_EXCL there would fail
633 #define wxOPEN_EXCL 0
635 #define wxOPEN_EXCL O_EXCL
639 #ifdef wxOpenOSFHandle
640 #define WX_HAVE_DELETE_ON_CLOSE
641 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
643 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
645 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
647 DWORD disposition
= OPEN_ALWAYS
;
649 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
650 FILE_FLAG_DELETE_ON_CLOSE
;
652 HANDLE h
= ::CreateFile(filename
, access
, 0, NULL
,
653 disposition
, attributes
, NULL
);
655 return wxOpenOSFHandle(h
, wxO_BINARY
);
657 #endif // wxOpenOSFHandle
660 // Helper to open the file
662 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
664 #ifdef WX_HAVE_DELETE_ON_CLOSE
666 return wxOpenWithDeleteOnClose(path
);
669 *deleteOnClose
= false;
671 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
676 // Helper to open the file and attach it to the wxFFile
678 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
681 *deleteOnClose
= false;
682 return file
->Open(path
, _T("w+b"));
684 int fd
= wxTempOpen(path
, deleteOnClose
);
687 file
->Attach(wx_fdopen(fd
, "w+b"));
688 return file
->IsOpened();
691 #endif // wxUSE_FFILE
695 #define WXFILEARGS(x, y) y
697 #define WXFILEARGS(x, y) x
699 #define WXFILEARGS(x, y) x, y
703 // Implementation of wxFileName::CreateTempFileName().
705 static wxString
wxCreateTempImpl(
706 const wxString
& prefix
,
707 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
708 bool *deleteOnClose
= NULL
)
710 #if wxUSE_FILE && wxUSE_FFILE
711 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
713 wxString path
, dir
, name
;
714 bool wantDeleteOnClose
= false;
718 // set the result to false initially
719 wantDeleteOnClose
= *deleteOnClose
;
720 *deleteOnClose
= false;
724 // easier if it alwasys points to something
725 deleteOnClose
= &wantDeleteOnClose
;
728 // use the directory specified by the prefix
729 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
733 dir
= wxFileName::GetTempDir();
736 #if defined(__WXWINCE__)
737 path
= dir
+ wxT("\\") + name
;
739 while (wxFileName::FileExists(path
))
741 path
= dir
+ wxT("\\") + name
;
746 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
747 if ( !::GetTempFileName(dir
, name
, 0, wxStringBuffer(path
, MAX_PATH
+ 1)) )
749 wxLogLastError(_T("GetTempFileName"));
757 if ( !wxEndsWithPathSeparator(dir
) &&
758 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
760 path
+= wxFILE_SEP_PATH
;
765 #if defined(HAVE_MKSTEMP)
766 // scratch space for mkstemp()
767 path
+= _T("XXXXXX");
769 // we need to copy the path to the buffer in which mkstemp() can modify it
770 wxCharBuffer
buf( wxConvFile
.cWX2MB( path
) );
772 // cast is safe because the string length doesn't change
773 int fdTemp
= mkstemp( (char*)(const char*) buf
);
776 // this might be not necessary as mkstemp() on most systems should have
777 // already done it but it doesn't hurt neither...
780 else // mkstemp() succeeded
782 path
= wxConvFile
.cMB2WX( (const char*) buf
);
785 // avoid leaking the fd
788 fileTemp
->Attach(fdTemp
);
797 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
799 ffileTemp
->Open(path
, _T("r+b"));
810 #else // !HAVE_MKSTEMP
814 path
+= _T("XXXXXX");
816 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
817 if ( !mktemp( (char*)(const char*) buf
) )
823 path
= wxConvFile
.cMB2WX( (const char*) buf
);
825 #else // !HAVE_MKTEMP (includes __DOS__)
826 // generate the unique file name ourselves
827 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
828 path
<< (unsigned int)getpid();
833 static const size_t numTries
= 1000;
834 for ( size_t n
= 0; n
< numTries
; n
++ )
836 // 3 hex digits is enough for numTries == 1000 < 4096
837 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
838 if ( !wxFileName::FileExists(pathTry
) )
847 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
849 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
851 #endif // Windows/!Windows
855 wxLogSysError(_("Failed to create a temporary file name"));
861 // open the file - of course, there is a race condition here, this is
862 // why we always prefer using mkstemp()...
864 if ( fileTemp
&& !fileTemp
->IsOpened() )
866 *deleteOnClose
= wantDeleteOnClose
;
867 int fd
= wxTempOpen(path
, deleteOnClose
);
869 fileTemp
->Attach(fd
);
876 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
878 *deleteOnClose
= wantDeleteOnClose
;
879 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
885 // FIXME: If !ok here should we loop and try again with another
886 // file name? That is the standard recourse if open(O_EXCL)
887 // fails, though of course it should be protected against
888 // possible infinite looping too.
890 wxLogError(_("Failed to open temporary file."));
900 static bool wxCreateTempImpl(
901 const wxString
& prefix
,
902 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
905 bool deleteOnClose
= true;
907 *name
= wxCreateTempImpl(prefix
,
908 WXFILEARGS(fileTemp
, ffileTemp
),
911 bool ok
= !name
->empty();
916 else if (ok
&& wxRemoveFile(*name
))
924 static void wxAssignTempImpl(
926 const wxString
& prefix
,
927 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
930 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
932 if ( tempname
.empty() )
934 // error, failed to get temp file name
939 fn
->Assign(tempname
);
944 void wxFileName::AssignTempFileName(const wxString
& prefix
)
946 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
950 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
952 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
955 #endif // wxUSE_FILE || wxUSE_FFILE
960 wxString
wxCreateTempFileName(const wxString
& prefix
,
964 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
967 bool wxCreateTempFile(const wxString
& prefix
,
971 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
974 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
976 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
981 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
983 return wxCreateTempFileName(prefix
, fileTemp
);
991 wxString
wxCreateTempFileName(const wxString
& prefix
,
995 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
998 bool wxCreateTempFile(const wxString
& prefix
,
1002 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1006 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1008 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1013 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1015 return wxCreateTempFileName(prefix
, fileTemp
);
1018 #endif // wxUSE_FFILE
1021 // ----------------------------------------------------------------------------
1022 // directory operations
1023 // ----------------------------------------------------------------------------
1025 wxString
wxFileName::GetTempDir()
1028 dir
= wxGetenv(_T("TMPDIR"));
1031 dir
= wxGetenv(_T("TMP"));
1034 dir
= wxGetenv(_T("TEMP"));
1038 #if defined(__WXWINCE__)
1041 // FIXME. Create \temp dir?
1042 if (DirExists(wxT("\\temp")))
1043 dir
= wxT("\\temp");
1045 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1049 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1051 wxLogLastError(_T("GetTempPath"));
1056 // GetTempFileName() fails if we pass it an empty string
1065 #if defined(__DOS__) || defined(__OS2__)
1067 #elif defined(__WXMAC__)
1068 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1078 bool wxFileName::Mkdir( int perm
, int flags
)
1080 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1083 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1085 if ( flags
& wxPATH_MKDIR_FULL
)
1087 // split the path in components
1088 wxFileName filename
;
1089 filename
.AssignDir(dir
);
1092 if ( filename
.HasVolume())
1094 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1097 wxArrayString dirs
= filename
.GetDirs();
1098 size_t count
= dirs
.GetCount();
1099 for ( size_t i
= 0; i
< count
; i
++ )
1102 #if defined(__WXMAC__) && !defined(__DARWIN__)
1103 // relative pathnames are exactely the other way round under mac...
1104 !filename
.IsAbsolute()
1106 filename
.IsAbsolute()
1109 currPath
+= wxFILE_SEP_PATH
;
1110 currPath
+= dirs
[i
];
1112 if (!DirExists(currPath
))
1114 if (!wxMkdir(currPath
, perm
))
1116 // no need to try creating further directories
1126 return ::wxMkdir( dir
, perm
);
1129 bool wxFileName::Rmdir()
1131 return wxFileName::Rmdir( GetPath() );
1134 bool wxFileName::Rmdir( const wxString
&dir
)
1136 return ::wxRmdir( dir
);
1139 // ----------------------------------------------------------------------------
1140 // path normalization
1141 // ----------------------------------------------------------------------------
1143 bool wxFileName::Normalize(int flags
,
1144 const wxString
& cwd
,
1145 wxPathFormat format
)
1147 // deal with env vars renaming first as this may seriously change the path
1148 if ( flags
& wxPATH_NORM_ENV_VARS
)
1150 wxString pathOrig
= GetFullPath(format
);
1151 wxString path
= wxExpandEnvVars(pathOrig
);
1152 if ( path
!= pathOrig
)
1159 // the existing path components
1160 wxArrayString dirs
= GetDirs();
1162 // the path to prepend in front to make the path absolute
1165 format
= GetFormat(format
);
1167 // set up the directory to use for making the path absolute later
1168 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1172 curDir
.AssignCwd(GetVolume());
1174 else // cwd provided
1176 curDir
.AssignDir(cwd
);
1180 // handle ~ stuff under Unix only
1181 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
1183 if ( !dirs
.IsEmpty() )
1185 wxString dir
= dirs
[0u];
1186 if ( !dir
.empty() && dir
[0u] == _T('~') )
1188 // to make the path absolute use the home directory
1189 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1191 // if we are expanding the tilde, then this path
1192 // *should* be already relative (since we checked for
1193 // the tilde only in the first char of the first dir);
1194 // if m_relative==false, it's because it was initialized
1195 // from a string which started with /~; in that case
1196 // we reach this point but then need m_relative=true
1197 // for relative->absolute expansion later
1205 // transform relative path into abs one
1206 if ( curDir
.IsOk() )
1208 // this path may be relative because it doesn't have the volume name
1209 // and still have m_relative=true; in this case we shouldn't modify
1210 // our directory components but just set the current volume
1211 if ( !HasVolume() && curDir
.HasVolume() )
1213 SetVolume(curDir
.GetVolume());
1217 // yes, it was the case - we don't need curDir then
1222 // finally, prepend curDir to the dirs array
1223 wxArrayString dirsNew
= curDir
.GetDirs();
1224 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1226 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1227 // return for some reason an absolute path, then curDir maybe not be absolute!
1228 if ( curDir
.IsAbsolute(format
) )
1230 // we have prepended an absolute path and thus we are now an absolute
1234 // else if (flags & wxPATH_NORM_ABSOLUTE):
1235 // should we warn the user that we didn't manage to make the path absolute?
1238 // now deal with ".", ".." and the rest
1240 size_t count
= dirs
.GetCount();
1241 for ( size_t n
= 0; n
< count
; n
++ )
1243 wxString dir
= dirs
[n
];
1245 if ( flags
& wxPATH_NORM_DOTS
)
1247 if ( dir
== wxT(".") )
1253 if ( dir
== wxT("..") )
1255 if ( m_dirs
.IsEmpty() )
1257 wxLogError(_("The path '%s' contains too many \"..\"!"),
1258 GetFullPath().c_str());
1262 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1267 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1275 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1276 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1279 if (GetShortcutTarget(GetFullPath(format
), filename
))
1281 // Repeat this since we may now have a new path
1282 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1284 filename
.MakeLower();
1292 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1294 // VZ: expand env vars here too?
1296 m_volume
.MakeLower();
1301 #if defined(__WIN32__)
1302 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1304 Assign(GetLongPath());
1311 // ----------------------------------------------------------------------------
1312 // get the shortcut target
1313 // ----------------------------------------------------------------------------
1315 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1316 // The .lnk file is a plain text file so it should be easy to
1317 // make it work. Hint from Google Groups:
1318 // "If you open up a lnk file, you'll see a
1319 // number, followed by a pound sign (#), followed by more text. The
1320 // number is the number of characters that follows the pound sign. The
1321 // characters after the pound sign are the command line (which _can_
1322 // include arguments) to be executed. Any path (e.g. \windows\program
1323 // files\myapp.exe) that includes spaces needs to be enclosed in
1324 // quotation marks."
1326 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1327 // The following lines are necessary under WinCE
1328 // #include "wx/msw/private.h"
1329 // #include <ole2.h>
1331 #if defined(__WXWINCE__)
1332 #include <shlguid.h>
1335 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1336 wxString
& targetFilename
,
1337 wxString
* arguments
)
1339 wxString path
, file
, ext
;
1340 wxSplitPath(shortcutPath
, & path
, & file
, & ext
);
1344 bool success
= false;
1346 // Assume it's not a shortcut if it doesn't end with lnk
1347 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1350 // create a ShellLink object
1351 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1352 IID_IShellLink
, (LPVOID
*) &psl
);
1354 if (SUCCEEDED(hres
))
1357 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1358 if (SUCCEEDED(hres
))
1360 WCHAR wsz
[MAX_PATH
];
1362 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1365 hres
= ppf
->Load(wsz
, 0);
1368 if (SUCCEEDED(hres
))
1371 // Wrong prototype in early versions
1372 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1373 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1375 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1377 targetFilename
= wxString(buf
);
1378 success
= (shortcutPath
!= targetFilename
);
1380 psl
->GetArguments(buf
, 2048);
1382 if (!args
.empty() && arguments
)
1394 #endif // __WIN32__ && !__WXWINCE__
1397 // ----------------------------------------------------------------------------
1398 // absolute/relative paths
1399 // ----------------------------------------------------------------------------
1401 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1403 // if our path doesn't start with a path separator, it's not an absolute
1408 if ( !GetVolumeSeparator(format
).empty() )
1410 // this format has volumes and an absolute path must have one, it's not
1411 // enough to have the full path to bean absolute file under Windows
1412 if ( GetVolume().empty() )
1419 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1421 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1423 // get cwd only once - small time saving
1424 wxString cwd
= wxGetCwd();
1425 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1426 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1428 bool withCase
= IsCaseSensitive(format
);
1430 // we can't do anything if the files live on different volumes
1431 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1437 // same drive, so we don't need our volume
1440 // remove common directories starting at the top
1441 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1442 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1445 fnBase
.m_dirs
.RemoveAt(0);
1448 // add as many ".." as needed
1449 size_t count
= fnBase
.m_dirs
.GetCount();
1450 for ( size_t i
= 0; i
< count
; i
++ )
1452 m_dirs
.Insert(wxT(".."), 0u);
1455 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1457 // a directory made relative with respect to itself is '.' under Unix
1458 // and DOS, by definition (but we don't have to insert "./" for the
1460 if ( m_dirs
.IsEmpty() && IsDir() )
1462 m_dirs
.Add(_T('.'));
1472 // ----------------------------------------------------------------------------
1473 // filename kind tests
1474 // ----------------------------------------------------------------------------
1476 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1478 wxFileName fn1
= *this,
1481 // get cwd only once - small time saving
1482 wxString cwd
= wxGetCwd();
1483 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1484 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1486 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1489 // TODO: compare inodes for Unix, this works even when filenames are
1490 // different but files are the same (symlinks) (VZ)
1496 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1498 // only Unix filenames are truely case-sensitive
1499 return GetFormat(format
) == wxPATH_UNIX
;
1503 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1505 // Inits to forbidden characters that are common to (almost) all platforms.
1506 wxString strForbiddenChars
= wxT("*?");
1508 // If asserts, wxPathFormat has been changed. In case of a new path format
1509 // addition, the following code might have to be updated.
1510 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1511 switch ( GetFormat(format
) )
1514 wxFAIL_MSG( wxT("Unknown path format") );
1515 // !! Fall through !!
1521 // On a Mac even names with * and ? are allowed (Tested with OS
1522 // 9.2.1 and OS X 10.2.5)
1523 strForbiddenChars
= wxEmptyString
;
1527 strForbiddenChars
+= wxT("\\/:\"<>|");
1534 return strForbiddenChars
;
1538 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1541 return wxEmptyString
;
1545 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1546 (GetFormat(format
) == wxPATH_VMS
) )
1548 sepVol
= wxFILE_SEP_DSK
;
1557 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1560 switch ( GetFormat(format
) )
1563 // accept both as native APIs do but put the native one first as
1564 // this is the one we use in GetFullPath()
1565 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1569 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1573 seps
= wxFILE_SEP_PATH_UNIX
;
1577 seps
= wxFILE_SEP_PATH_MAC
;
1581 seps
= wxFILE_SEP_PATH_VMS
;
1589 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1591 format
= GetFormat(format
);
1593 // under VMS the end of the path is ']', not the path separator used to
1594 // separate the components
1595 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1599 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1601 // wxString::Find() doesn't work as expected with NUL - it will always find
1602 // it, so test for it separately
1603 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1606 // ----------------------------------------------------------------------------
1607 // path components manipulation
1608 // ----------------------------------------------------------------------------
1610 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1614 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1619 const size_t len
= dir
.length();
1620 for ( size_t n
= 0; n
< len
; n
++ )
1622 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1624 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1633 void wxFileName::AppendDir( const wxString
& dir
)
1635 if ( IsValidDirComponent(dir
) )
1639 void wxFileName::PrependDir( const wxString
& dir
)
1644 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1646 if ( IsValidDirComponent(dir
) )
1647 m_dirs
.Insert(dir
, before
);
1650 void wxFileName::RemoveDir(size_t pos
)
1652 m_dirs
.RemoveAt(pos
);
1655 // ----------------------------------------------------------------------------
1657 // ----------------------------------------------------------------------------
1659 void wxFileName::SetFullName(const wxString
& fullname
)
1661 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1662 &m_name
, &m_ext
, &m_hasExt
);
1665 wxString
wxFileName::GetFullName() const
1667 wxString fullname
= m_name
;
1670 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1676 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1678 format
= GetFormat( format
);
1682 // return the volume with the path as well if requested
1683 if ( flags
& wxPATH_GET_VOLUME
)
1685 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1688 // the leading character
1693 fullpath
+= wxFILE_SEP_PATH_MAC
;
1698 fullpath
+= wxFILE_SEP_PATH_DOS
;
1702 wxFAIL_MSG( wxT("Unknown path format") );
1708 // normally the absolute file names start with a slash
1709 // with one exception: the ones like "~/foo.bar" don't
1711 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1713 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1719 // no leading character here but use this place to unset
1720 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1721 // as, if I understand correctly, there should never be a dot
1722 // before the closing bracket
1723 flags
&= ~wxPATH_GET_SEPARATOR
;
1726 if ( m_dirs
.empty() )
1728 // there is nothing more
1732 // then concatenate all the path components using the path separator
1733 if ( format
== wxPATH_VMS
)
1735 fullpath
+= wxT('[');
1738 const size_t dirCount
= m_dirs
.GetCount();
1739 for ( size_t i
= 0; i
< dirCount
; i
++ )
1744 if ( m_dirs
[i
] == wxT(".") )
1746 // skip appending ':', this shouldn't be done in this
1747 // case as "::" is interpreted as ".." under Unix
1751 // convert back from ".." to nothing
1752 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1753 fullpath
+= m_dirs
[i
];
1757 wxFAIL_MSG( wxT("Unexpected path format") );
1758 // still fall through
1762 fullpath
+= m_dirs
[i
];
1766 // TODO: What to do with ".." under VMS
1768 // convert back from ".." to nothing
1769 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1770 fullpath
+= m_dirs
[i
];
1774 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1775 fullpath
+= GetPathSeparator(format
);
1778 if ( format
== wxPATH_VMS
)
1780 fullpath
+= wxT(']');
1786 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1788 // we already have a function to get the path
1789 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1792 // now just add the file name and extension to it
1793 fullpath
+= GetFullName();
1798 // Return the short form of the path (returns identity on non-Windows platforms)
1799 wxString
wxFileName::GetShortPath() const
1801 wxString
path(GetFullPath());
1803 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1804 DWORD sz
= ::GetShortPathName(path
, NULL
, 0);
1808 if ( ::GetShortPathName
1811 wxStringBuffer(pathOut
, sz
),
1823 // Return the long form of the path (returns identity on non-Windows platforms)
1824 wxString
wxFileName::GetLongPath() const
1827 path
= GetFullPath();
1829 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1831 #if wxUSE_DYNAMIC_LOADER
1832 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1834 // this is MT-safe as in the worst case we're going to resolve the function
1835 // twice -- but as the result is the same in both threads, it's ok
1836 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1837 if ( !s_pfnGetLongPathName
)
1839 static bool s_triedToLoad
= false;
1841 if ( !s_triedToLoad
)
1843 s_triedToLoad
= true;
1845 wxDynamicLibrary
dllKernel(_T("kernel32"));
1847 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1852 #endif // Unicode/ANSI
1854 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1856 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1857 dllKernel
.GetSymbol(GetLongPathName
);
1860 // note that kernel32.dll can be unloaded, it stays in memory
1861 // anyhow as all Win32 programs link to it and so it's safe to call
1862 // GetLongPathName() even after unloading it
1866 if ( s_pfnGetLongPathName
)
1868 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
, NULL
, 0);
1871 if ( (*s_pfnGetLongPathName
)
1874 wxStringBuffer(pathOut
, dwSize
),
1882 #endif // wxUSE_DYNAMIC_LOADER
1884 // The OS didn't support GetLongPathName, or some other error.
1885 // We need to call FindFirstFile on each component in turn.
1887 WIN32_FIND_DATA findFileData
;
1891 pathOut
= GetVolume() +
1892 GetVolumeSeparator(wxPATH_DOS
) +
1893 GetPathSeparator(wxPATH_DOS
);
1895 pathOut
= wxEmptyString
;
1897 wxArrayString dirs
= GetDirs();
1898 dirs
.Add(GetFullName());
1902 size_t count
= dirs
.GetCount();
1903 for ( size_t i
= 0; i
< count
; i
++ )
1905 // We're using pathOut to collect the long-name path, but using a
1906 // temporary for appending the last path component which may be
1908 tmpPath
= pathOut
+ dirs
[i
];
1910 if ( tmpPath
.empty() )
1913 // can't see this being necessary? MF
1914 if ( tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
1916 // Can't pass a drive and root dir to FindFirstFile,
1917 // so continue to next dir
1918 tmpPath
+= wxFILE_SEP_PATH
;
1923 hFind
= ::FindFirstFile(tmpPath
, &findFileData
);
1924 if (hFind
== INVALID_HANDLE_VALUE
)
1926 // Error: most likely reason is that path doesn't exist, so
1927 // append any unprocessed parts and return
1928 for ( i
+= 1; i
< count
; i
++ )
1929 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
1934 pathOut
+= findFileData
.cFileName
;
1935 if ( (i
< (count
-1)) )
1936 pathOut
+= wxFILE_SEP_PATH
;
1942 #endif // Win32/!Win32
1947 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
1949 if (format
== wxPATH_NATIVE
)
1951 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1952 format
= wxPATH_DOS
;
1953 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1954 format
= wxPATH_MAC
;
1955 #elif defined(__VMS)
1956 format
= wxPATH_VMS
;
1958 format
= wxPATH_UNIX
;
1964 // ----------------------------------------------------------------------------
1965 // path splitting function
1966 // ----------------------------------------------------------------------------
1970 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
1971 wxString
*pstrVolume
,
1973 wxPathFormat format
)
1975 format
= GetFormat(format
);
1977 wxString fullpath
= fullpathWithVolume
;
1979 // special Windows UNC paths hack: transform \\share\path into share:path
1980 if ( IsUNCPath(fullpath
, format
) )
1982 fullpath
.erase(0, 2);
1984 size_t posFirstSlash
=
1985 fullpath
.find_first_of(GetPathTerminators(format
));
1986 if ( posFirstSlash
!= wxString::npos
)
1988 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
1990 // UNC paths are always absolute, right? (FIXME)
1991 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
1995 // We separate the volume here
1996 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
1998 wxString sepVol
= GetVolumeSeparator(format
);
2000 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2001 if ( posFirstColon
!= wxString::npos
)
2005 *pstrVolume
= fullpath
.Left(posFirstColon
);
2008 // remove the volume name and the separator from the full path
2009 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2014 *pstrPath
= fullpath
;
2018 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2019 wxString
*pstrVolume
,
2024 wxPathFormat format
)
2026 format
= GetFormat(format
);
2029 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2031 // find the positions of the last dot and last path separator in the path
2032 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2033 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2035 // check whether this dot occurs at the very beginning of a path component
2036 if ( (posLastDot
!= wxString::npos
) &&
2038 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2039 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
2041 // dot may be (and commonly -- at least under Unix -- is) the first
2042 // character of the filename, don't treat the entire filename as
2043 // extension in this case
2044 posLastDot
= wxString::npos
;
2047 // if we do have a dot and a slash, check that the dot is in the name part
2048 if ( (posLastDot
!= wxString::npos
) &&
2049 (posLastSlash
!= wxString::npos
) &&
2050 (posLastDot
< posLastSlash
) )
2052 // the dot is part of the path, not the start of the extension
2053 posLastDot
= wxString::npos
;
2056 // now fill in the variables provided by user
2059 if ( posLastSlash
== wxString::npos
)
2066 // take everything up to the path separator but take care to make
2067 // the path equal to something like '/', not empty, for the files
2068 // immediately under root directory
2069 size_t len
= posLastSlash
;
2071 // this rule does not apply to mac since we do not start with colons (sep)
2072 // except for relative paths
2073 if ( !len
&& format
!= wxPATH_MAC
)
2076 *pstrPath
= fullpath
.Left(len
);
2078 // special VMS hack: remove the initial bracket
2079 if ( format
== wxPATH_VMS
)
2081 if ( (*pstrPath
)[0u] == _T('[') )
2082 pstrPath
->erase(0, 1);
2089 // take all characters starting from the one after the last slash and
2090 // up to, but excluding, the last dot
2091 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2093 if ( posLastDot
== wxString::npos
)
2095 // take all until the end
2096 count
= wxString::npos
;
2098 else if ( posLastSlash
== wxString::npos
)
2102 else // have both dot and slash
2104 count
= posLastDot
- posLastSlash
- 1;
2107 *pstrName
= fullpath
.Mid(nStart
, count
);
2110 // finally deal with the extension here: we have an added complication that
2111 // extension may be empty (but present) as in "foo." where trailing dot
2112 // indicates the empty extension at the end -- and hence we must remember
2113 // that we have it independently of pstrExt
2114 if ( posLastDot
== wxString::npos
)
2124 // take everything after the dot
2126 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2133 void wxFileName::SplitPath(const wxString
& fullpath
,
2137 wxPathFormat format
)
2140 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2144 path
->Prepend(wxGetVolumeString(volume
, format
));
2148 // ----------------------------------------------------------------------------
2150 // ----------------------------------------------------------------------------
2154 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2155 const wxDateTime
*dtMod
,
2156 const wxDateTime
*dtCreate
)
2158 #if defined(__WIN32__)
2161 // VZ: please let me know how to do this if you can
2162 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
2166 wxFileHandle
fh(GetFullPath(), wxFileHandle::Write
);
2169 FILETIME ftAccess
, ftCreate
, ftWrite
;
2172 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2174 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2176 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2178 if ( ::SetFileTime(fh
,
2179 dtCreate
? &ftCreate
: NULL
,
2180 dtAccess
? &ftAccess
: NULL
,
2181 dtMod
? &ftWrite
: NULL
) )
2187 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2188 wxUnusedVar(dtCreate
);
2190 if ( !dtAccess
&& !dtMod
)
2192 // can't modify the creation time anyhow, don't try
2196 // if dtAccess or dtMod is not specified, use the other one (which must be
2197 // non NULL because of the test above) for both times
2199 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2200 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2201 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2205 #else // other platform
2206 wxUnusedVar(dtAccess
);
2208 wxUnusedVar(dtCreate
);
2211 wxLogSysError(_("Failed to modify file times for '%s'"),
2212 GetFullPath().c_str());
2217 bool wxFileName::Touch()
2219 #if defined(__UNIX_LIKE__)
2220 // under Unix touching file is simple: just pass NULL to utime()
2221 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2226 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2229 #else // other platform
2230 wxDateTime dtNow
= wxDateTime::Now();
2232 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2236 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2238 wxDateTime
*dtCreate
) const
2240 #if defined(__WIN32__)
2241 // we must use different methods for the files and directories under
2242 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2243 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2246 FILETIME ftAccess
, ftCreate
, ftWrite
;
2249 // implemented in msw/dir.cpp
2250 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2251 FILETIME
*, FILETIME
*, FILETIME
*);
2253 // we should pass the path without the trailing separator to
2254 // wxGetDirectoryTimes()
2255 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2256 &ftAccess
, &ftCreate
, &ftWrite
);
2260 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2263 ok
= ::GetFileTime(fh
,
2264 dtCreate
? &ftCreate
: NULL
,
2265 dtAccess
? &ftAccess
: NULL
,
2266 dtMod
? &ftWrite
: NULL
) != 0;
2277 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2279 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2281 ConvertFileTimeToWx(dtMod
, ftWrite
);
2285 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2286 // no need to test for IsDir() here
2288 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2291 dtAccess
->Set(stBuf
.st_atime
);
2293 dtMod
->Set(stBuf
.st_mtime
);
2295 dtCreate
->Set(stBuf
.st_ctime
);
2299 #else // other platform
2300 wxUnusedVar(dtAccess
);
2302 wxUnusedVar(dtCreate
);
2305 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2306 GetFullPath().c_str());
2311 #endif // wxUSE_DATETIME
2314 // ----------------------------------------------------------------------------
2315 // file size functions
2316 // ----------------------------------------------------------------------------
2319 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2321 if (!wxFileExists(filename
))
2322 return wxInvalidSize
;
2324 #if defined(__WXPALMOS__)
2326 return wxInvalidSize
;
2327 #elif defined(__WIN32__)
2328 wxFileHandle
f(filename
, wxFileHandle::Read
);
2330 return wxInvalidSize
;
2332 DWORD lpFileSizeHigh
;
2333 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2334 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2335 return wxInvalidSize
;
2337 return wxULongLong(lpFileSizeHigh
, ret
);
2338 #else // ! __WIN32__
2340 #ifndef wxNEED_WX_UNISTD_H
2341 if (wxStat( filename
.fn_str() , &st
) != 0)
2343 if (wxStat( filename
, &st
) != 0)
2345 return wxInvalidSize
;
2346 return wxULongLong(st
.st_size
);
2351 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2352 const wxString
&nullsize
,
2355 static const double KILOBYTESIZE
= 1024.0;
2356 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2357 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2358 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2360 if (bs
== 0 || bs
== wxInvalidSize
)
2363 double bytesize
= bs
.ToDouble();
2364 if (bytesize
< KILOBYTESIZE
)
2365 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2366 if (bytesize
< MEGABYTESIZE
)
2367 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2368 if (bytesize
< GIGABYTESIZE
)
2369 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2370 if (bytesize
< TERABYTESIZE
)
2371 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2373 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2376 wxULongLong
wxFileName::GetSize() const
2378 return GetSize(GetFullPath());
2381 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2383 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2387 // ----------------------------------------------------------------------------
2388 // Mac-specific functions
2389 // ----------------------------------------------------------------------------
2393 const short kMacExtensionMaxLength
= 16 ;
2394 class MacDefaultExtensionRecord
2397 MacDefaultExtensionRecord()
2400 m_type
= m_creator
= 0 ;
2402 MacDefaultExtensionRecord( const MacDefaultExtensionRecord
& from
)
2404 wxStrcpy( m_ext
, from
.m_ext
) ;
2405 m_type
= from
.m_type
;
2406 m_creator
= from
.m_creator
;
2408 MacDefaultExtensionRecord( const wxChar
* extension
, OSType type
, OSType creator
)
2410 wxStrncpy( m_ext
, extension
, kMacExtensionMaxLength
) ;
2411 m_ext
[kMacExtensionMaxLength
] = 0 ;
2413 m_creator
= creator
;
2415 wxChar m_ext
[kMacExtensionMaxLength
] ;
2420 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
) ;
2422 bool gMacDefaultExtensionsInited
= false ;
2424 #include "wx/arrimpl.cpp"
2426 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
) ;
2428 MacDefaultExtensionArray gMacDefaultExtensions
;
2430 // load the default extensions
2431 MacDefaultExtensionRecord gDefaults
[] =
2433 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2434 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2435 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2438 static void MacEnsureDefaultExtensionsLoaded()
2440 if ( !gMacDefaultExtensionsInited
)
2442 // we could load the pc exchange prefs here too
2443 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2445 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2447 gMacDefaultExtensionsInited
= true ;
2451 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2454 FSCatalogInfo catInfo
;
2457 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2459 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2461 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2462 finfo
->fileType
= type
;
2463 finfo
->fileCreator
= creator
;
2464 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2471 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2474 FSCatalogInfo catInfo
;
2477 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2479 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2481 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2482 *type
= finfo
->fileType
;
2483 *creator
= finfo
->fileCreator
;
2490 bool wxFileName::MacSetDefaultTypeAndCreator()
2492 wxUint32 type
, creator
;
2493 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2496 return MacSetTypeAndCreator( type
, creator
) ;
2501 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2503 MacEnsureDefaultExtensionsLoaded() ;
2504 wxString extl
= ext
.Lower() ;
2505 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2507 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2509 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2510 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2517 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2519 MacEnsureDefaultExtensionsLoaded() ;
2520 MacDefaultExtensionRecord rec
;
2522 rec
.m_creator
= creator
;
2523 wxStrncpy( rec
.m_ext
, ext
.Lower().c_str() , kMacExtensionMaxLength
) ;
2524 gMacDefaultExtensions
.Add( rec
) ;