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
150 // ----------------------------------------------------------------------------
152 // ----------------------------------------------------------------------------
154 // small helper class which opens and closes the file - we use it just to get
155 // a file handle for the given file name to pass it to some Win32 API function
156 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
167 wxFileHandle(const wxString
& filename
, OpenMode mode
, int flags
= 0)
169 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
170 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
171 // be changed when we open it because this class is used for setting
172 // access time (see #10567)
173 m_hFile
= ::CreateFile
175 filename
.fn_str(), // name
176 mode
== ReadAttr
? FILE_READ_ATTRIBUTES
// access mask
177 : FILE_WRITE_ATTRIBUTES
,
178 FILE_SHARE_READ
| // sharing mode
179 FILE_SHARE_WRITE
, // (allow everything)
180 NULL
, // no secutity attr
181 OPEN_EXISTING
, // creation disposition
183 NULL
// no template file
186 if ( m_hFile
== INVALID_HANDLE_VALUE
)
188 if ( mode
== ReadAttr
)
190 wxLogSysError(_("Failed to open '%s' for reading"),
195 wxLogSysError(_("Failed to open '%s' for writing"),
203 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
205 if ( !::CloseHandle(m_hFile
) )
207 wxLogSysError(_("Failed to close file handle"));
212 // return true only if the file could be opened successfully
213 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
216 operator HANDLE() const { return m_hFile
; }
224 // ----------------------------------------------------------------------------
226 // ----------------------------------------------------------------------------
228 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
230 // convert between wxDateTime and FILETIME which is a 64-bit value representing
231 // the number of 100-nanosecond intervals since January 1, 1601.
233 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
235 FILETIME ftcopy
= ft
;
237 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
239 wxLogLastError(wxT("FileTimeToLocalFileTime"));
243 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
245 wxLogLastError(wxT("FileTimeToSystemTime"));
248 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
249 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
252 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
255 st
.wDay
= dt
.GetDay();
256 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
257 st
.wYear
= (WORD
)dt
.GetYear();
258 st
.wHour
= dt
.GetHour();
259 st
.wMinute
= dt
.GetMinute();
260 st
.wSecond
= dt
.GetSecond();
261 st
.wMilliseconds
= dt
.GetMillisecond();
264 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
266 wxLogLastError(wxT("SystemTimeToFileTime"));
269 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
271 wxLogLastError(wxT("LocalFileTimeToFileTime"));
275 #endif // wxUSE_DATETIME && __WIN32__
277 // return a string with the volume par
278 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
282 if ( !volume
.empty() )
284 format
= wxFileName::GetFormat(format
);
286 // Special Windows UNC paths hack, part 2: undo what we did in
287 // SplitPath() and make an UNC path if we have a drive which is not a
288 // single letter (hopefully the network shares can't be one letter only
289 // although I didn't find any authoritative docs on this)
290 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
292 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
294 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
296 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
304 // return true if the character is a DOS path separator i.e. either a slash or
306 inline bool IsDOSPathSep(wxUniChar ch
)
308 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
311 // return true if the format used is the DOS/Windows one and the string looks
313 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
315 return format
== wxPATH_DOS
&&
316 path
.length() >= 4 && // "\\a" can't be a UNC path
317 IsDOSPathSep(path
[0u]) &&
318 IsDOSPathSep(path
[1u]) &&
319 !IsDOSPathSep(path
[2u]);
322 } // anonymous namespace
324 // ============================================================================
326 // ============================================================================
328 // ----------------------------------------------------------------------------
329 // wxFileName construction
330 // ----------------------------------------------------------------------------
332 void wxFileName::Assign( const wxFileName
&filepath
)
334 m_volume
= filepath
.GetVolume();
335 m_dirs
= filepath
.GetDirs();
336 m_name
= filepath
.GetName();
337 m_ext
= filepath
.GetExt();
338 m_relative
= filepath
.m_relative
;
339 m_hasExt
= filepath
.m_hasExt
;
342 void wxFileName::Assign(const wxString
& volume
,
343 const wxString
& path
,
344 const wxString
& name
,
349 // we should ignore paths which look like UNC shares because we already
350 // have the volume here and the UNC notation (\\server\path) is only valid
351 // for paths which don't start with a volume, so prevent SetPath() from
352 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
354 // note also that this is a rather ugly way to do what we want (passing
355 // some kind of flag telling to ignore UNC paths to SetPath() would be
356 // better) but this is the safest thing to do to avoid breaking backwards
357 // compatibility in 2.8
358 if ( IsUNCPath(path
, format
) )
360 // remove one of the 2 leading backslashes to ensure that it's not
361 // recognized as an UNC path by SetPath()
362 wxString
pathNonUNC(path
, 1, wxString::npos
);
363 SetPath(pathNonUNC
, format
);
365 else // no UNC complications
367 SetPath(path
, format
);
377 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
381 if ( pathOrig
.empty() )
389 format
= GetFormat( format
);
391 // 0) deal with possible volume part first
394 SplitVolume(pathOrig
, &volume
, &path
, format
);
395 if ( !volume
.empty() )
402 // 1) Determine if the path is relative or absolute.
406 // we had only the volume
410 wxChar leadingChar
= path
[0u];
415 m_relative
= leadingChar
== wxT(':');
417 // We then remove a leading ":". The reason is in our
418 // storage form for relative paths:
419 // ":dir:file.txt" actually means "./dir/file.txt" in
420 // DOS notation and should get stored as
421 // (relative) (dir) (file.txt)
422 // "::dir:file.txt" actually means "../dir/file.txt"
423 // stored as (relative) (..) (dir) (file.txt)
424 // This is important only for the Mac as an empty dir
425 // actually means <UP>, whereas under DOS, double
426 // slashes can be ignored: "\\\\" is the same as "\\".
432 // TODO: what is the relative path format here?
437 wxFAIL_MSG( wxT("Unknown path format") );
438 // !! Fall through !!
441 m_relative
= leadingChar
!= wxT('/');
445 m_relative
= !IsPathSeparator(leadingChar
, format
);
450 // 2) Break up the path into its members. If the original path
451 // was just "/" or "\\", m_dirs will be empty. We know from
452 // the m_relative field, if this means "nothing" or "root dir".
454 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
456 while ( tn
.HasMoreTokens() )
458 wxString token
= tn
.GetNextToken();
460 // Remove empty token under DOS and Unix, interpret them
464 if (format
== wxPATH_MAC
)
465 m_dirs
.Add( wxT("..") );
475 void wxFileName::Assign(const wxString
& fullpath
,
478 wxString volume
, path
, name
, ext
;
480 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
482 Assign(volume
, path
, name
, ext
, hasExt
, format
);
485 void wxFileName::Assign(const wxString
& fullpathOrig
,
486 const wxString
& fullname
,
489 // always recognize fullpath as directory, even if it doesn't end with a
491 wxString fullpath
= fullpathOrig
;
492 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
494 fullpath
+= GetPathSeparator(format
);
497 wxString volume
, path
, name
, ext
;
500 // do some consistency checks: the name should be really just the filename
501 // and the path should be really just a path
502 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
504 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
506 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
507 wxT("the file name shouldn't contain the path") );
509 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
512 // This test makes no sense on an OpenVMS system.
513 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
514 wxT("the path shouldn't contain file name nor extension") );
516 Assign(volume
, path
, name
, ext
, hasExt
, format
);
519 void wxFileName::Assign(const wxString
& pathOrig
,
520 const wxString
& name
,
526 SplitVolume(pathOrig
, &volume
, &path
, format
);
528 Assign(volume
, path
, name
, ext
, format
);
531 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
533 Assign(dir
, wxEmptyString
, format
);
536 void wxFileName::Clear()
542 m_ext
= wxEmptyString
;
544 // we don't have any absolute path for now
552 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
554 return wxFileName(file
, format
);
558 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
561 fn
.AssignDir(dir
, format
);
565 // ----------------------------------------------------------------------------
567 // ----------------------------------------------------------------------------
569 bool wxFileName::FileExists() const
571 return wxFileName::FileExists( GetFullPath() );
575 bool wxFileName::FileExists( const wxString
&filePath
)
577 #if defined(__WXPALMOS__)
579 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
580 // we must use GetFileAttributes() instead of the ANSI C functions because
581 // it can cope with network (UNC) paths unlike them
582 DWORD ret
= ::GetFileAttributes(filePath
.fn_str());
584 return (ret
!= INVALID_FILE_ATTRIBUTES
) && !(ret
& FILE_ATTRIBUTE_DIRECTORY
);
587 #define S_ISREG(mode) ((mode) & S_IFREG)
590 #ifndef wxNEED_WX_UNISTD_H
591 return (wxStat( filePath
.fn_str() , &st
) == 0 && S_ISREG(st
.st_mode
))
593 || (errno
== EACCES
) // if access is denied something with that name
594 // exists and is opened in exclusive mode.
598 return wxStat( filePath
, &st
) == 0 && S_ISREG(st
.st_mode
);
600 #endif // __WIN32__/!__WIN32__
603 bool wxFileName::DirExists() const
605 return wxFileName::DirExists( GetPath() );
609 bool wxFileName::DirExists( const wxString
&dirPath
)
611 wxString
strPath(dirPath
);
613 #if defined(__WINDOWS__) || defined(__OS2__)
614 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
615 // so remove all trailing backslashes from the path - but don't do this for
616 // the paths "d:\" (which are different from "d:") nor for just "\"
617 while ( wxEndsWithPathSeparator(strPath
) )
619 size_t len
= strPath
.length();
620 if ( len
== 1 || (len
== 3 && strPath
[len
- 2] == wxT(':')) )
623 strPath
.Truncate(len
- 1);
625 #endif // __WINDOWS__
628 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
629 if (strPath
.length() == 2 && strPath
[1u] == wxT(':'))
633 #if defined(__WXPALMOS__)
635 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
636 // stat() can't cope with network paths
637 DWORD ret
= ::GetFileAttributes(strPath
.fn_str());
639 return (ret
!= INVALID_FILE_ATTRIBUTES
) && (ret
& FILE_ATTRIBUTE_DIRECTORY
);
640 #elif defined(__OS2__)
641 FILESTATUS3 Info
= {{0}};
642 APIRET rc
= ::DosQueryPathInfo((PSZ
)(WXSTRINGCAST strPath
), FIL_STANDARD
,
643 (void*) &Info
, sizeof(FILESTATUS3
));
645 return ((rc
== NO_ERROR
) && (Info
.attrFile
& FILE_DIRECTORY
)) ||
646 (rc
== ERROR_SHARING_VIOLATION
);
647 // If we got a sharing violation, there must be something with this name.
651 #ifndef __VISAGECPP__
652 return wxStat(strPath
.c_str(), &st
) == 0 && ((st
.st_mode
& S_IFMT
) == S_IFDIR
);
654 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
655 return wxStat(strPath
.c_str(), &st
) == 0 && (st
.st_mode
== S_IFDIR
);
658 #endif // __WIN32__/!__WIN32__
661 // ----------------------------------------------------------------------------
662 // CWD and HOME stuff
663 // ----------------------------------------------------------------------------
665 void wxFileName::AssignCwd(const wxString
& volume
)
667 AssignDir(wxFileName::GetCwd(volume
));
671 wxString
wxFileName::GetCwd(const wxString
& volume
)
673 // if we have the volume, we must get the current directory on this drive
674 // and to do this we have to chdir to this volume - at least under Windows,
675 // I don't know how to get the current drive on another volume elsewhere
678 if ( !volume
.empty() )
681 SetCwd(volume
+ GetVolumeSeparator());
684 wxString cwd
= ::wxGetCwd();
686 if ( !volume
.empty() )
694 bool wxFileName::SetCwd() const
696 return wxFileName::SetCwd( GetPath() );
699 bool wxFileName::SetCwd( const wxString
&cwd
)
701 return ::wxSetWorkingDirectory( cwd
);
704 void wxFileName::AssignHomeDir()
706 AssignDir(wxFileName::GetHomeDir());
709 wxString
wxFileName::GetHomeDir()
711 return ::wxGetHomeDir();
715 // ----------------------------------------------------------------------------
716 // CreateTempFileName
717 // ----------------------------------------------------------------------------
719 #if wxUSE_FILE || wxUSE_FFILE
722 #if !defined wx_fdopen && defined HAVE_FDOPEN
723 #define wx_fdopen fdopen
726 // NB: GetTempFileName() under Windows creates the file, so using
727 // O_EXCL there would fail
729 #define wxOPEN_EXCL 0
731 #define wxOPEN_EXCL O_EXCL
735 #ifdef wxOpenOSFHandle
736 #define WX_HAVE_DELETE_ON_CLOSE
737 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
739 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
741 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
743 DWORD disposition
= OPEN_ALWAYS
;
745 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
746 FILE_FLAG_DELETE_ON_CLOSE
;
748 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
749 disposition
, attributes
, NULL
);
751 return wxOpenOSFHandle(h
, wxO_BINARY
);
753 #endif // wxOpenOSFHandle
756 // Helper to open the file
758 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
760 #ifdef WX_HAVE_DELETE_ON_CLOSE
762 return wxOpenWithDeleteOnClose(path
);
765 *deleteOnClose
= false;
767 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
772 // Helper to open the file and attach it to the wxFFile
774 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
777 *deleteOnClose
= false;
778 return file
->Open(path
, wxT("w+b"));
780 int fd
= wxTempOpen(path
, deleteOnClose
);
783 file
->Attach(wx_fdopen(fd
, "w+b"));
784 return file
->IsOpened();
787 #endif // wxUSE_FFILE
791 #define WXFILEARGS(x, y) y
793 #define WXFILEARGS(x, y) x
795 #define WXFILEARGS(x, y) x, y
799 // Implementation of wxFileName::CreateTempFileName().
801 static wxString
wxCreateTempImpl(
802 const wxString
& prefix
,
803 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
804 bool *deleteOnClose
= NULL
)
806 #if wxUSE_FILE && wxUSE_FFILE
807 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
809 wxString path
, dir
, name
;
810 bool wantDeleteOnClose
= false;
814 // set the result to false initially
815 wantDeleteOnClose
= *deleteOnClose
;
816 *deleteOnClose
= false;
820 // easier if it alwasys points to something
821 deleteOnClose
= &wantDeleteOnClose
;
824 // use the directory specified by the prefix
825 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
829 dir
= wxFileName::GetTempDir();
832 #if defined(__WXWINCE__)
833 path
= dir
+ wxT("\\") + name
;
835 while (wxFileName::FileExists(path
))
837 path
= dir
+ wxT("\\") + name
;
842 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
843 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
844 wxStringBuffer(path
, MAX_PATH
+ 1)) )
846 wxLogLastError(wxT("GetTempFileName"));
854 if ( !wxEndsWithPathSeparator(dir
) &&
855 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
857 path
+= wxFILE_SEP_PATH
;
862 #if defined(HAVE_MKSTEMP)
863 // scratch space for mkstemp()
864 path
+= wxT("XXXXXX");
866 // we need to copy the path to the buffer in which mkstemp() can modify it
867 wxCharBuffer
buf(path
.fn_str());
869 // cast is safe because the string length doesn't change
870 int fdTemp
= mkstemp( (char*)(const char*) buf
);
873 // this might be not necessary as mkstemp() on most systems should have
874 // already done it but it doesn't hurt neither...
877 else // mkstemp() succeeded
879 path
= wxConvFile
.cMB2WX( (const char*) buf
);
882 // avoid leaking the fd
885 fileTemp
->Attach(fdTemp
);
894 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
896 ffileTemp
->Open(path
, wxT("r+b"));
907 #else // !HAVE_MKSTEMP
911 path
+= wxT("XXXXXX");
913 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
914 if ( !mktemp( (char*)(const char*) buf
) )
920 path
= wxConvFile
.cMB2WX( (const char*) buf
);
922 #else // !HAVE_MKTEMP (includes __DOS__)
923 // generate the unique file name ourselves
924 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
925 path
<< (unsigned int)getpid();
930 static const size_t numTries
= 1000;
931 for ( size_t n
= 0; n
< numTries
; n
++ )
933 // 3 hex digits is enough for numTries == 1000 < 4096
934 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
935 if ( !wxFileName::FileExists(pathTry
) )
944 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
946 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
948 #endif // Windows/!Windows
952 wxLogSysError(_("Failed to create a temporary file name"));
958 // open the file - of course, there is a race condition here, this is
959 // why we always prefer using mkstemp()...
961 if ( fileTemp
&& !fileTemp
->IsOpened() )
963 *deleteOnClose
= wantDeleteOnClose
;
964 int fd
= wxTempOpen(path
, deleteOnClose
);
966 fileTemp
->Attach(fd
);
973 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
975 *deleteOnClose
= wantDeleteOnClose
;
976 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
982 // FIXME: If !ok here should we loop and try again with another
983 // file name? That is the standard recourse if open(O_EXCL)
984 // fails, though of course it should be protected against
985 // possible infinite looping too.
987 wxLogError(_("Failed to open temporary file."));
997 static bool wxCreateTempImpl(
998 const wxString
& prefix
,
999 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
1002 bool deleteOnClose
= true;
1004 *name
= wxCreateTempImpl(prefix
,
1005 WXFILEARGS(fileTemp
, ffileTemp
),
1008 bool ok
= !name
->empty();
1013 else if (ok
&& wxRemoveFile(*name
))
1021 static void wxAssignTempImpl(
1023 const wxString
& prefix
,
1024 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
1027 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
1029 if ( tempname
.empty() )
1031 // error, failed to get temp file name
1036 fn
->Assign(tempname
);
1041 void wxFileName::AssignTempFileName(const wxString
& prefix
)
1043 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
1047 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
1049 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
1052 #endif // wxUSE_FILE || wxUSE_FFILE
1057 wxString
wxCreateTempFileName(const wxString
& prefix
,
1059 bool *deleteOnClose
)
1061 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
1064 bool wxCreateTempFile(const wxString
& prefix
,
1068 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
1071 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1073 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
1078 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
1080 return wxCreateTempFileName(prefix
, fileTemp
);
1083 #endif // wxUSE_FILE
1088 wxString
wxCreateTempFileName(const wxString
& prefix
,
1090 bool *deleteOnClose
)
1092 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1095 bool wxCreateTempFile(const wxString
& prefix
,
1099 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1103 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1105 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1110 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1112 return wxCreateTempFileName(prefix
, fileTemp
);
1115 #endif // wxUSE_FFILE
1118 // ----------------------------------------------------------------------------
1119 // directory operations
1120 // ----------------------------------------------------------------------------
1122 // helper of GetTempDir(): check if the given directory exists and return it if
1123 // it does or an empty string otherwise
1127 wxString
CheckIfDirExists(const wxString
& dir
)
1129 return wxFileName::DirExists(dir
) ? dir
: wxString();
1132 } // anonymous namespace
1134 wxString
wxFileName::GetTempDir()
1136 // first try getting it from environment: this allows overriding the values
1137 // used by default if the user wants to create temporary files in another
1139 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1142 dir
= CheckIfDirExists(wxGetenv("TMP"));
1144 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1147 // if no environment variables are set, use the system default
1150 #if defined(__WXWINCE__)
1151 dir
= CheckIfDirExists(wxT("\\temp"));
1152 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1153 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1155 wxLogLastError(wxT("GetTempPath"));
1157 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1158 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1159 #endif // systems with native way
1162 // fall back to hard coded value
1165 #ifdef __UNIX_LIKE__
1166 dir
= CheckIfDirExists("/tmp");
1168 #endif // __UNIX_LIKE__
1175 bool wxFileName::Mkdir( int perm
, int flags
) const
1177 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1180 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1182 if ( flags
& wxPATH_MKDIR_FULL
)
1184 // split the path in components
1185 wxFileName filename
;
1186 filename
.AssignDir(dir
);
1189 if ( filename
.HasVolume())
1191 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1194 wxArrayString dirs
= filename
.GetDirs();
1195 size_t count
= dirs
.GetCount();
1196 for ( size_t i
= 0; i
< count
; i
++ )
1198 if ( i
> 0 || filename
.IsAbsolute() )
1199 currPath
+= wxFILE_SEP_PATH
;
1200 currPath
+= dirs
[i
];
1202 if (!DirExists(currPath
))
1204 if (!wxMkdir(currPath
, perm
))
1206 // no need to try creating further directories
1216 return ::wxMkdir( dir
, perm
);
1219 bool wxFileName::Rmdir(int flags
) const
1221 return wxFileName::Rmdir( GetPath(), flags
);
1224 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1227 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1229 // SHFileOperation needs double null termination string
1230 // but without separator at the end of the path
1232 if ( path
.Last() == wxFILE_SEP_PATH
)
1236 SHFILEOPSTRUCT fileop
;
1237 wxZeroMemory(fileop
);
1238 fileop
.wFunc
= FO_DELETE
;
1239 fileop
.pFrom
= path
.fn_str();
1240 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1242 // FOF_NOERRORUI is not defined in WinCE
1243 fileop
.fFlags
|= FOF_NOERRORUI
;
1246 int ret
= SHFileOperation(&fileop
);
1249 // SHFileOperation may return non-Win32 error codes, so the error
1250 // message can be incorrect
1251 wxLogApiError(wxT("SHFileOperation"), ret
);
1257 else if ( flags
& wxPATH_RMDIR_FULL
)
1259 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1260 #endif // !__WXMSW__
1263 if ( path
.Last() != wxFILE_SEP_PATH
)
1264 path
+= wxFILE_SEP_PATH
;
1268 if ( !d
.IsOpened() )
1273 // first delete all subdirectories
1274 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1277 wxFileName::Rmdir(path
+ filename
, flags
);
1278 cont
= d
.GetNext(&filename
);
1282 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1284 // delete all files too
1285 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1288 ::wxRemoveFile(path
+ filename
);
1289 cont
= d
.GetNext(&filename
);
1292 #endif // !__WXMSW__
1295 return ::wxRmdir(dir
);
1298 // ----------------------------------------------------------------------------
1299 // path normalization
1300 // ----------------------------------------------------------------------------
1302 bool wxFileName::Normalize(int flags
,
1303 const wxString
& cwd
,
1304 wxPathFormat format
)
1306 // deal with env vars renaming first as this may seriously change the path
1307 if ( flags
& wxPATH_NORM_ENV_VARS
)
1309 wxString pathOrig
= GetFullPath(format
);
1310 wxString path
= wxExpandEnvVars(pathOrig
);
1311 if ( path
!= pathOrig
)
1317 // the existing path components
1318 wxArrayString dirs
= GetDirs();
1320 // the path to prepend in front to make the path absolute
1323 format
= GetFormat(format
);
1325 // set up the directory to use for making the path absolute later
1326 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1330 curDir
.AssignCwd(GetVolume());
1332 else // cwd provided
1334 curDir
.AssignDir(cwd
);
1338 // handle ~ stuff under Unix only
1339 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1341 if ( !dirs
.IsEmpty() )
1343 wxString dir
= dirs
[0u];
1344 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1346 // to make the path absolute use the home directory
1347 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1353 // transform relative path into abs one
1354 if ( curDir
.IsOk() )
1356 // this path may be relative because it doesn't have the volume name
1357 // and still have m_relative=true; in this case we shouldn't modify
1358 // our directory components but just set the current volume
1359 if ( !HasVolume() && curDir
.HasVolume() )
1361 SetVolume(curDir
.GetVolume());
1365 // yes, it was the case - we don't need curDir then
1370 // finally, prepend curDir to the dirs array
1371 wxArrayString dirsNew
= curDir
.GetDirs();
1372 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1374 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1375 // return for some reason an absolute path, then curDir maybe not be absolute!
1376 if ( !curDir
.m_relative
)
1378 // we have prepended an absolute path and thus we are now an absolute
1382 // else if (flags & wxPATH_NORM_ABSOLUTE):
1383 // should we warn the user that we didn't manage to make the path absolute?
1386 // now deal with ".", ".." and the rest
1388 size_t count
= dirs
.GetCount();
1389 for ( size_t n
= 0; n
< count
; n
++ )
1391 wxString dir
= dirs
[n
];
1393 if ( flags
& wxPATH_NORM_DOTS
)
1395 if ( dir
== wxT(".") )
1401 if ( dir
== wxT("..") )
1403 if ( m_dirs
.IsEmpty() )
1405 wxLogError(_("The path '%s' contains too many \"..\"!"),
1406 GetFullPath().c_str());
1410 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1418 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1419 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1422 if (GetShortcutTarget(GetFullPath(format
), filename
))
1430 #if defined(__WIN32__)
1431 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1433 Assign(GetLongPath());
1437 // Change case (this should be kept at the end of the function, to ensure
1438 // that the path doesn't change any more after we normalize its case)
1439 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1441 m_volume
.MakeLower();
1445 // directory entries must be made lower case as well
1446 count
= m_dirs
.GetCount();
1447 for ( size_t i
= 0; i
< count
; i
++ )
1449 m_dirs
[i
].MakeLower();
1457 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1458 const wxString
& replacementFmtString
,
1459 wxPathFormat format
)
1461 // look into stringForm for the contents of the given environment variable
1463 if (envname
.empty() ||
1464 !wxGetEnv(envname
, &val
))
1469 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1470 // do not touch the file name and the extension
1472 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1473 stringForm
.Replace(val
, replacement
);
1475 // Now assign ourselves the modified path:
1476 Assign(stringForm
, GetFullName(), format
);
1482 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1484 wxString homedir
= wxGetHomeDir();
1485 if (homedir
.empty())
1488 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1489 // do not touch the file name and the extension
1491 stringForm
.Replace(homedir
, "~");
1493 // Now assign ourselves the modified path:
1494 Assign(stringForm
, GetFullName(), format
);
1499 // ----------------------------------------------------------------------------
1500 // get the shortcut target
1501 // ----------------------------------------------------------------------------
1503 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1504 // The .lnk file is a plain text file so it should be easy to
1505 // make it work. Hint from Google Groups:
1506 // "If you open up a lnk file, you'll see a
1507 // number, followed by a pound sign (#), followed by more text. The
1508 // number is the number of characters that follows the pound sign. The
1509 // characters after the pound sign are the command line (which _can_
1510 // include arguments) to be executed. Any path (e.g. \windows\program
1511 // files\myapp.exe) that includes spaces needs to be enclosed in
1512 // quotation marks."
1514 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1515 // The following lines are necessary under WinCE
1516 // #include "wx/msw/private.h"
1517 // #include <ole2.h>
1519 #if defined(__WXWINCE__)
1520 #include <shlguid.h>
1523 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1524 wxString
& targetFilename
,
1525 wxString
* arguments
) const
1527 wxString path
, file
, ext
;
1528 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1532 bool success
= false;
1534 // Assume it's not a shortcut if it doesn't end with lnk
1535 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1538 // create a ShellLink object
1539 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1540 IID_IShellLink
, (LPVOID
*) &psl
);
1542 if (SUCCEEDED(hres
))
1545 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1546 if (SUCCEEDED(hres
))
1548 WCHAR wsz
[MAX_PATH
];
1550 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1553 hres
= ppf
->Load(wsz
, 0);
1556 if (SUCCEEDED(hres
))
1559 // Wrong prototype in early versions
1560 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1561 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1563 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1565 targetFilename
= wxString(buf
);
1566 success
= (shortcutPath
!= targetFilename
);
1568 psl
->GetArguments(buf
, 2048);
1570 if (!args
.empty() && arguments
)
1582 #endif // __WIN32__ && !__WXWINCE__
1585 // ----------------------------------------------------------------------------
1586 // absolute/relative paths
1587 // ----------------------------------------------------------------------------
1589 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1591 // unix paths beginning with ~ are reported as being absolute
1592 if ( format
== wxPATH_UNIX
)
1594 if ( !m_dirs
.IsEmpty() )
1596 wxString dir
= m_dirs
[0u];
1598 if (!dir
.empty() && dir
[0u] == wxT('~'))
1603 // if our path doesn't start with a path separator, it's not an absolute
1608 if ( !GetVolumeSeparator(format
).empty() )
1610 // this format has volumes and an absolute path must have one, it's not
1611 // enough to have the full path to be an absolute file under Windows
1612 if ( GetVolume().empty() )
1619 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1621 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1623 // get cwd only once - small time saving
1624 wxString cwd
= wxGetCwd();
1625 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1626 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1628 bool withCase
= IsCaseSensitive(format
);
1630 // we can't do anything if the files live on different volumes
1631 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1637 // same drive, so we don't need our volume
1640 // remove common directories starting at the top
1641 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1642 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1645 fnBase
.m_dirs
.RemoveAt(0);
1648 // add as many ".." as needed
1649 size_t count
= fnBase
.m_dirs
.GetCount();
1650 for ( size_t i
= 0; i
< count
; i
++ )
1652 m_dirs
.Insert(wxT(".."), 0u);
1655 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1657 // a directory made relative with respect to itself is '.' under Unix
1658 // and DOS, by definition (but we don't have to insert "./" for the
1660 if ( m_dirs
.IsEmpty() && IsDir() )
1662 m_dirs
.Add(wxT('.'));
1672 // ----------------------------------------------------------------------------
1673 // filename kind tests
1674 // ----------------------------------------------------------------------------
1676 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1678 wxFileName fn1
= *this,
1681 // get cwd only once - small time saving
1682 wxString cwd
= wxGetCwd();
1683 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1684 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1686 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1689 // TODO: compare inodes for Unix, this works even when filenames are
1690 // different but files are the same (symlinks) (VZ)
1696 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1698 // only Unix filenames are truely case-sensitive
1699 return GetFormat(format
) == wxPATH_UNIX
;
1703 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1705 // Inits to forbidden characters that are common to (almost) all platforms.
1706 wxString strForbiddenChars
= wxT("*?");
1708 // If asserts, wxPathFormat has been changed. In case of a new path format
1709 // addition, the following code might have to be updated.
1710 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1711 switch ( GetFormat(format
) )
1714 wxFAIL_MSG( wxT("Unknown path format") );
1715 // !! Fall through !!
1721 // On a Mac even names with * and ? are allowed (Tested with OS
1722 // 9.2.1 and OS X 10.2.5)
1723 strForbiddenChars
= wxEmptyString
;
1727 strForbiddenChars
+= wxT("\\/:\"<>|");
1734 return strForbiddenChars
;
1738 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1741 return wxEmptyString
;
1745 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1746 (GetFormat(format
) == wxPATH_VMS
) )
1748 sepVol
= wxFILE_SEP_DSK
;
1757 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1760 switch ( GetFormat(format
) )
1763 // accept both as native APIs do but put the native one first as
1764 // this is the one we use in GetFullPath()
1765 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1769 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1773 seps
= wxFILE_SEP_PATH_UNIX
;
1777 seps
= wxFILE_SEP_PATH_MAC
;
1781 seps
= wxFILE_SEP_PATH_VMS
;
1789 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1791 format
= GetFormat(format
);
1793 // under VMS the end of the path is ']', not the path separator used to
1794 // separate the components
1795 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1799 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1801 // wxString::Find() doesn't work as expected with NUL - it will always find
1802 // it, so test for it separately
1803 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1806 // ----------------------------------------------------------------------------
1807 // path components manipulation
1808 // ----------------------------------------------------------------------------
1810 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1814 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1819 const size_t len
= dir
.length();
1820 for ( size_t n
= 0; n
< len
; n
++ )
1822 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1824 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1833 void wxFileName::AppendDir( const wxString
& dir
)
1835 if ( IsValidDirComponent(dir
) )
1839 void wxFileName::PrependDir( const wxString
& dir
)
1844 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1846 if ( IsValidDirComponent(dir
) )
1847 m_dirs
.Insert(dir
, before
);
1850 void wxFileName::RemoveDir(size_t pos
)
1852 m_dirs
.RemoveAt(pos
);
1855 // ----------------------------------------------------------------------------
1857 // ----------------------------------------------------------------------------
1859 void wxFileName::SetFullName(const wxString
& fullname
)
1861 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1862 &m_name
, &m_ext
, &m_hasExt
);
1865 wxString
wxFileName::GetFullName() const
1867 wxString fullname
= m_name
;
1870 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1876 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1878 format
= GetFormat( format
);
1882 // return the volume with the path as well if requested
1883 if ( flags
& wxPATH_GET_VOLUME
)
1885 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1888 // the leading character
1893 fullpath
+= wxFILE_SEP_PATH_MAC
;
1898 fullpath
+= wxFILE_SEP_PATH_DOS
;
1902 wxFAIL_MSG( wxT("Unknown path format") );
1908 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1913 // no leading character here but use this place to unset
1914 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1915 // as, if I understand correctly, there should never be a dot
1916 // before the closing bracket
1917 flags
&= ~wxPATH_GET_SEPARATOR
;
1920 if ( m_dirs
.empty() )
1922 // there is nothing more
1926 // then concatenate all the path components using the path separator
1927 if ( format
== wxPATH_VMS
)
1929 fullpath
+= wxT('[');
1932 const size_t dirCount
= m_dirs
.GetCount();
1933 for ( size_t i
= 0; i
< dirCount
; i
++ )
1938 if ( m_dirs
[i
] == wxT(".") )
1940 // skip appending ':', this shouldn't be done in this
1941 // case as "::" is interpreted as ".." under Unix
1945 // convert back from ".." to nothing
1946 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1947 fullpath
+= m_dirs
[i
];
1951 wxFAIL_MSG( wxT("Unexpected path format") );
1952 // still fall through
1956 fullpath
+= m_dirs
[i
];
1960 // TODO: What to do with ".." under VMS
1962 // convert back from ".." to nothing
1963 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1964 fullpath
+= m_dirs
[i
];
1968 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1969 fullpath
+= GetPathSeparator(format
);
1972 if ( format
== wxPATH_VMS
)
1974 fullpath
+= wxT(']');
1980 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1982 // we already have a function to get the path
1983 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1986 // now just add the file name and extension to it
1987 fullpath
+= GetFullName();
1992 // Return the short form of the path (returns identity on non-Windows platforms)
1993 wxString
wxFileName::GetShortPath() const
1995 wxString
path(GetFullPath());
1997 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1998 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
2002 if ( ::GetShortPathName
2005 wxStringBuffer(pathOut
, sz
),
2017 // Return the long form of the path (returns identity on non-Windows platforms)
2018 wxString
wxFileName::GetLongPath() const
2021 path
= GetFullPath();
2023 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2025 #if wxUSE_DYNLIB_CLASS
2026 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
2028 // this is MT-safe as in the worst case we're going to resolve the function
2029 // twice -- but as the result is the same in both threads, it's ok
2030 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
2031 if ( !s_pfnGetLongPathName
)
2033 static bool s_triedToLoad
= false;
2035 if ( !s_triedToLoad
)
2037 s_triedToLoad
= true;
2039 wxDynamicLibrary
dllKernel(wxT("kernel32"));
2041 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
2046 #endif // Unicode/ANSI
2048 if ( dllKernel
.HasSymbol(GetLongPathName
) )
2050 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
2051 dllKernel
.GetSymbol(GetLongPathName
);
2054 // note that kernel32.dll can be unloaded, it stays in memory
2055 // anyhow as all Win32 programs link to it and so it's safe to call
2056 // GetLongPathName() even after unloading it
2060 if ( s_pfnGetLongPathName
)
2062 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
2065 if ( (*s_pfnGetLongPathName
)
2068 wxStringBuffer(pathOut
, dwSize
),
2076 #endif // wxUSE_DYNLIB_CLASS
2078 // The OS didn't support GetLongPathName, or some other error.
2079 // We need to call FindFirstFile on each component in turn.
2081 WIN32_FIND_DATA findFileData
;
2085 pathOut
= GetVolume() +
2086 GetVolumeSeparator(wxPATH_DOS
) +
2087 GetPathSeparator(wxPATH_DOS
);
2089 pathOut
= wxEmptyString
;
2091 wxArrayString dirs
= GetDirs();
2092 dirs
.Add(GetFullName());
2096 size_t count
= dirs
.GetCount();
2097 for ( size_t i
= 0; i
< count
; i
++ )
2099 const wxString
& dir
= dirs
[i
];
2101 // We're using pathOut to collect the long-name path, but using a
2102 // temporary for appending the last path component which may be
2104 tmpPath
= pathOut
+ dir
;
2106 // We must not process "." or ".." here as they would be (unexpectedly)
2107 // replaced by the corresponding directory names so just leave them
2110 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2111 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2112 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2114 tmpPath
+= wxFILE_SEP_PATH
;
2119 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
2120 if (hFind
== INVALID_HANDLE_VALUE
)
2122 // Error: most likely reason is that path doesn't exist, so
2123 // append any unprocessed parts and return
2124 for ( i
+= 1; i
< count
; i
++ )
2125 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2130 pathOut
+= findFileData
.cFileName
;
2131 if ( (i
< (count
-1)) )
2132 pathOut
+= wxFILE_SEP_PATH
;
2138 #endif // Win32/!Win32
2143 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2145 if (format
== wxPATH_NATIVE
)
2147 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2148 format
= wxPATH_DOS
;
2149 #elif defined(__VMS)
2150 format
= wxPATH_VMS
;
2152 format
= wxPATH_UNIX
;
2158 #ifdef wxHAS_FILESYSTEM_VOLUMES
2161 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2163 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2165 wxString
vol(drive
);
2166 vol
+= wxFILE_SEP_DSK
;
2167 if ( flags
& wxPATH_GET_SEPARATOR
)
2168 vol
+= wxFILE_SEP_PATH
;
2173 #endif // wxHAS_FILESYSTEM_VOLUMES
2175 // ----------------------------------------------------------------------------
2176 // path splitting function
2177 // ----------------------------------------------------------------------------
2181 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2182 wxString
*pstrVolume
,
2184 wxPathFormat format
)
2186 format
= GetFormat(format
);
2188 wxString fullpath
= fullpathWithVolume
;
2190 // special Windows UNC paths hack: transform \\share\path into share:path
2191 if ( IsUNCPath(fullpath
, format
) )
2193 fullpath
.erase(0, 2);
2195 size_t posFirstSlash
=
2196 fullpath
.find_first_of(GetPathTerminators(format
));
2197 if ( posFirstSlash
!= wxString::npos
)
2199 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2201 // UNC paths are always absolute, right? (FIXME)
2202 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2206 // We separate the volume here
2207 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2209 wxString sepVol
= GetVolumeSeparator(format
);
2211 // we have to exclude the case of a colon in the very beginning of the
2212 // string as it can't be a volume separator (nor can this be a valid
2213 // DOS file name at all but we'll leave dealing with this to our caller)
2214 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2215 if ( posFirstColon
&& posFirstColon
!= wxString::npos
)
2219 *pstrVolume
= fullpath
.Left(posFirstColon
);
2222 // remove the volume name and the separator from the full path
2223 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2228 *pstrPath
= fullpath
;
2232 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2233 wxString
*pstrVolume
,
2238 wxPathFormat format
)
2240 format
= GetFormat(format
);
2243 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2245 // find the positions of the last dot and last path separator in the path
2246 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2247 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2249 // check whether this dot occurs at the very beginning of a path component
2250 if ( (posLastDot
!= wxString::npos
) &&
2252 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2253 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2255 // dot may be (and commonly -- at least under Unix -- is) the first
2256 // character of the filename, don't treat the entire filename as
2257 // extension in this case
2258 posLastDot
= wxString::npos
;
2261 // if we do have a dot and a slash, check that the dot is in the name part
2262 if ( (posLastDot
!= wxString::npos
) &&
2263 (posLastSlash
!= wxString::npos
) &&
2264 (posLastDot
< posLastSlash
) )
2266 // the dot is part of the path, not the start of the extension
2267 posLastDot
= wxString::npos
;
2270 // now fill in the variables provided by user
2273 if ( posLastSlash
== wxString::npos
)
2280 // take everything up to the path separator but take care to make
2281 // the path equal to something like '/', not empty, for the files
2282 // immediately under root directory
2283 size_t len
= posLastSlash
;
2285 // this rule does not apply to mac since we do not start with colons (sep)
2286 // except for relative paths
2287 if ( !len
&& format
!= wxPATH_MAC
)
2290 *pstrPath
= fullpath
.Left(len
);
2292 // special VMS hack: remove the initial bracket
2293 if ( format
== wxPATH_VMS
)
2295 if ( (*pstrPath
)[0u] == wxT('[') )
2296 pstrPath
->erase(0, 1);
2303 // take all characters starting from the one after the last slash and
2304 // up to, but excluding, the last dot
2305 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2307 if ( posLastDot
== wxString::npos
)
2309 // take all until the end
2310 count
= wxString::npos
;
2312 else if ( posLastSlash
== wxString::npos
)
2316 else // have both dot and slash
2318 count
= posLastDot
- posLastSlash
- 1;
2321 *pstrName
= fullpath
.Mid(nStart
, count
);
2324 // finally deal with the extension here: we have an added complication that
2325 // extension may be empty (but present) as in "foo." where trailing dot
2326 // indicates the empty extension at the end -- and hence we must remember
2327 // that we have it independently of pstrExt
2328 if ( posLastDot
== wxString::npos
)
2338 // take everything after the dot
2340 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2347 void wxFileName::SplitPath(const wxString
& fullpath
,
2351 wxPathFormat format
)
2354 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2358 path
->Prepend(wxGetVolumeString(volume
, format
));
2363 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2365 wxFileName
fn(fullpath
);
2367 return fn
.GetFullPath();
2370 // ----------------------------------------------------------------------------
2372 // ----------------------------------------------------------------------------
2376 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2377 const wxDateTime
*dtMod
,
2378 const wxDateTime
*dtCreate
) const
2380 #if defined(__WIN32__)
2381 FILETIME ftAccess
, ftCreate
, ftWrite
;
2384 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2386 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2388 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2394 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2396 wxLogError(_("Setting directory access times is not supported "
2397 "under this OS version"));
2402 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2406 path
= GetFullPath();
2410 wxFileHandle
fh(path
, wxFileHandle::WriteAttr
, flags
);
2413 if ( ::SetFileTime(fh
,
2414 dtCreate
? &ftCreate
: NULL
,
2415 dtAccess
? &ftAccess
: NULL
,
2416 dtMod
? &ftWrite
: NULL
) )
2421 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2422 wxUnusedVar(dtCreate
);
2424 if ( !dtAccess
&& !dtMod
)
2426 // can't modify the creation time anyhow, don't try
2430 // if dtAccess or dtMod is not specified, use the other one (which must be
2431 // non NULL because of the test above) for both times
2433 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2434 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2435 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2439 #else // other platform
2440 wxUnusedVar(dtAccess
);
2442 wxUnusedVar(dtCreate
);
2445 wxLogSysError(_("Failed to modify file times for '%s'"),
2446 GetFullPath().c_str());
2451 bool wxFileName::Touch() const
2453 #if defined(__UNIX_LIKE__)
2454 // under Unix touching file is simple: just pass NULL to utime()
2455 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2460 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2463 #else // other platform
2464 wxDateTime dtNow
= wxDateTime::Now();
2466 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2470 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2472 wxDateTime
*dtCreate
) const
2474 #if defined(__WIN32__)
2475 // we must use different methods for the files and directories under
2476 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2477 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2480 FILETIME ftAccess
, ftCreate
, ftWrite
;
2483 // implemented in msw/dir.cpp
2484 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2485 FILETIME
*, FILETIME
*, FILETIME
*);
2487 // we should pass the path without the trailing separator to
2488 // wxGetDirectoryTimes()
2489 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2490 &ftAccess
, &ftCreate
, &ftWrite
);
2494 wxFileHandle
fh(GetFullPath(), wxFileHandle::ReadAttr
);
2497 ok
= ::GetFileTime(fh
,
2498 dtCreate
? &ftCreate
: NULL
,
2499 dtAccess
? &ftAccess
: NULL
,
2500 dtMod
? &ftWrite
: NULL
) != 0;
2511 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2513 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2515 ConvertFileTimeToWx(dtMod
, ftWrite
);
2519 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2520 // no need to test for IsDir() here
2522 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2525 dtAccess
->Set(stBuf
.st_atime
);
2527 dtMod
->Set(stBuf
.st_mtime
);
2529 dtCreate
->Set(stBuf
.st_ctime
);
2533 #else // other platform
2534 wxUnusedVar(dtAccess
);
2536 wxUnusedVar(dtCreate
);
2539 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2540 GetFullPath().c_str());
2545 #endif // wxUSE_DATETIME
2548 // ----------------------------------------------------------------------------
2549 // file size functions
2550 // ----------------------------------------------------------------------------
2555 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2557 if (!wxFileExists(filename
))
2558 return wxInvalidSize
;
2560 #if defined(__WXPALMOS__)
2562 return wxInvalidSize
;
2563 #elif defined(__WIN32__)
2564 wxFileHandle
f(filename
, wxFileHandle::ReadAttr
);
2566 return wxInvalidSize
;
2568 DWORD lpFileSizeHigh
;
2569 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2570 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2571 return wxInvalidSize
;
2573 return wxULongLong(lpFileSizeHigh
, ret
);
2574 #else // ! __WIN32__
2576 #ifndef wxNEED_WX_UNISTD_H
2577 if (wxStat( filename
.fn_str() , &st
) != 0)
2579 if (wxStat( filename
, &st
) != 0)
2581 return wxInvalidSize
;
2582 return wxULongLong(st
.st_size
);
2587 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2588 const wxString
&nullsize
,
2591 static const double KILOBYTESIZE
= 1024.0;
2592 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2593 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2594 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2596 if (bs
== 0 || bs
== wxInvalidSize
)
2599 double bytesize
= bs
.ToDouble();
2600 if (bytesize
< KILOBYTESIZE
)
2601 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2602 if (bytesize
< MEGABYTESIZE
)
2603 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2604 if (bytesize
< GIGABYTESIZE
)
2605 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2606 if (bytesize
< TERABYTESIZE
)
2607 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2609 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2612 wxULongLong
wxFileName::GetSize() const
2614 return GetSize(GetFullPath());
2617 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2619 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2622 #endif // wxUSE_LONGLONG
2624 // ----------------------------------------------------------------------------
2625 // Mac-specific functions
2626 // ----------------------------------------------------------------------------
2628 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2633 class MacDefaultExtensionRecord
2636 MacDefaultExtensionRecord()
2642 // default copy ctor, assignment operator and dtor are ok
2644 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2648 m_creator
= creator
;
2656 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2658 bool gMacDefaultExtensionsInited
= false;
2660 #include "wx/arrimpl.cpp"
2662 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2664 MacDefaultExtensionArray gMacDefaultExtensions
;
2666 // load the default extensions
2667 const MacDefaultExtensionRecord gDefaults
[] =
2669 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2670 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2671 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2674 void MacEnsureDefaultExtensionsLoaded()
2676 if ( !gMacDefaultExtensionsInited
)
2678 // we could load the pc exchange prefs here too
2679 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2681 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2683 gMacDefaultExtensionsInited
= true;
2687 } // anonymous namespace
2689 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2692 FSCatalogInfo catInfo
;
2695 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2697 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2699 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2700 finfo
->fileType
= type
;
2701 finfo
->fileCreator
= creator
;
2702 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2709 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2712 FSCatalogInfo catInfo
;
2715 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2717 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2719 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2720 *type
= finfo
->fileType
;
2721 *creator
= finfo
->fileCreator
;
2728 bool wxFileName::MacSetDefaultTypeAndCreator()
2730 wxUint32 type
, creator
;
2731 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2734 return MacSetTypeAndCreator( type
, creator
) ;
2739 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2741 MacEnsureDefaultExtensionsLoaded() ;
2742 wxString extl
= ext
.Lower() ;
2743 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2745 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2747 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2748 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2755 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2757 MacEnsureDefaultExtensionsLoaded();
2758 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2759 gMacDefaultExtensions
.Add( rec
);
2762 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON