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"
88 #if defined(__WIN32__) && defined(__MINGW32__)
89 #include "wx/msw/gccpriv.h"
93 #include "wx/msw/private.h"
96 #if defined(__WXMAC__)
97 #include "wx/osx/private.h" // includes mac headers
100 // utime() is POSIX so should normally be available on all Unices
102 #include <sys/types.h>
104 #include <sys/stat.h>
114 #include <sys/types.h>
116 #include <sys/stat.h>
127 #include <sys/utime.h>
128 #include <sys/stat.h>
139 #define MAX_PATH _MAX_PATH
144 extern const wxULongLong wxInvalidSize
= (unsigned)-1;
145 #endif // wxUSE_LONGLONG
148 // ----------------------------------------------------------------------------
150 // ----------------------------------------------------------------------------
152 // small helper class which opens and closes the file - we use it just to get
153 // a file handle for the given file name to pass it to some Win32 API function
154 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
165 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
167 m_hFile
= ::CreateFile
169 filename
.fn_str(), // name
170 mode
== Read
? GENERIC_READ
// access mask
172 FILE_SHARE_READ
| // sharing mode
173 FILE_SHARE_WRITE
, // (allow everything)
174 NULL
, // no secutity attr
175 OPEN_EXISTING
, // creation disposition
177 NULL
// no template file
180 if ( m_hFile
== INVALID_HANDLE_VALUE
)
183 wxLogSysError(_("Failed to open '%s' for reading"),
186 wxLogSysError(_("Failed to open '%s' for writing"),
193 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
195 if ( !::CloseHandle(m_hFile
) )
197 wxLogSysError(_("Failed to close file handle"));
202 // return true only if the file could be opened successfully
203 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
206 operator HANDLE() const { return m_hFile
; }
214 // ----------------------------------------------------------------------------
216 // ----------------------------------------------------------------------------
218 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
220 // convert between wxDateTime and FILETIME which is a 64-bit value representing
221 // the number of 100-nanosecond intervals since January 1, 1601.
223 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
225 FILETIME ftcopy
= ft
;
227 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
229 wxLogLastError(_T("FileTimeToLocalFileTime"));
233 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
235 wxLogLastError(_T("FileTimeToSystemTime"));
238 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
239 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
242 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
245 st
.wDay
= dt
.GetDay();
246 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
247 st
.wYear
= (WORD
)dt
.GetYear();
248 st
.wHour
= dt
.GetHour();
249 st
.wMinute
= dt
.GetMinute();
250 st
.wSecond
= dt
.GetSecond();
251 st
.wMilliseconds
= dt
.GetMillisecond();
254 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
256 wxLogLastError(_T("SystemTimeToFileTime"));
259 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
261 wxLogLastError(_T("LocalFileTimeToFileTime"));
265 #endif // wxUSE_DATETIME && __WIN32__
267 // return a string with the volume par
268 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
272 if ( !volume
.empty() )
274 format
= wxFileName::GetFormat(format
);
276 // Special Windows UNC paths hack, part 2: undo what we did in
277 // SplitPath() and make an UNC path if we have a drive which is not a
278 // single letter (hopefully the network shares can't be one letter only
279 // although I didn't find any authoritative docs on this)
280 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
282 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
284 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
286 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
294 // return true if the format used is the DOS/Windows one and the string looks
296 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
298 return format
== wxPATH_DOS
&&
299 path
.length() >= 4 && // "\\a" can't be a UNC path
300 path
[0u] == wxFILE_SEP_PATH_DOS
&&
301 path
[1u] == wxFILE_SEP_PATH_DOS
&&
302 path
[2u] != wxFILE_SEP_PATH_DOS
;
305 // ============================================================================
307 // ============================================================================
309 // ----------------------------------------------------------------------------
310 // wxFileName construction
311 // ----------------------------------------------------------------------------
313 void wxFileName::Assign( const wxFileName
&filepath
)
315 m_volume
= filepath
.GetVolume();
316 m_dirs
= filepath
.GetDirs();
317 m_name
= filepath
.GetName();
318 m_ext
= filepath
.GetExt();
319 m_relative
= filepath
.m_relative
;
320 m_hasExt
= filepath
.m_hasExt
;
323 void wxFileName::Assign(const wxString
& volume
,
324 const wxString
& path
,
325 const wxString
& name
,
330 // we should ignore paths which look like UNC shares because we already
331 // have the volume here and the UNC notation (\\server\path) is only valid
332 // for paths which don't start with a volume, so prevent SetPath() from
333 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
335 // note also that this is a rather ugly way to do what we want (passing
336 // some kind of flag telling to ignore UNC paths to SetPath() would be
337 // better) but this is the safest thing to do to avoid breaking backwards
338 // compatibility in 2.8
339 if ( IsUNCPath(path
, format
) )
341 // remove one of the 2 leading backslashes to ensure that it's not
342 // recognized as an UNC path by SetPath()
343 wxString
pathNonUNC(path
, 1, wxString::npos
);
344 SetPath(pathNonUNC
, format
);
346 else // no UNC complications
348 SetPath(path
, format
);
358 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
362 if ( pathOrig
.empty() )
370 format
= GetFormat( format
);
372 // 0) deal with possible volume part first
375 SplitVolume(pathOrig
, &volume
, &path
, format
);
376 if ( !volume
.empty() )
383 // 1) Determine if the path is relative or absolute.
384 wxChar leadingChar
= path
[0u];
389 m_relative
= leadingChar
== wxT(':');
391 // We then remove a leading ":". The reason is in our
392 // storage form for relative paths:
393 // ":dir:file.txt" actually means "./dir/file.txt" in
394 // DOS notation and should get stored as
395 // (relative) (dir) (file.txt)
396 // "::dir:file.txt" actually means "../dir/file.txt"
397 // stored as (relative) (..) (dir) (file.txt)
398 // This is important only for the Mac as an empty dir
399 // actually means <UP>, whereas under DOS, double
400 // slashes can be ignored: "\\\\" is the same as "\\".
406 // TODO: what is the relative path format here?
411 wxFAIL_MSG( _T("Unknown path format") );
412 // !! Fall through !!
415 m_relative
= leadingChar
!= wxT('/');
419 m_relative
= !IsPathSeparator(leadingChar
, format
);
424 // 2) Break up the path into its members. If the original path
425 // was just "/" or "\\", m_dirs will be empty. We know from
426 // the m_relative field, if this means "nothing" or "root dir".
428 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
430 while ( tn
.HasMoreTokens() )
432 wxString token
= tn
.GetNextToken();
434 // Remove empty token under DOS and Unix, interpret them
438 if (format
== wxPATH_MAC
)
439 m_dirs
.Add( wxT("..") );
449 void wxFileName::Assign(const wxString
& fullpath
,
452 wxString volume
, path
, name
, ext
;
454 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
456 Assign(volume
, path
, name
, ext
, hasExt
, format
);
459 void wxFileName::Assign(const wxString
& fullpathOrig
,
460 const wxString
& fullname
,
463 // always recognize fullpath as directory, even if it doesn't end with a
465 wxString fullpath
= fullpathOrig
;
466 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
468 fullpath
+= GetPathSeparator(format
);
471 wxString volume
, path
, name
, ext
;
474 // do some consistency checks: the name should be really just the filename
475 // and the path should be really just a path
476 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
478 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
480 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
481 _T("the file name shouldn't contain the path") );
483 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
485 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
486 _T("the path shouldn't contain file name nor extension") );
488 Assign(volume
, path
, name
, ext
, hasExt
, format
);
491 void wxFileName::Assign(const wxString
& pathOrig
,
492 const wxString
& name
,
498 SplitVolume(pathOrig
, &volume
, &path
, format
);
500 Assign(volume
, path
, name
, ext
, format
);
503 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
505 Assign(dir
, wxEmptyString
, format
);
508 void wxFileName::Clear()
514 m_ext
= wxEmptyString
;
516 // we don't have any absolute path for now
524 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
526 return wxFileName(file
, format
);
530 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
533 fn
.AssignDir(dir
, format
);
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
541 bool wxFileName::FileExists() const
543 return wxFileName::FileExists( GetFullPath() );
546 bool wxFileName::FileExists( const wxString
&file
)
548 return ::wxFileExists( file
);
551 bool wxFileName::DirExists() const
553 return wxFileName::DirExists( GetPath() );
556 bool wxFileName::DirExists( const wxString
&dir
)
558 return ::wxDirExists( dir
);
561 // ----------------------------------------------------------------------------
562 // CWD and HOME stuff
563 // ----------------------------------------------------------------------------
565 void wxFileName::AssignCwd(const wxString
& volume
)
567 AssignDir(wxFileName::GetCwd(volume
));
571 wxString
wxFileName::GetCwd(const wxString
& volume
)
573 // if we have the volume, we must get the current directory on this drive
574 // and to do this we have to chdir to this volume - at least under Windows,
575 // I don't know how to get the current drive on another volume elsewhere
578 if ( !volume
.empty() )
581 SetCwd(volume
+ GetVolumeSeparator());
584 wxString cwd
= ::wxGetCwd();
586 if ( !volume
.empty() )
594 bool wxFileName::SetCwd() const
596 return wxFileName::SetCwd( GetPath() );
599 bool wxFileName::SetCwd( const wxString
&cwd
)
601 return ::wxSetWorkingDirectory( cwd
);
604 void wxFileName::AssignHomeDir()
606 AssignDir(wxFileName::GetHomeDir());
609 wxString
wxFileName::GetHomeDir()
611 return ::wxGetHomeDir();
615 // ----------------------------------------------------------------------------
616 // CreateTempFileName
617 // ----------------------------------------------------------------------------
619 #if wxUSE_FILE || wxUSE_FFILE
622 #if !defined wx_fdopen && defined HAVE_FDOPEN
623 #define wx_fdopen fdopen
626 // NB: GetTempFileName() under Windows creates the file, so using
627 // O_EXCL there would fail
629 #define wxOPEN_EXCL 0
631 #define wxOPEN_EXCL O_EXCL
635 #ifdef wxOpenOSFHandle
636 #define WX_HAVE_DELETE_ON_CLOSE
637 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
639 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
641 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
643 DWORD disposition
= OPEN_ALWAYS
;
645 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
646 FILE_FLAG_DELETE_ON_CLOSE
;
648 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
649 disposition
, attributes
, NULL
);
651 return wxOpenOSFHandle(h
, wxO_BINARY
);
653 #endif // wxOpenOSFHandle
656 // Helper to open the file
658 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
660 #ifdef WX_HAVE_DELETE_ON_CLOSE
662 return wxOpenWithDeleteOnClose(path
);
665 *deleteOnClose
= false;
667 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
672 // Helper to open the file and attach it to the wxFFile
674 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
677 *deleteOnClose
= false;
678 return file
->Open(path
, _T("w+b"));
680 int fd
= wxTempOpen(path
, deleteOnClose
);
683 file
->Attach(wx_fdopen(fd
, "w+b"));
684 return file
->IsOpened();
687 #endif // wxUSE_FFILE
691 #define WXFILEARGS(x, y) y
693 #define WXFILEARGS(x, y) x
695 #define WXFILEARGS(x, y) x, y
699 // Implementation of wxFileName::CreateTempFileName().
701 static wxString
wxCreateTempImpl(
702 const wxString
& prefix
,
703 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
704 bool *deleteOnClose
= NULL
)
706 #if wxUSE_FILE && wxUSE_FFILE
707 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
709 wxString path
, dir
, name
;
710 bool wantDeleteOnClose
= false;
714 // set the result to false initially
715 wantDeleteOnClose
= *deleteOnClose
;
716 *deleteOnClose
= false;
720 // easier if it alwasys points to something
721 deleteOnClose
= &wantDeleteOnClose
;
724 // use the directory specified by the prefix
725 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
729 dir
= wxFileName::GetTempDir();
732 #if defined(__WXWINCE__)
733 path
= dir
+ wxT("\\") + name
;
735 while (wxFileName::FileExists(path
))
737 path
= dir
+ wxT("\\") + name
;
742 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
743 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
744 wxStringBuffer(path
, MAX_PATH
+ 1)) )
746 wxLogLastError(_T("GetTempFileName"));
754 if ( !wxEndsWithPathSeparator(dir
) &&
755 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
757 path
+= wxFILE_SEP_PATH
;
762 #if defined(HAVE_MKSTEMP)
763 // scratch space for mkstemp()
764 path
+= _T("XXXXXX");
766 // we need to copy the path to the buffer in which mkstemp() can modify it
767 wxCharBuffer
buf(path
.fn_str());
769 // cast is safe because the string length doesn't change
770 int fdTemp
= mkstemp( (char*)(const char*) buf
);
773 // this might be not necessary as mkstemp() on most systems should have
774 // already done it but it doesn't hurt neither...
777 else // mkstemp() succeeded
779 path
= wxConvFile
.cMB2WX( (const char*) buf
);
782 // avoid leaking the fd
785 fileTemp
->Attach(fdTemp
);
794 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
796 ffileTemp
->Open(path
, _T("r+b"));
807 #else // !HAVE_MKSTEMP
811 path
+= _T("XXXXXX");
813 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
814 if ( !mktemp( (char*)(const char*) buf
) )
820 path
= wxConvFile
.cMB2WX( (const char*) buf
);
822 #else // !HAVE_MKTEMP (includes __DOS__)
823 // generate the unique file name ourselves
824 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
825 path
<< (unsigned int)getpid();
830 static const size_t numTries
= 1000;
831 for ( size_t n
= 0; n
< numTries
; n
++ )
833 // 3 hex digits is enough for numTries == 1000 < 4096
834 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
835 if ( !wxFileName::FileExists(pathTry
) )
844 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
846 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
848 #endif // Windows/!Windows
852 wxLogSysError(_("Failed to create a temporary file name"));
858 // open the file - of course, there is a race condition here, this is
859 // why we always prefer using mkstemp()...
861 if ( fileTemp
&& !fileTemp
->IsOpened() )
863 *deleteOnClose
= wantDeleteOnClose
;
864 int fd
= wxTempOpen(path
, deleteOnClose
);
866 fileTemp
->Attach(fd
);
873 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
875 *deleteOnClose
= wantDeleteOnClose
;
876 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
882 // FIXME: If !ok here should we loop and try again with another
883 // file name? That is the standard recourse if open(O_EXCL)
884 // fails, though of course it should be protected against
885 // possible infinite looping too.
887 wxLogError(_("Failed to open temporary file."));
897 static bool wxCreateTempImpl(
898 const wxString
& prefix
,
899 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
902 bool deleteOnClose
= true;
904 *name
= wxCreateTempImpl(prefix
,
905 WXFILEARGS(fileTemp
, ffileTemp
),
908 bool ok
= !name
->empty();
913 else if (ok
&& wxRemoveFile(*name
))
921 static void wxAssignTempImpl(
923 const wxString
& prefix
,
924 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
927 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
929 if ( tempname
.empty() )
931 // error, failed to get temp file name
936 fn
->Assign(tempname
);
941 void wxFileName::AssignTempFileName(const wxString
& prefix
)
943 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
947 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
949 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
952 #endif // wxUSE_FILE || wxUSE_FFILE
957 wxString
wxCreateTempFileName(const wxString
& prefix
,
961 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
964 bool wxCreateTempFile(const wxString
& prefix
,
968 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
971 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
973 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
978 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
980 return wxCreateTempFileName(prefix
, fileTemp
);
988 wxString
wxCreateTempFileName(const wxString
& prefix
,
992 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
995 bool wxCreateTempFile(const wxString
& prefix
,
999 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1003 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1005 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1010 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1012 return wxCreateTempFileName(prefix
, fileTemp
);
1015 #endif // wxUSE_FFILE
1018 // ----------------------------------------------------------------------------
1019 // directory operations
1020 // ----------------------------------------------------------------------------
1022 // helper of GetTempDir(): check if the given directory exists and return it if
1023 // it does or an empty string otherwise
1027 wxString
CheckIfDirExists(const wxString
& dir
)
1029 return wxFileName::DirExists(dir
) ? dir
: wxString();
1032 } // anonymous namespace
1034 wxString
wxFileName::GetTempDir()
1036 // first try getting it from environment: this allows overriding the values
1037 // used by default if the user wants to create temporary files in another
1039 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1042 dir
= CheckIfDirExists(wxGetenv("TMP"));
1044 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1047 // if no environment variables are set, use the system default
1050 #if defined(__WXWINCE__)
1051 dir
= CheckIfDirExists(wxT("\\temp"));
1052 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1053 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1055 wxLogLastError(_T("GetTempPath"));
1057 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1058 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1059 #endif // systems with native way
1062 // fall back to hard coded value
1065 #ifdef __UNIX_LIKE__
1066 dir
= CheckIfDirExists("/tmp");
1068 #endif // __UNIX_LIKE__
1075 bool wxFileName::Mkdir( int perm
, int flags
) const
1077 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1080 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1082 if ( flags
& wxPATH_MKDIR_FULL
)
1084 // split the path in components
1085 wxFileName filename
;
1086 filename
.AssignDir(dir
);
1089 if ( filename
.HasVolume())
1091 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1094 wxArrayString dirs
= filename
.GetDirs();
1095 size_t count
= dirs
.GetCount();
1096 for ( size_t i
= 0; i
< count
; i
++ )
1098 if ( i
> 0 || filename
.IsAbsolute() )
1099 currPath
+= wxFILE_SEP_PATH
;
1100 currPath
+= dirs
[i
];
1102 if (!DirExists(currPath
))
1104 if (!wxMkdir(currPath
, perm
))
1106 // no need to try creating further directories
1116 return ::wxMkdir( dir
, perm
);
1119 bool wxFileName::Rmdir(int flags
) const
1121 return wxFileName::Rmdir( GetPath(), flags
);
1124 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1127 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1129 // SHFileOperation needs double null termination string
1130 // but without separator at the end of the path
1132 if ( path
.Last() == wxFILE_SEP_PATH
)
1136 SHFILEOPSTRUCT fileop
;
1137 wxZeroMemory(fileop
);
1138 fileop
.wFunc
= FO_DELETE
;
1139 fileop
.pFrom
= path
.fn_str();
1140 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1142 // FOF_NOERRORUI is not defined in WinCE
1143 fileop
.fFlags
|= FOF_NOERRORUI
;
1146 int ret
= SHFileOperation(&fileop
);
1149 // SHFileOperation may return non-Win32 error codes, so the error
1150 // message can be incorrect
1151 wxLogApiError(_T("SHFileOperation"), ret
);
1157 else if ( flags
& wxPATH_RMDIR_FULL
)
1159 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1160 #endif // !__WXMSW__
1163 if ( path
.Last() != wxFILE_SEP_PATH
)
1164 path
+= wxFILE_SEP_PATH
;
1168 if ( !d
.IsOpened() )
1173 // first delete all subdirectories
1174 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1177 wxFileName::Rmdir(path
+ filename
, flags
);
1178 cont
= d
.GetNext(&filename
);
1182 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1184 // delete all files too
1185 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1188 ::wxRemoveFile(path
+ filename
);
1189 cont
= d
.GetNext(&filename
);
1192 #endif // !__WXMSW__
1195 return ::wxRmdir(dir
);
1198 // ----------------------------------------------------------------------------
1199 // path normalization
1200 // ----------------------------------------------------------------------------
1202 bool wxFileName::Normalize(int flags
,
1203 const wxString
& cwd
,
1204 wxPathFormat format
)
1206 // deal with env vars renaming first as this may seriously change the path
1207 if ( flags
& wxPATH_NORM_ENV_VARS
)
1209 wxString pathOrig
= GetFullPath(format
);
1210 wxString path
= wxExpandEnvVars(pathOrig
);
1211 if ( path
!= pathOrig
)
1217 // the existing path components
1218 wxArrayString dirs
= GetDirs();
1220 // the path to prepend in front to make the path absolute
1223 format
= GetFormat(format
);
1225 // set up the directory to use for making the path absolute later
1226 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1230 curDir
.AssignCwd(GetVolume());
1232 else // cwd provided
1234 curDir
.AssignDir(cwd
);
1238 // handle ~ stuff under Unix only
1239 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1241 if ( !dirs
.IsEmpty() )
1243 wxString dir
= dirs
[0u];
1244 if ( !dir
.empty() && dir
[0u] == _T('~') )
1246 // to make the path absolute use the home directory
1247 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1253 // transform relative path into abs one
1254 if ( curDir
.IsOk() )
1256 // this path may be relative because it doesn't have the volume name
1257 // and still have m_relative=true; in this case we shouldn't modify
1258 // our directory components but just set the current volume
1259 if ( !HasVolume() && curDir
.HasVolume() )
1261 SetVolume(curDir
.GetVolume());
1265 // yes, it was the case - we don't need curDir then
1270 // finally, prepend curDir to the dirs array
1271 wxArrayString dirsNew
= curDir
.GetDirs();
1272 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1274 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1275 // return for some reason an absolute path, then curDir maybe not be absolute!
1276 if ( !curDir
.m_relative
)
1278 // we have prepended an absolute path and thus we are now an absolute
1282 // else if (flags & wxPATH_NORM_ABSOLUTE):
1283 // should we warn the user that we didn't manage to make the path absolute?
1286 // now deal with ".", ".." and the rest
1288 size_t count
= dirs
.GetCount();
1289 for ( size_t n
= 0; n
< count
; n
++ )
1291 wxString dir
= dirs
[n
];
1293 if ( flags
& wxPATH_NORM_DOTS
)
1295 if ( dir
== wxT(".") )
1301 if ( dir
== wxT("..") )
1303 if ( m_dirs
.IsEmpty() )
1305 wxLogError(_("The path '%s' contains too many \"..\"!"),
1306 GetFullPath().c_str());
1310 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1318 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1319 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1322 if (GetShortcutTarget(GetFullPath(format
), filename
))
1330 #if defined(__WIN32__)
1331 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1333 Assign(GetLongPath());
1337 // Change case (this should be kept at the end of the function, to ensure
1338 // that the path doesn't change any more after we normalize its case)
1339 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1341 m_volume
.MakeLower();
1345 // directory entries must be made lower case as well
1346 count
= m_dirs
.GetCount();
1347 for ( size_t i
= 0; i
< count
; i
++ )
1349 m_dirs
[i
].MakeLower();
1357 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1358 const wxString
& replacementFmtString
,
1359 wxPathFormat format
)
1361 // look into stringForm for the contents of the given environment variable
1363 if (envname
.empty() ||
1364 !wxGetEnv(envname
, &val
))
1369 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1370 // do not touch the file name and the extension
1372 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1373 stringForm
.Replace(val
, replacement
);
1375 // Now assign ourselves the modified path:
1376 Assign(stringForm
, GetFullName(), format
);
1382 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1384 wxString homedir
= wxGetHomeDir();
1385 if (homedir
.empty())
1388 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1389 // do not touch the file name and the extension
1391 stringForm
.Replace(homedir
, "~");
1393 // Now assign ourselves the modified path:
1394 Assign(stringForm
, GetFullName(), format
);
1399 // ----------------------------------------------------------------------------
1400 // get the shortcut target
1401 // ----------------------------------------------------------------------------
1403 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1404 // The .lnk file is a plain text file so it should be easy to
1405 // make it work. Hint from Google Groups:
1406 // "If you open up a lnk file, you'll see a
1407 // number, followed by a pound sign (#), followed by more text. The
1408 // number is the number of characters that follows the pound sign. The
1409 // characters after the pound sign are the command line (which _can_
1410 // include arguments) to be executed. Any path (e.g. \windows\program
1411 // files\myapp.exe) that includes spaces needs to be enclosed in
1412 // quotation marks."
1414 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1415 // The following lines are necessary under WinCE
1416 // #include "wx/msw/private.h"
1417 // #include <ole2.h>
1419 #if defined(__WXWINCE__)
1420 #include <shlguid.h>
1423 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1424 wxString
& targetFilename
,
1425 wxString
* arguments
) const
1427 wxString path
, file
, ext
;
1428 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1432 bool success
= false;
1434 // Assume it's not a shortcut if it doesn't end with lnk
1435 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1438 // create a ShellLink object
1439 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1440 IID_IShellLink
, (LPVOID
*) &psl
);
1442 if (SUCCEEDED(hres
))
1445 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1446 if (SUCCEEDED(hres
))
1448 WCHAR wsz
[MAX_PATH
];
1450 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1453 hres
= ppf
->Load(wsz
, 0);
1456 if (SUCCEEDED(hres
))
1459 // Wrong prototype in early versions
1460 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1461 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1463 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1465 targetFilename
= wxString(buf
);
1466 success
= (shortcutPath
!= targetFilename
);
1468 psl
->GetArguments(buf
, 2048);
1470 if (!args
.empty() && arguments
)
1482 #endif // __WIN32__ && !__WXWINCE__
1485 // ----------------------------------------------------------------------------
1486 // absolute/relative paths
1487 // ----------------------------------------------------------------------------
1489 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1491 // unix paths beginning with ~ are reported as being absolute
1492 if ( format
== wxPATH_UNIX
)
1494 if ( !m_dirs
.IsEmpty() )
1496 wxString dir
= m_dirs
[0u];
1498 if (!dir
.empty() && dir
[0u] == _T('~'))
1503 // if our path doesn't start with a path separator, it's not an absolute
1508 if ( !GetVolumeSeparator(format
).empty() )
1510 // this format has volumes and an absolute path must have one, it's not
1511 // enough to have the full path to be an absolute file under Windows
1512 if ( GetVolume().empty() )
1519 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1521 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1523 // get cwd only once - small time saving
1524 wxString cwd
= wxGetCwd();
1525 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1526 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1528 bool withCase
= IsCaseSensitive(format
);
1530 // we can't do anything if the files live on different volumes
1531 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1537 // same drive, so we don't need our volume
1540 // remove common directories starting at the top
1541 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1542 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1545 fnBase
.m_dirs
.RemoveAt(0);
1548 // add as many ".." as needed
1549 size_t count
= fnBase
.m_dirs
.GetCount();
1550 for ( size_t i
= 0; i
< count
; i
++ )
1552 m_dirs
.Insert(wxT(".."), 0u);
1555 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1557 // a directory made relative with respect to itself is '.' under Unix
1558 // and DOS, by definition (but we don't have to insert "./" for the
1560 if ( m_dirs
.IsEmpty() && IsDir() )
1562 m_dirs
.Add(_T('.'));
1572 // ----------------------------------------------------------------------------
1573 // filename kind tests
1574 // ----------------------------------------------------------------------------
1576 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1578 wxFileName fn1
= *this,
1581 // get cwd only once - small time saving
1582 wxString cwd
= wxGetCwd();
1583 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1584 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1586 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1589 // TODO: compare inodes for Unix, this works even when filenames are
1590 // different but files are the same (symlinks) (VZ)
1596 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1598 // only Unix filenames are truely case-sensitive
1599 return GetFormat(format
) == wxPATH_UNIX
;
1603 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1605 // Inits to forbidden characters that are common to (almost) all platforms.
1606 wxString strForbiddenChars
= wxT("*?");
1608 // If asserts, wxPathFormat has been changed. In case of a new path format
1609 // addition, the following code might have to be updated.
1610 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1611 switch ( GetFormat(format
) )
1614 wxFAIL_MSG( wxT("Unknown path format") );
1615 // !! Fall through !!
1621 // On a Mac even names with * and ? are allowed (Tested with OS
1622 // 9.2.1 and OS X 10.2.5)
1623 strForbiddenChars
= wxEmptyString
;
1627 strForbiddenChars
+= wxT("\\/:\"<>|");
1634 return strForbiddenChars
;
1638 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1641 return wxEmptyString
;
1645 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1646 (GetFormat(format
) == wxPATH_VMS
) )
1648 sepVol
= wxFILE_SEP_DSK
;
1657 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1660 switch ( GetFormat(format
) )
1663 // accept both as native APIs do but put the native one first as
1664 // this is the one we use in GetFullPath()
1665 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1669 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1673 seps
= wxFILE_SEP_PATH_UNIX
;
1677 seps
= wxFILE_SEP_PATH_MAC
;
1681 seps
= wxFILE_SEP_PATH_VMS
;
1689 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1691 format
= GetFormat(format
);
1693 // under VMS the end of the path is ']', not the path separator used to
1694 // separate the components
1695 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1699 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1701 // wxString::Find() doesn't work as expected with NUL - it will always find
1702 // it, so test for it separately
1703 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1706 // ----------------------------------------------------------------------------
1707 // path components manipulation
1708 // ----------------------------------------------------------------------------
1710 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1714 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1719 const size_t len
= dir
.length();
1720 for ( size_t n
= 0; n
< len
; n
++ )
1722 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1724 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1733 void wxFileName::AppendDir( const wxString
& dir
)
1735 if ( IsValidDirComponent(dir
) )
1739 void wxFileName::PrependDir( const wxString
& dir
)
1744 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1746 if ( IsValidDirComponent(dir
) )
1747 m_dirs
.Insert(dir
, before
);
1750 void wxFileName::RemoveDir(size_t pos
)
1752 m_dirs
.RemoveAt(pos
);
1755 // ----------------------------------------------------------------------------
1757 // ----------------------------------------------------------------------------
1759 void wxFileName::SetFullName(const wxString
& fullname
)
1761 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1762 &m_name
, &m_ext
, &m_hasExt
);
1765 wxString
wxFileName::GetFullName() const
1767 wxString fullname
= m_name
;
1770 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1776 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1778 format
= GetFormat( format
);
1782 // return the volume with the path as well if requested
1783 if ( flags
& wxPATH_GET_VOLUME
)
1785 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1788 // the leading character
1793 fullpath
+= wxFILE_SEP_PATH_MAC
;
1798 fullpath
+= wxFILE_SEP_PATH_DOS
;
1802 wxFAIL_MSG( wxT("Unknown path format") );
1808 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1813 // no leading character here but use this place to unset
1814 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1815 // as, if I understand correctly, there should never be a dot
1816 // before the closing bracket
1817 flags
&= ~wxPATH_GET_SEPARATOR
;
1820 if ( m_dirs
.empty() )
1822 // there is nothing more
1826 // then concatenate all the path components using the path separator
1827 if ( format
== wxPATH_VMS
)
1829 fullpath
+= wxT('[');
1832 const size_t dirCount
= m_dirs
.GetCount();
1833 for ( size_t i
= 0; i
< dirCount
; i
++ )
1838 if ( m_dirs
[i
] == wxT(".") )
1840 // skip appending ':', this shouldn't be done in this
1841 // case as "::" is interpreted as ".." under Unix
1845 // convert back from ".." to nothing
1846 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1847 fullpath
+= m_dirs
[i
];
1851 wxFAIL_MSG( wxT("Unexpected path format") );
1852 // still fall through
1856 fullpath
+= m_dirs
[i
];
1860 // TODO: What to do with ".." under VMS
1862 // convert back from ".." to nothing
1863 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1864 fullpath
+= m_dirs
[i
];
1868 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1869 fullpath
+= GetPathSeparator(format
);
1872 if ( format
== wxPATH_VMS
)
1874 fullpath
+= wxT(']');
1880 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1882 // we already have a function to get the path
1883 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1886 // now just add the file name and extension to it
1887 fullpath
+= GetFullName();
1892 // Return the short form of the path (returns identity on non-Windows platforms)
1893 wxString
wxFileName::GetShortPath() const
1895 wxString
path(GetFullPath());
1897 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1898 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
1902 if ( ::GetShortPathName
1905 wxStringBuffer(pathOut
, sz
),
1917 // Return the long form of the path (returns identity on non-Windows platforms)
1918 wxString
wxFileName::GetLongPath() const
1921 path
= GetFullPath();
1923 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1925 #if wxUSE_DYNLIB_CLASS
1926 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1928 // this is MT-safe as in the worst case we're going to resolve the function
1929 // twice -- but as the result is the same in both threads, it's ok
1930 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1931 if ( !s_pfnGetLongPathName
)
1933 static bool s_triedToLoad
= false;
1935 if ( !s_triedToLoad
)
1937 s_triedToLoad
= true;
1939 wxDynamicLibrary
dllKernel(_T("kernel32"));
1941 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1946 #endif // Unicode/ANSI
1948 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1950 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1951 dllKernel
.GetSymbol(GetLongPathName
);
1954 // note that kernel32.dll can be unloaded, it stays in memory
1955 // anyhow as all Win32 programs link to it and so it's safe to call
1956 // GetLongPathName() even after unloading it
1960 if ( s_pfnGetLongPathName
)
1962 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
1965 if ( (*s_pfnGetLongPathName
)
1968 wxStringBuffer(pathOut
, dwSize
),
1976 #endif // wxUSE_DYNLIB_CLASS
1978 // The OS didn't support GetLongPathName, or some other error.
1979 // We need to call FindFirstFile on each component in turn.
1981 WIN32_FIND_DATA findFileData
;
1985 pathOut
= GetVolume() +
1986 GetVolumeSeparator(wxPATH_DOS
) +
1987 GetPathSeparator(wxPATH_DOS
);
1989 pathOut
= wxEmptyString
;
1991 wxArrayString dirs
= GetDirs();
1992 dirs
.Add(GetFullName());
1996 size_t count
= dirs
.GetCount();
1997 for ( size_t i
= 0; i
< count
; i
++ )
1999 const wxString
& dir
= dirs
[i
];
2001 // We're using pathOut to collect the long-name path, but using a
2002 // temporary for appending the last path component which may be
2004 tmpPath
= pathOut
+ dir
;
2006 // We must not process "." or ".." here as they would be (unexpectedly)
2007 // replaced by the corresponding directory names so just leave them
2010 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2011 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2012 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2014 tmpPath
+= wxFILE_SEP_PATH
;
2019 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
2020 if (hFind
== INVALID_HANDLE_VALUE
)
2022 // Error: most likely reason is that path doesn't exist, so
2023 // append any unprocessed parts and return
2024 for ( i
+= 1; i
< count
; i
++ )
2025 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2030 pathOut
+= findFileData
.cFileName
;
2031 if ( (i
< (count
-1)) )
2032 pathOut
+= wxFILE_SEP_PATH
;
2038 #endif // Win32/!Win32
2043 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2045 if (format
== wxPATH_NATIVE
)
2047 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2048 format
= wxPATH_DOS
;
2049 #elif defined(__VMS)
2050 format
= wxPATH_VMS
;
2052 format
= wxPATH_UNIX
;
2058 #ifdef wxHAS_FILESYSTEM_VOLUMES
2061 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2063 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2065 wxString
vol(drive
);
2066 vol
+= wxFILE_SEP_DSK
;
2067 if ( flags
& wxPATH_GET_SEPARATOR
)
2068 vol
+= wxFILE_SEP_PATH
;
2073 #endif // wxHAS_FILESYSTEM_VOLUMES
2075 // ----------------------------------------------------------------------------
2076 // path splitting function
2077 // ----------------------------------------------------------------------------
2081 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2082 wxString
*pstrVolume
,
2084 wxPathFormat format
)
2086 format
= GetFormat(format
);
2088 wxString fullpath
= fullpathWithVolume
;
2090 // special Windows UNC paths hack: transform \\share\path into share:path
2091 if ( IsUNCPath(fullpath
, format
) )
2093 fullpath
.erase(0, 2);
2095 size_t posFirstSlash
=
2096 fullpath
.find_first_of(GetPathTerminators(format
));
2097 if ( posFirstSlash
!= wxString::npos
)
2099 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2101 // UNC paths are always absolute, right? (FIXME)
2102 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2106 // We separate the volume here
2107 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2109 wxString sepVol
= GetVolumeSeparator(format
);
2111 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2112 if ( posFirstColon
!= wxString::npos
)
2116 *pstrVolume
= fullpath
.Left(posFirstColon
);
2119 // remove the volume name and the separator from the full path
2120 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2125 *pstrPath
= fullpath
;
2129 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2130 wxString
*pstrVolume
,
2135 wxPathFormat format
)
2137 format
= GetFormat(format
);
2140 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2142 // find the positions of the last dot and last path separator in the path
2143 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2144 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2146 // check whether this dot occurs at the very beginning of a path component
2147 if ( (posLastDot
!= wxString::npos
) &&
2149 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2150 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
2152 // dot may be (and commonly -- at least under Unix -- is) the first
2153 // character of the filename, don't treat the entire filename as
2154 // extension in this case
2155 posLastDot
= wxString::npos
;
2158 // if we do have a dot and a slash, check that the dot is in the name part
2159 if ( (posLastDot
!= wxString::npos
) &&
2160 (posLastSlash
!= wxString::npos
) &&
2161 (posLastDot
< posLastSlash
) )
2163 // the dot is part of the path, not the start of the extension
2164 posLastDot
= wxString::npos
;
2167 // now fill in the variables provided by user
2170 if ( posLastSlash
== wxString::npos
)
2177 // take everything up to the path separator but take care to make
2178 // the path equal to something like '/', not empty, for the files
2179 // immediately under root directory
2180 size_t len
= posLastSlash
;
2182 // this rule does not apply to mac since we do not start with colons (sep)
2183 // except for relative paths
2184 if ( !len
&& format
!= wxPATH_MAC
)
2187 *pstrPath
= fullpath
.Left(len
);
2189 // special VMS hack: remove the initial bracket
2190 if ( format
== wxPATH_VMS
)
2192 if ( (*pstrPath
)[0u] == _T('[') )
2193 pstrPath
->erase(0, 1);
2200 // take all characters starting from the one after the last slash and
2201 // up to, but excluding, the last dot
2202 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2204 if ( posLastDot
== wxString::npos
)
2206 // take all until the end
2207 count
= wxString::npos
;
2209 else if ( posLastSlash
== wxString::npos
)
2213 else // have both dot and slash
2215 count
= posLastDot
- posLastSlash
- 1;
2218 *pstrName
= fullpath
.Mid(nStart
, count
);
2221 // finally deal with the extension here: we have an added complication that
2222 // extension may be empty (but present) as in "foo." where trailing dot
2223 // indicates the empty extension at the end -- and hence we must remember
2224 // that we have it independently of pstrExt
2225 if ( posLastDot
== wxString::npos
)
2235 // take everything after the dot
2237 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2244 void wxFileName::SplitPath(const wxString
& fullpath
,
2248 wxPathFormat format
)
2251 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2255 path
->Prepend(wxGetVolumeString(volume
, format
));
2260 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2262 wxFileName
fn(fullpath
);
2264 return fn
.GetFullPath();
2267 // ----------------------------------------------------------------------------
2269 // ----------------------------------------------------------------------------
2273 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2274 const wxDateTime
*dtMod
,
2275 const wxDateTime
*dtCreate
) const
2277 #if defined(__WIN32__)
2278 FILETIME ftAccess
, ftCreate
, ftWrite
;
2281 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2283 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2285 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2291 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2293 wxLogError(_("Setting directory access times is not supported "
2294 "under this OS version"));
2299 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2303 path
= GetFullPath();
2307 wxFileHandle
fh(path
, wxFileHandle::Write
, flags
);
2310 if ( ::SetFileTime(fh
,
2311 dtCreate
? &ftCreate
: NULL
,
2312 dtAccess
? &ftAccess
: NULL
,
2313 dtMod
? &ftWrite
: NULL
) )
2318 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2319 wxUnusedVar(dtCreate
);
2321 if ( !dtAccess
&& !dtMod
)
2323 // can't modify the creation time anyhow, don't try
2327 // if dtAccess or dtMod is not specified, use the other one (which must be
2328 // non NULL because of the test above) for both times
2330 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2331 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2332 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2336 #else // other platform
2337 wxUnusedVar(dtAccess
);
2339 wxUnusedVar(dtCreate
);
2342 wxLogSysError(_("Failed to modify file times for '%s'"),
2343 GetFullPath().c_str());
2348 bool wxFileName::Touch() const
2350 #if defined(__UNIX_LIKE__)
2351 // under Unix touching file is simple: just pass NULL to utime()
2352 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2357 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2360 #else // other platform
2361 wxDateTime dtNow
= wxDateTime::Now();
2363 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2367 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2369 wxDateTime
*dtCreate
) const
2371 #if defined(__WIN32__)
2372 // we must use different methods for the files and directories under
2373 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2374 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2377 FILETIME ftAccess
, ftCreate
, ftWrite
;
2380 // implemented in msw/dir.cpp
2381 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2382 FILETIME
*, FILETIME
*, FILETIME
*);
2384 // we should pass the path without the trailing separator to
2385 // wxGetDirectoryTimes()
2386 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2387 &ftAccess
, &ftCreate
, &ftWrite
);
2391 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2394 ok
= ::GetFileTime(fh
,
2395 dtCreate
? &ftCreate
: NULL
,
2396 dtAccess
? &ftAccess
: NULL
,
2397 dtMod
? &ftWrite
: NULL
) != 0;
2408 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2410 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2412 ConvertFileTimeToWx(dtMod
, ftWrite
);
2416 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2417 // no need to test for IsDir() here
2419 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2422 dtAccess
->Set(stBuf
.st_atime
);
2424 dtMod
->Set(stBuf
.st_mtime
);
2426 dtCreate
->Set(stBuf
.st_ctime
);
2430 #else // other platform
2431 wxUnusedVar(dtAccess
);
2433 wxUnusedVar(dtCreate
);
2436 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2437 GetFullPath().c_str());
2442 #endif // wxUSE_DATETIME
2445 // ----------------------------------------------------------------------------
2446 // file size functions
2447 // ----------------------------------------------------------------------------
2452 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2454 if (!wxFileExists(filename
))
2455 return wxInvalidSize
;
2457 #if defined(__WXPALMOS__)
2459 return wxInvalidSize
;
2460 #elif defined(__WIN32__)
2461 wxFileHandle
f(filename
, wxFileHandle::Read
);
2463 return wxInvalidSize
;
2465 DWORD lpFileSizeHigh
;
2466 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2467 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2468 return wxInvalidSize
;
2470 return wxULongLong(lpFileSizeHigh
, ret
);
2471 #else // ! __WIN32__
2473 #ifndef wxNEED_WX_UNISTD_H
2474 if (wxStat( filename
.fn_str() , &st
) != 0)
2476 if (wxStat( filename
, &st
) != 0)
2478 return wxInvalidSize
;
2479 return wxULongLong(st
.st_size
);
2484 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2485 const wxString
&nullsize
,
2488 static const double KILOBYTESIZE
= 1024.0;
2489 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2490 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2491 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2493 if (bs
== 0 || bs
== wxInvalidSize
)
2496 double bytesize
= bs
.ToDouble();
2497 if (bytesize
< KILOBYTESIZE
)
2498 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2499 if (bytesize
< MEGABYTESIZE
)
2500 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2501 if (bytesize
< GIGABYTESIZE
)
2502 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2503 if (bytesize
< TERABYTESIZE
)
2504 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2506 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2509 wxULongLong
wxFileName::GetSize() const
2511 return GetSize(GetFullPath());
2514 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2516 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2519 #endif // wxUSE_LONGLONG
2521 // ----------------------------------------------------------------------------
2522 // Mac-specific functions
2523 // ----------------------------------------------------------------------------
2525 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2530 class MacDefaultExtensionRecord
2533 MacDefaultExtensionRecord()
2539 // default copy ctor, assignment operator and dtor are ok
2541 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2545 m_creator
= creator
;
2553 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2555 bool gMacDefaultExtensionsInited
= false;
2557 #include "wx/arrimpl.cpp"
2559 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2561 MacDefaultExtensionArray gMacDefaultExtensions
;
2563 // load the default extensions
2564 const MacDefaultExtensionRecord gDefaults
[] =
2566 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2567 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2568 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2571 void MacEnsureDefaultExtensionsLoaded()
2573 if ( !gMacDefaultExtensionsInited
)
2575 // we could load the pc exchange prefs here too
2576 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2578 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2580 gMacDefaultExtensionsInited
= true;
2584 } // anonymous namespace
2586 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2589 FSCatalogInfo catInfo
;
2592 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2594 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2596 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2597 finfo
->fileType
= type
;
2598 finfo
->fileCreator
= creator
;
2599 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2606 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2609 FSCatalogInfo catInfo
;
2612 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2614 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2616 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2617 *type
= finfo
->fileType
;
2618 *creator
= finfo
->fileCreator
;
2625 bool wxFileName::MacSetDefaultTypeAndCreator()
2627 wxUint32 type
, creator
;
2628 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2631 return MacSetTypeAndCreator( type
, creator
) ;
2636 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2638 MacEnsureDefaultExtensionsLoaded() ;
2639 wxString extl
= ext
.Lower() ;
2640 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2642 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2644 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2645 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2652 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2654 MacEnsureDefaultExtensionsLoaded();
2655 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2656 gMacDefaultExtensions
.Add( rec
);
2659 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON