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 // the paths of the form "~" or "~username" are absolute
416 m_relative
= leadingChar
!= wxT('/') && leadingChar
!= _T('~');
420 m_relative
= !IsPathSeparator(leadingChar
, format
);
425 // 2) Break up the path into its members. If the original path
426 // was just "/" or "\\", m_dirs will be empty. We know from
427 // the m_relative field, if this means "nothing" or "root dir".
429 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
431 while ( tn
.HasMoreTokens() )
433 wxString token
= tn
.GetNextToken();
435 // Remove empty token under DOS and Unix, interpret them
439 if (format
== wxPATH_MAC
)
440 m_dirs
.Add( wxT("..") );
450 void wxFileName::Assign(const wxString
& fullpath
,
453 wxString volume
, path
, name
, ext
;
455 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
457 Assign(volume
, path
, name
, ext
, hasExt
, format
);
460 void wxFileName::Assign(const wxString
& fullpathOrig
,
461 const wxString
& fullname
,
464 // always recognize fullpath as directory, even if it doesn't end with a
466 wxString fullpath
= fullpathOrig
;
467 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
469 fullpath
+= GetPathSeparator(format
);
472 wxString volume
, path
, name
, ext
;
475 // do some consistency checks in debug mode: the name should be really just
476 // the filename and the path should be really just a path
478 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
480 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
482 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
483 _T("the file name shouldn't contain the path") );
485 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
487 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
488 _T("the path shouldn't contain file name nor extension") );
490 #else // !__WXDEBUG__
491 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
492 &name
, &ext
, &hasExt
, format
);
493 SplitPath(fullpath
, &volume
, &path
, NULL
, NULL
, format
);
494 #endif // __WXDEBUG__/!__WXDEBUG__
496 Assign(volume
, path
, name
, ext
, hasExt
, format
);
499 void wxFileName::Assign(const wxString
& pathOrig
,
500 const wxString
& name
,
506 SplitVolume(pathOrig
, &volume
, &path
, format
);
508 Assign(volume
, path
, name
, ext
, format
);
511 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
513 Assign(dir
, wxEmptyString
, format
);
516 void wxFileName::Clear()
522 m_ext
= wxEmptyString
;
524 // we don't have any absolute path for now
532 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
534 return wxFileName(file
, format
);
538 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
541 fn
.AssignDir(dir
, format
);
545 // ----------------------------------------------------------------------------
547 // ----------------------------------------------------------------------------
549 bool wxFileName::FileExists() const
551 return wxFileName::FileExists( GetFullPath() );
554 bool wxFileName::FileExists( const wxString
&file
)
556 return ::wxFileExists( file
);
559 bool wxFileName::DirExists() const
561 return wxFileName::DirExists( GetPath() );
564 bool wxFileName::DirExists( const wxString
&dir
)
566 return ::wxDirExists( dir
);
569 // ----------------------------------------------------------------------------
570 // CWD and HOME stuff
571 // ----------------------------------------------------------------------------
573 void wxFileName::AssignCwd(const wxString
& volume
)
575 AssignDir(wxFileName::GetCwd(volume
));
579 wxString
wxFileName::GetCwd(const wxString
& volume
)
581 // if we have the volume, we must get the current directory on this drive
582 // and to do this we have to chdir to this volume - at least under Windows,
583 // I don't know how to get the current drive on another volume elsewhere
586 if ( !volume
.empty() )
589 SetCwd(volume
+ GetVolumeSeparator());
592 wxString cwd
= ::wxGetCwd();
594 if ( !volume
.empty() )
602 bool wxFileName::SetCwd()
604 return wxFileName::SetCwd( GetPath() );
607 bool wxFileName::SetCwd( const wxString
&cwd
)
609 return ::wxSetWorkingDirectory( cwd
);
612 void wxFileName::AssignHomeDir()
614 AssignDir(wxFileName::GetHomeDir());
617 wxString
wxFileName::GetHomeDir()
619 return ::wxGetHomeDir();
623 // ----------------------------------------------------------------------------
624 // CreateTempFileName
625 // ----------------------------------------------------------------------------
627 #if wxUSE_FILE || wxUSE_FFILE
630 #if !defined wx_fdopen && defined HAVE_FDOPEN
631 #define wx_fdopen fdopen
634 // NB: GetTempFileName() under Windows creates the file, so using
635 // O_EXCL there would fail
637 #define wxOPEN_EXCL 0
639 #define wxOPEN_EXCL O_EXCL
643 #ifdef wxOpenOSFHandle
644 #define WX_HAVE_DELETE_ON_CLOSE
645 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
647 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
649 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
651 DWORD disposition
= OPEN_ALWAYS
;
653 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
654 FILE_FLAG_DELETE_ON_CLOSE
;
656 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
657 disposition
, attributes
, NULL
);
659 return wxOpenOSFHandle(h
, wxO_BINARY
);
661 #endif // wxOpenOSFHandle
664 // Helper to open the file
666 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
668 #ifdef WX_HAVE_DELETE_ON_CLOSE
670 return wxOpenWithDeleteOnClose(path
);
673 *deleteOnClose
= false;
675 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
680 // Helper to open the file and attach it to the wxFFile
682 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
685 *deleteOnClose
= false;
686 return file
->Open(path
, _T("w+b"));
688 int fd
= wxTempOpen(path
, deleteOnClose
);
691 file
->Attach(wx_fdopen(fd
, "w+b"));
692 return file
->IsOpened();
695 #endif // wxUSE_FFILE
699 #define WXFILEARGS(x, y) y
701 #define WXFILEARGS(x, y) x
703 #define WXFILEARGS(x, y) x, y
707 // Implementation of wxFileName::CreateTempFileName().
709 static wxString
wxCreateTempImpl(
710 const wxString
& prefix
,
711 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
712 bool *deleteOnClose
= NULL
)
714 #if wxUSE_FILE && wxUSE_FFILE
715 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
717 wxString path
, dir
, name
;
718 bool wantDeleteOnClose
= false;
722 // set the result to false initially
723 wantDeleteOnClose
= *deleteOnClose
;
724 *deleteOnClose
= false;
728 // easier if it alwasys points to something
729 deleteOnClose
= &wantDeleteOnClose
;
732 // use the directory specified by the prefix
733 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
737 dir
= wxFileName::GetTempDir();
740 #if defined(__WXWINCE__)
741 path
= dir
+ wxT("\\") + name
;
743 while (wxFileName::FileExists(path
))
745 path
= dir
+ wxT("\\") + name
;
750 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
751 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
752 wxStringBuffer(path
, MAX_PATH
+ 1)) )
754 wxLogLastError(_T("GetTempFileName"));
762 if ( !wxEndsWithPathSeparator(dir
) &&
763 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
765 path
+= wxFILE_SEP_PATH
;
770 #if defined(HAVE_MKSTEMP)
771 // scratch space for mkstemp()
772 path
+= _T("XXXXXX");
774 // we need to copy the path to the buffer in which mkstemp() can modify it
775 wxCharBuffer
buf(path
.fn_str());
777 // cast is safe because the string length doesn't change
778 int fdTemp
= mkstemp( (char*)(const char*) buf
);
781 // this might be not necessary as mkstemp() on most systems should have
782 // already done it but it doesn't hurt neither...
785 else // mkstemp() succeeded
787 path
= wxConvFile
.cMB2WX( (const char*) buf
);
790 // avoid leaking the fd
793 fileTemp
->Attach(fdTemp
);
802 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
804 ffileTemp
->Open(path
, _T("r+b"));
815 #else // !HAVE_MKSTEMP
819 path
+= _T("XXXXXX");
821 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
822 if ( !mktemp( (char*)(const char*) buf
) )
828 path
= wxConvFile
.cMB2WX( (const char*) buf
);
830 #else // !HAVE_MKTEMP (includes __DOS__)
831 // generate the unique file name ourselves
832 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
833 path
<< (unsigned int)getpid();
838 static const size_t numTries
= 1000;
839 for ( size_t n
= 0; n
< numTries
; n
++ )
841 // 3 hex digits is enough for numTries == 1000 < 4096
842 pathTry
= path
+ wxString::Format(_T("%.03x"), (unsigned int) n
);
843 if ( !wxFileName::FileExists(pathTry
) )
852 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
854 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
856 #endif // Windows/!Windows
860 wxLogSysError(_("Failed to create a temporary file name"));
866 // open the file - of course, there is a race condition here, this is
867 // why we always prefer using mkstemp()...
869 if ( fileTemp
&& !fileTemp
->IsOpened() )
871 *deleteOnClose
= wantDeleteOnClose
;
872 int fd
= wxTempOpen(path
, deleteOnClose
);
874 fileTemp
->Attach(fd
);
881 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
883 *deleteOnClose
= wantDeleteOnClose
;
884 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
890 // FIXME: If !ok here should we loop and try again with another
891 // file name? That is the standard recourse if open(O_EXCL)
892 // fails, though of course it should be protected against
893 // possible infinite looping too.
895 wxLogError(_("Failed to open temporary file."));
905 static bool wxCreateTempImpl(
906 const wxString
& prefix
,
907 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
910 bool deleteOnClose
= true;
912 *name
= wxCreateTempImpl(prefix
,
913 WXFILEARGS(fileTemp
, ffileTemp
),
916 bool ok
= !name
->empty();
921 else if (ok
&& wxRemoveFile(*name
))
929 static void wxAssignTempImpl(
931 const wxString
& prefix
,
932 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
935 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
937 if ( tempname
.empty() )
939 // error, failed to get temp file name
944 fn
->Assign(tempname
);
949 void wxFileName::AssignTempFileName(const wxString
& prefix
)
951 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
955 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
957 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
960 #endif // wxUSE_FILE || wxUSE_FFILE
965 wxString
wxCreateTempFileName(const wxString
& prefix
,
969 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
972 bool wxCreateTempFile(const wxString
& prefix
,
976 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
979 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
981 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
986 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
988 return wxCreateTempFileName(prefix
, fileTemp
);
996 wxString
wxCreateTempFileName(const wxString
& prefix
,
1000 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1003 bool wxCreateTempFile(const wxString
& prefix
,
1007 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1011 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1013 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1018 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1020 return wxCreateTempFileName(prefix
, fileTemp
);
1023 #endif // wxUSE_FFILE
1026 // ----------------------------------------------------------------------------
1027 // directory operations
1028 // ----------------------------------------------------------------------------
1030 // helper of GetTempDir(): check if the given directory exists and return it if
1031 // it does or an empty string otherwise
1035 wxString
CheckIfDirExists(const wxString
& dir
)
1037 return wxFileName::DirExists(dir
) ? dir
: wxString();
1040 } // anonymous namespace
1042 wxString
wxFileName::GetTempDir()
1044 // first try getting it from environment: this allows overriding the values
1045 // used by default if the user wants to create temporary files in another
1047 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1050 dir
= CheckIfDirExists(wxGetenv("TMP"));
1052 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1055 // if no environment variables are set, use the system default
1058 #if defined(__WXWINCE__)
1059 dir
= CheckIfDirExists(wxT("\\temp"));
1060 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1061 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1063 wxLogLastError(_T("GetTempPath"));
1065 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1066 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1067 #endif // systems with native way
1070 // fall back to hard coded value
1073 #ifdef __UNIX_LIKE__
1074 dir
= CheckIfDirExists("/tmp");
1076 #endif // __UNIX_LIKE__
1083 bool wxFileName::Mkdir( int perm
, int flags
)
1085 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1088 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1090 if ( flags
& wxPATH_MKDIR_FULL
)
1092 // split the path in components
1093 wxFileName filename
;
1094 filename
.AssignDir(dir
);
1097 if ( filename
.HasVolume())
1099 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1102 wxArrayString dirs
= filename
.GetDirs();
1103 size_t count
= dirs
.GetCount();
1104 for ( size_t i
= 0; i
< count
; i
++ )
1106 if ( i
> 0 || filename
.IsAbsolute() )
1107 currPath
+= wxFILE_SEP_PATH
;
1108 currPath
+= dirs
[i
];
1110 if (!DirExists(currPath
))
1112 if (!wxMkdir(currPath
, perm
))
1114 // no need to try creating further directories
1124 return ::wxMkdir( dir
, perm
);
1127 bool wxFileName::Rmdir(int flags
)
1129 return wxFileName::Rmdir( GetPath(), flags
);
1132 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1135 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1137 // SHFileOperation needs double null termination string
1138 // but without separator at the end of the path
1140 if ( path
.Last() == wxFILE_SEP_PATH
)
1144 SHFILEOPSTRUCT fileop
;
1145 wxZeroMemory(fileop
);
1146 fileop
.wFunc
= FO_DELETE
;
1147 fileop
.pFrom
= path
.fn_str();
1148 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1150 // FOF_NOERRORUI is not defined in WinCE
1151 fileop
.fFlags
|= FOF_NOERRORUI
;
1154 int ret
= SHFileOperation(&fileop
);
1157 // SHFileOperation may return non-Win32 error codes, so the error
1158 // message can be incorrect
1159 wxLogApiError(_T("SHFileOperation"), ret
);
1165 else if ( flags
& wxPATH_RMDIR_FULL
)
1167 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1168 #endif // !__WXMSW__
1171 if ( path
.Last() != wxFILE_SEP_PATH
)
1172 path
+= wxFILE_SEP_PATH
;
1176 if ( !d
.IsOpened() )
1181 // first delete all subdirectories
1182 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1185 wxFileName::Rmdir(path
+ filename
, flags
);
1186 cont
= d
.GetNext(&filename
);
1190 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1192 // delete all files too
1193 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1196 ::wxRemoveFile(path
+ filename
);
1197 cont
= d
.GetNext(&filename
);
1200 #endif // !__WXMSW__
1203 return ::wxRmdir(dir
);
1206 // ----------------------------------------------------------------------------
1207 // path normalization
1208 // ----------------------------------------------------------------------------
1210 bool wxFileName::Normalize(int flags
,
1211 const wxString
& cwd
,
1212 wxPathFormat format
)
1214 // deal with env vars renaming first as this may seriously change the path
1215 if ( flags
& wxPATH_NORM_ENV_VARS
)
1217 wxString pathOrig
= GetFullPath(format
);
1218 wxString path
= wxExpandEnvVars(pathOrig
);
1219 if ( path
!= pathOrig
)
1225 // the existing path components
1226 wxArrayString dirs
= GetDirs();
1228 // the path to prepend in front to make the path absolute
1231 format
= GetFormat(format
);
1233 // set up the directory to use for making the path absolute later
1234 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1238 curDir
.AssignCwd(GetVolume());
1240 else // cwd provided
1242 curDir
.AssignDir(cwd
);
1246 // handle ~ stuff under Unix only
1247 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) )
1249 if ( !dirs
.IsEmpty() )
1251 wxString dir
= dirs
[0u];
1252 if ( !dir
.empty() && dir
[0u] == _T('~') )
1254 // to make the path absolute use the home directory
1255 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1257 // if we are expanding the tilde, then this path
1258 // *should* be already relative (since we checked for
1259 // the tilde only in the first char of the first dir);
1260 // if m_relative==false, it's because it was initialized
1261 // from a string which started with /~; in that case
1262 // we reach this point but then need m_relative=true
1263 // for relative->absolute expansion later
1271 // transform relative path into abs one
1272 if ( curDir
.IsOk() )
1274 // this path may be relative because it doesn't have the volume name
1275 // and still have m_relative=true; in this case we shouldn't modify
1276 // our directory components but just set the current volume
1277 if ( !HasVolume() && curDir
.HasVolume() )
1279 SetVolume(curDir
.GetVolume());
1283 // yes, it was the case - we don't need curDir then
1288 // finally, prepend curDir to the dirs array
1289 wxArrayString dirsNew
= curDir
.GetDirs();
1290 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1292 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1293 // return for some reason an absolute path, then curDir maybe not be absolute!
1294 if ( curDir
.IsAbsolute(format
) )
1296 // we have prepended an absolute path and thus we are now an absolute
1300 // else if (flags & wxPATH_NORM_ABSOLUTE):
1301 // should we warn the user that we didn't manage to make the path absolute?
1304 // now deal with ".", ".." and the rest
1306 size_t count
= dirs
.GetCount();
1307 for ( size_t n
= 0; n
< count
; n
++ )
1309 wxString dir
= dirs
[n
];
1311 if ( flags
& wxPATH_NORM_DOTS
)
1313 if ( dir
== wxT(".") )
1319 if ( dir
== wxT("..") )
1321 if ( m_dirs
.IsEmpty() )
1323 wxLogError(_("The path '%s' contains too many \"..\"!"),
1324 GetFullPath().c_str());
1328 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1336 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1337 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1340 if (GetShortcutTarget(GetFullPath(format
), filename
))
1348 #if defined(__WIN32__)
1349 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1351 Assign(GetLongPath());
1355 // Change case (this should be kept at the end of the function, to ensure
1356 // that the path doesn't change any more after we normalize its case)
1357 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1359 m_volume
.MakeLower();
1363 // directory entries must be made lower case as well
1364 count
= m_dirs
.GetCount();
1365 for ( size_t i
= 0; i
< count
; i
++ )
1367 m_dirs
[i
].MakeLower();
1375 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1376 const wxString
& replacementFmtString
,
1377 wxPathFormat format
)
1379 // look into stringForm for the contents of the given environment variable
1381 if (envname
.empty() ||
1382 !wxGetEnv(envname
, &val
))
1387 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1388 // do not touch the file name and the extension
1390 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1391 stringForm
.Replace(val
, replacement
);
1393 // Now assign ourselves the modified path:
1394 Assign(stringForm
, GetFullName(), format
);
1400 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1402 wxString homedir
= wxGetHomeDir();
1403 if (homedir
.empty())
1406 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1407 // do not touch the file name and the extension
1409 stringForm
.Replace(homedir
, "~");
1411 // Now assign ourselves the modified path:
1412 Assign(stringForm
, GetFullName(), format
);
1417 // ----------------------------------------------------------------------------
1418 // get the shortcut target
1419 // ----------------------------------------------------------------------------
1421 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1422 // The .lnk file is a plain text file so it should be easy to
1423 // make it work. Hint from Google Groups:
1424 // "If you open up a lnk file, you'll see a
1425 // number, followed by a pound sign (#), followed by more text. The
1426 // number is the number of characters that follows the pound sign. The
1427 // characters after the pound sign are the command line (which _can_
1428 // include arguments) to be executed. Any path (e.g. \windows\program
1429 // files\myapp.exe) that includes spaces needs to be enclosed in
1430 // quotation marks."
1432 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1433 // The following lines are necessary under WinCE
1434 // #include "wx/msw/private.h"
1435 // #include <ole2.h>
1437 #if defined(__WXWINCE__)
1438 #include <shlguid.h>
1441 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1442 wxString
& targetFilename
,
1443 wxString
* arguments
)
1445 wxString path
, file
, ext
;
1446 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1450 bool success
= false;
1452 // Assume it's not a shortcut if it doesn't end with lnk
1453 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1456 // create a ShellLink object
1457 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1458 IID_IShellLink
, (LPVOID
*) &psl
);
1460 if (SUCCEEDED(hres
))
1463 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1464 if (SUCCEEDED(hres
))
1466 WCHAR wsz
[MAX_PATH
];
1468 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1471 hres
= ppf
->Load(wsz
, 0);
1474 if (SUCCEEDED(hres
))
1477 // Wrong prototype in early versions
1478 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1479 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1481 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1483 targetFilename
= wxString(buf
);
1484 success
= (shortcutPath
!= targetFilename
);
1486 psl
->GetArguments(buf
, 2048);
1488 if (!args
.empty() && arguments
)
1500 #endif // __WIN32__ && !__WXWINCE__
1503 // ----------------------------------------------------------------------------
1504 // absolute/relative paths
1505 // ----------------------------------------------------------------------------
1507 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1509 // if our path doesn't start with a path separator, it's not an absolute
1514 if ( !GetVolumeSeparator(format
).empty() )
1516 // this format has volumes and an absolute path must have one, it's not
1517 // enough to have the full path to bean absolute file under Windows
1518 if ( GetVolume().empty() )
1525 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1527 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1529 // get cwd only once - small time saving
1530 wxString cwd
= wxGetCwd();
1531 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1532 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1534 bool withCase
= IsCaseSensitive(format
);
1536 // we can't do anything if the files live on different volumes
1537 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1543 // same drive, so we don't need our volume
1546 // remove common directories starting at the top
1547 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1548 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1551 fnBase
.m_dirs
.RemoveAt(0);
1554 // add as many ".." as needed
1555 size_t count
= fnBase
.m_dirs
.GetCount();
1556 for ( size_t i
= 0; i
< count
; i
++ )
1558 m_dirs
.Insert(wxT(".."), 0u);
1561 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1563 // a directory made relative with respect to itself is '.' under Unix
1564 // and DOS, by definition (but we don't have to insert "./" for the
1566 if ( m_dirs
.IsEmpty() && IsDir() )
1568 m_dirs
.Add(_T('.'));
1578 // ----------------------------------------------------------------------------
1579 // filename kind tests
1580 // ----------------------------------------------------------------------------
1582 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1584 wxFileName fn1
= *this,
1587 // get cwd only once - small time saving
1588 wxString cwd
= wxGetCwd();
1589 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1590 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1592 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1595 // TODO: compare inodes for Unix, this works even when filenames are
1596 // different but files are the same (symlinks) (VZ)
1602 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1604 // only Unix filenames are truely case-sensitive
1605 return GetFormat(format
) == wxPATH_UNIX
;
1609 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1611 // Inits to forbidden characters that are common to (almost) all platforms.
1612 wxString strForbiddenChars
= wxT("*?");
1614 // If asserts, wxPathFormat has been changed. In case of a new path format
1615 // addition, the following code might have to be updated.
1616 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1617 switch ( GetFormat(format
) )
1620 wxFAIL_MSG( wxT("Unknown path format") );
1621 // !! Fall through !!
1627 // On a Mac even names with * and ? are allowed (Tested with OS
1628 // 9.2.1 and OS X 10.2.5)
1629 strForbiddenChars
= wxEmptyString
;
1633 strForbiddenChars
+= wxT("\\/:\"<>|");
1640 return strForbiddenChars
;
1644 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1647 return wxEmptyString
;
1651 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1652 (GetFormat(format
) == wxPATH_VMS
) )
1654 sepVol
= wxFILE_SEP_DSK
;
1663 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1666 switch ( GetFormat(format
) )
1669 // accept both as native APIs do but put the native one first as
1670 // this is the one we use in GetFullPath()
1671 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1675 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1679 seps
= wxFILE_SEP_PATH_UNIX
;
1683 seps
= wxFILE_SEP_PATH_MAC
;
1687 seps
= wxFILE_SEP_PATH_VMS
;
1695 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1697 format
= GetFormat(format
);
1699 // under VMS the end of the path is ']', not the path separator used to
1700 // separate the components
1701 return format
== wxPATH_VMS
? wxString(_T(']')) : GetPathSeparators(format
);
1705 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1707 // wxString::Find() doesn't work as expected with NUL - it will always find
1708 // it, so test for it separately
1709 return ch
!= _T('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1712 // ----------------------------------------------------------------------------
1713 // path components manipulation
1714 // ----------------------------------------------------------------------------
1716 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1720 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1725 const size_t len
= dir
.length();
1726 for ( size_t n
= 0; n
< len
; n
++ )
1728 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1730 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1739 void wxFileName::AppendDir( const wxString
& dir
)
1741 if ( IsValidDirComponent(dir
) )
1745 void wxFileName::PrependDir( const wxString
& dir
)
1750 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1752 if ( IsValidDirComponent(dir
) )
1753 m_dirs
.Insert(dir
, before
);
1756 void wxFileName::RemoveDir(size_t pos
)
1758 m_dirs
.RemoveAt(pos
);
1761 // ----------------------------------------------------------------------------
1763 // ----------------------------------------------------------------------------
1765 void wxFileName::SetFullName(const wxString
& fullname
)
1767 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1768 &m_name
, &m_ext
, &m_hasExt
);
1771 wxString
wxFileName::GetFullName() const
1773 wxString fullname
= m_name
;
1776 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1782 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1784 format
= GetFormat( format
);
1788 // return the volume with the path as well if requested
1789 if ( flags
& wxPATH_GET_VOLUME
)
1791 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1794 // the leading character
1799 fullpath
+= wxFILE_SEP_PATH_MAC
;
1804 fullpath
+= wxFILE_SEP_PATH_DOS
;
1808 wxFAIL_MSG( wxT("Unknown path format") );
1814 // normally the absolute file names start with a slash
1815 // with one exception: the ones like "~/foo.bar" don't
1817 if ( m_dirs
.IsEmpty() || m_dirs
[0u] != _T('~') )
1819 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1825 // no leading character here but use this place to unset
1826 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1827 // as, if I understand correctly, there should never be a dot
1828 // before the closing bracket
1829 flags
&= ~wxPATH_GET_SEPARATOR
;
1832 if ( m_dirs
.empty() )
1834 // there is nothing more
1838 // then concatenate all the path components using the path separator
1839 if ( format
== wxPATH_VMS
)
1841 fullpath
+= wxT('[');
1844 const size_t dirCount
= m_dirs
.GetCount();
1845 for ( size_t i
= 0; i
< dirCount
; i
++ )
1850 if ( m_dirs
[i
] == wxT(".") )
1852 // skip appending ':', this shouldn't be done in this
1853 // case as "::" is interpreted as ".." under Unix
1857 // convert back from ".." to nothing
1858 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1859 fullpath
+= m_dirs
[i
];
1863 wxFAIL_MSG( wxT("Unexpected path format") );
1864 // still fall through
1868 fullpath
+= m_dirs
[i
];
1872 // TODO: What to do with ".." under VMS
1874 // convert back from ".." to nothing
1875 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1876 fullpath
+= m_dirs
[i
];
1880 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1881 fullpath
+= GetPathSeparator(format
);
1884 if ( format
== wxPATH_VMS
)
1886 fullpath
+= wxT(']');
1892 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1894 // we already have a function to get the path
1895 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1898 // now just add the file name and extension to it
1899 fullpath
+= GetFullName();
1904 // Return the short form of the path (returns identity on non-Windows platforms)
1905 wxString
wxFileName::GetShortPath() const
1907 wxString
path(GetFullPath());
1909 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1910 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
1914 if ( ::GetShortPathName
1917 wxStringBuffer(pathOut
, sz
),
1929 // Return the long form of the path (returns identity on non-Windows platforms)
1930 wxString
wxFileName::GetLongPath() const
1933 path
= GetFullPath();
1935 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1937 #if wxUSE_DYNLIB_CLASS
1938 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1940 // this is MT-safe as in the worst case we're going to resolve the function
1941 // twice -- but as the result is the same in both threads, it's ok
1942 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1943 if ( !s_pfnGetLongPathName
)
1945 static bool s_triedToLoad
= false;
1947 if ( !s_triedToLoad
)
1949 s_triedToLoad
= true;
1951 wxDynamicLibrary
dllKernel(_T("kernel32"));
1953 const wxChar
* GetLongPathName
= _T("GetLongPathName")
1958 #endif // Unicode/ANSI
1960 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1962 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1963 dllKernel
.GetSymbol(GetLongPathName
);
1966 // note that kernel32.dll can be unloaded, it stays in memory
1967 // anyhow as all Win32 programs link to it and so it's safe to call
1968 // GetLongPathName() even after unloading it
1972 if ( s_pfnGetLongPathName
)
1974 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
1977 if ( (*s_pfnGetLongPathName
)
1980 wxStringBuffer(pathOut
, dwSize
),
1988 #endif // wxUSE_DYNLIB_CLASS
1990 // The OS didn't support GetLongPathName, or some other error.
1991 // We need to call FindFirstFile on each component in turn.
1993 WIN32_FIND_DATA findFileData
;
1997 pathOut
= GetVolume() +
1998 GetVolumeSeparator(wxPATH_DOS
) +
1999 GetPathSeparator(wxPATH_DOS
);
2001 pathOut
= wxEmptyString
;
2003 wxArrayString dirs
= GetDirs();
2004 dirs
.Add(GetFullName());
2008 size_t count
= dirs
.GetCount();
2009 for ( size_t i
= 0; i
< count
; i
++ )
2011 const wxString
& dir
= dirs
[i
];
2013 // We're using pathOut to collect the long-name path, but using a
2014 // temporary for appending the last path component which may be
2016 tmpPath
= pathOut
+ dir
;
2018 // We must not process "." or ".." here as they would be (unexpectedly)
2019 // replaced by the corresponding directory names so just leave them
2022 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2023 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2024 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2026 tmpPath
+= wxFILE_SEP_PATH
;
2031 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
2032 if (hFind
== INVALID_HANDLE_VALUE
)
2034 // Error: most likely reason is that path doesn't exist, so
2035 // append any unprocessed parts and return
2036 for ( i
+= 1; i
< count
; i
++ )
2037 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2042 pathOut
+= findFileData
.cFileName
;
2043 if ( (i
< (count
-1)) )
2044 pathOut
+= wxFILE_SEP_PATH
;
2050 #endif // Win32/!Win32
2055 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2057 if (format
== wxPATH_NATIVE
)
2059 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2060 format
= wxPATH_DOS
;
2061 #elif defined(__VMS)
2062 format
= wxPATH_VMS
;
2064 format
= wxPATH_UNIX
;
2070 #ifdef wxHAS_FILESYSTEM_VOLUMES
2073 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2075 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2077 wxString
vol(drive
);
2078 vol
+= wxFILE_SEP_DSK
;
2079 if ( flags
& wxPATH_GET_SEPARATOR
)
2080 vol
+= wxFILE_SEP_PATH
;
2085 #endif // wxHAS_FILESYSTEM_VOLUMES
2087 // ----------------------------------------------------------------------------
2088 // path splitting function
2089 // ----------------------------------------------------------------------------
2093 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2094 wxString
*pstrVolume
,
2096 wxPathFormat format
)
2098 format
= GetFormat(format
);
2100 wxString fullpath
= fullpathWithVolume
;
2102 // special Windows UNC paths hack: transform \\share\path into share:path
2103 if ( IsUNCPath(fullpath
, format
) )
2105 fullpath
.erase(0, 2);
2107 size_t posFirstSlash
=
2108 fullpath
.find_first_of(GetPathTerminators(format
));
2109 if ( posFirstSlash
!= wxString::npos
)
2111 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2113 // UNC paths are always absolute, right? (FIXME)
2114 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2118 // We separate the volume here
2119 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2121 wxString sepVol
= GetVolumeSeparator(format
);
2123 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2124 if ( posFirstColon
!= wxString::npos
)
2128 *pstrVolume
= fullpath
.Left(posFirstColon
);
2131 // remove the volume name and the separator from the full path
2132 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2137 *pstrPath
= fullpath
;
2141 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2142 wxString
*pstrVolume
,
2147 wxPathFormat format
)
2149 format
= GetFormat(format
);
2152 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2154 // find the positions of the last dot and last path separator in the path
2155 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2156 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2158 // check whether this dot occurs at the very beginning of a path component
2159 if ( (posLastDot
!= wxString::npos
) &&
2161 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2162 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == _T(']'))) )
2164 // dot may be (and commonly -- at least under Unix -- is) the first
2165 // character of the filename, don't treat the entire filename as
2166 // extension in this case
2167 posLastDot
= wxString::npos
;
2170 // if we do have a dot and a slash, check that the dot is in the name part
2171 if ( (posLastDot
!= wxString::npos
) &&
2172 (posLastSlash
!= wxString::npos
) &&
2173 (posLastDot
< posLastSlash
) )
2175 // the dot is part of the path, not the start of the extension
2176 posLastDot
= wxString::npos
;
2179 // now fill in the variables provided by user
2182 if ( posLastSlash
== wxString::npos
)
2189 // take everything up to the path separator but take care to make
2190 // the path equal to something like '/', not empty, for the files
2191 // immediately under root directory
2192 size_t len
= posLastSlash
;
2194 // this rule does not apply to mac since we do not start with colons (sep)
2195 // except for relative paths
2196 if ( !len
&& format
!= wxPATH_MAC
)
2199 *pstrPath
= fullpath
.Left(len
);
2201 // special VMS hack: remove the initial bracket
2202 if ( format
== wxPATH_VMS
)
2204 if ( (*pstrPath
)[0u] == _T('[') )
2205 pstrPath
->erase(0, 1);
2212 // take all characters starting from the one after the last slash and
2213 // up to, but excluding, the last dot
2214 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2216 if ( posLastDot
== wxString::npos
)
2218 // take all until the end
2219 count
= wxString::npos
;
2221 else if ( posLastSlash
== wxString::npos
)
2225 else // have both dot and slash
2227 count
= posLastDot
- posLastSlash
- 1;
2230 *pstrName
= fullpath
.Mid(nStart
, count
);
2233 // finally deal with the extension here: we have an added complication that
2234 // extension may be empty (but present) as in "foo." where trailing dot
2235 // indicates the empty extension at the end -- and hence we must remember
2236 // that we have it independently of pstrExt
2237 if ( posLastDot
== wxString::npos
)
2247 // take everything after the dot
2249 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2256 void wxFileName::SplitPath(const wxString
& fullpath
,
2260 wxPathFormat format
)
2263 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2267 path
->Prepend(wxGetVolumeString(volume
, format
));
2271 // ----------------------------------------------------------------------------
2273 // ----------------------------------------------------------------------------
2277 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2278 const wxDateTime
*dtMod
,
2279 const wxDateTime
*dtCreate
)
2281 #if defined(__WIN32__)
2282 FILETIME ftAccess
, ftCreate
, ftWrite
;
2285 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2287 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2289 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2295 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2297 wxLogError(_("Setting directory access times is not supported "
2298 "under this OS version"));
2303 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2307 path
= GetFullPath();
2311 wxFileHandle
fh(path
, wxFileHandle::Write
, flags
);
2314 if ( ::SetFileTime(fh
,
2315 dtCreate
? &ftCreate
: NULL
,
2316 dtAccess
? &ftAccess
: NULL
,
2317 dtMod
? &ftWrite
: NULL
) )
2322 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2323 wxUnusedVar(dtCreate
);
2325 if ( !dtAccess
&& !dtMod
)
2327 // can't modify the creation time anyhow, don't try
2331 // if dtAccess or dtMod is not specified, use the other one (which must be
2332 // non NULL because of the test above) for both times
2334 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2335 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2336 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2340 #else // other platform
2341 wxUnusedVar(dtAccess
);
2343 wxUnusedVar(dtCreate
);
2346 wxLogSysError(_("Failed to modify file times for '%s'"),
2347 GetFullPath().c_str());
2352 bool wxFileName::Touch()
2354 #if defined(__UNIX_LIKE__)
2355 // under Unix touching file is simple: just pass NULL to utime()
2356 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2361 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2364 #else // other platform
2365 wxDateTime dtNow
= wxDateTime::Now();
2367 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2371 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2373 wxDateTime
*dtCreate
) const
2375 #if defined(__WIN32__)
2376 // we must use different methods for the files and directories under
2377 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2378 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2381 FILETIME ftAccess
, ftCreate
, ftWrite
;
2384 // implemented in msw/dir.cpp
2385 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2386 FILETIME
*, FILETIME
*, FILETIME
*);
2388 // we should pass the path without the trailing separator to
2389 // wxGetDirectoryTimes()
2390 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2391 &ftAccess
, &ftCreate
, &ftWrite
);
2395 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2398 ok
= ::GetFileTime(fh
,
2399 dtCreate
? &ftCreate
: NULL
,
2400 dtAccess
? &ftAccess
: NULL
,
2401 dtMod
? &ftWrite
: NULL
) != 0;
2412 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2414 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2416 ConvertFileTimeToWx(dtMod
, ftWrite
);
2420 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2421 // no need to test for IsDir() here
2423 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2426 dtAccess
->Set(stBuf
.st_atime
);
2428 dtMod
->Set(stBuf
.st_mtime
);
2430 dtCreate
->Set(stBuf
.st_ctime
);
2434 #else // other platform
2435 wxUnusedVar(dtAccess
);
2437 wxUnusedVar(dtCreate
);
2440 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2441 GetFullPath().c_str());
2446 #endif // wxUSE_DATETIME
2449 // ----------------------------------------------------------------------------
2450 // file size functions
2451 // ----------------------------------------------------------------------------
2456 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2458 if (!wxFileExists(filename
))
2459 return wxInvalidSize
;
2461 #if defined(__WXPALMOS__)
2463 return wxInvalidSize
;
2464 #elif defined(__WIN32__)
2465 wxFileHandle
f(filename
, wxFileHandle::Read
);
2467 return wxInvalidSize
;
2469 DWORD lpFileSizeHigh
;
2470 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2471 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2472 return wxInvalidSize
;
2474 return wxULongLong(lpFileSizeHigh
, ret
);
2475 #else // ! __WIN32__
2477 #ifndef wxNEED_WX_UNISTD_H
2478 if (wxStat( filename
.fn_str() , &st
) != 0)
2480 if (wxStat( filename
, &st
) != 0)
2482 return wxInvalidSize
;
2483 return wxULongLong(st
.st_size
);
2488 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2489 const wxString
&nullsize
,
2492 static const double KILOBYTESIZE
= 1024.0;
2493 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2494 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2495 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2497 if (bs
== 0 || bs
== wxInvalidSize
)
2500 double bytesize
= bs
.ToDouble();
2501 if (bytesize
< KILOBYTESIZE
)
2502 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2503 if (bytesize
< MEGABYTESIZE
)
2504 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2505 if (bytesize
< GIGABYTESIZE
)
2506 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2507 if (bytesize
< TERABYTESIZE
)
2508 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2510 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2513 wxULongLong
wxFileName::GetSize() const
2515 return GetSize(GetFullPath());
2518 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2520 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2523 #endif // wxUSE_LONGLONG
2525 // ----------------------------------------------------------------------------
2526 // Mac-specific functions
2527 // ----------------------------------------------------------------------------
2529 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2534 class MacDefaultExtensionRecord
2537 MacDefaultExtensionRecord()
2543 // default copy ctor, assignment operator and dtor are ok
2545 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2549 m_creator
= creator
;
2557 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2559 bool gMacDefaultExtensionsInited
= false;
2561 #include "wx/arrimpl.cpp"
2563 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2565 MacDefaultExtensionArray gMacDefaultExtensions
;
2567 // load the default extensions
2568 const MacDefaultExtensionRecord gDefaults
[] =
2570 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2571 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2572 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2575 void MacEnsureDefaultExtensionsLoaded()
2577 if ( !gMacDefaultExtensionsInited
)
2579 // we could load the pc exchange prefs here too
2580 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2582 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2584 gMacDefaultExtensionsInited
= true;
2588 } // anonymous namespace
2590 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2593 FSCatalogInfo catInfo
;
2596 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2598 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2600 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2601 finfo
->fileType
= type
;
2602 finfo
->fileCreator
= creator
;
2603 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2610 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
)
2613 FSCatalogInfo catInfo
;
2616 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2618 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2620 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2621 *type
= finfo
->fileType
;
2622 *creator
= finfo
->fileCreator
;
2629 bool wxFileName::MacSetDefaultTypeAndCreator()
2631 wxUint32 type
, creator
;
2632 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2635 return MacSetTypeAndCreator( type
, creator
) ;
2640 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2642 MacEnsureDefaultExtensionsLoaded() ;
2643 wxString extl
= ext
.Lower() ;
2644 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2646 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2648 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2649 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2656 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2658 MacEnsureDefaultExtensionsLoaded();
2659 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2660 gMacDefaultExtensions
.Add( rec
);
2663 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON