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 m_hFile
= ::CreateFile
171 filename
.fn_str(), // name
172 mode
== Read
? GENERIC_READ
// access mask
174 FILE_SHARE_READ
| // sharing mode
175 FILE_SHARE_WRITE
, // (allow everything)
176 NULL
, // no secutity attr
177 OPEN_EXISTING
, // creation disposition
179 NULL
// no template file
182 if ( m_hFile
== INVALID_HANDLE_VALUE
)
186 wxLogSysError(_("Failed to open '%s' for reading"),
191 wxLogSysError(_("Failed to open '%s' for writing"),
199 if ( m_hFile
!= INVALID_HANDLE_VALUE
)
201 if ( !::CloseHandle(m_hFile
) )
203 wxLogSysError(_("Failed to close file handle"));
208 // return true only if the file could be opened successfully
209 bool IsOk() const { return m_hFile
!= INVALID_HANDLE_VALUE
; }
212 operator HANDLE() const { return m_hFile
; }
220 // ----------------------------------------------------------------------------
222 // ----------------------------------------------------------------------------
224 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
226 // convert between wxDateTime and FILETIME which is a 64-bit value representing
227 // the number of 100-nanosecond intervals since January 1, 1601.
229 static void ConvertFileTimeToWx(wxDateTime
*dt
, const FILETIME
&ft
)
231 FILETIME ftcopy
= ft
;
233 if ( !::FileTimeToLocalFileTime(&ftcopy
, &ftLocal
) )
235 wxLogLastError(wxT("FileTimeToLocalFileTime"));
239 if ( !::FileTimeToSystemTime(&ftLocal
, &st
) )
241 wxLogLastError(wxT("FileTimeToSystemTime"));
244 dt
->Set(st
.wDay
, wxDateTime::Month(st
.wMonth
- 1), st
.wYear
,
245 st
.wHour
, st
.wMinute
, st
.wSecond
, st
.wMilliseconds
);
248 static void ConvertWxToFileTime(FILETIME
*ft
, const wxDateTime
& dt
)
251 st
.wDay
= dt
.GetDay();
252 st
.wMonth
= (WORD
)(dt
.GetMonth() + 1);
253 st
.wYear
= (WORD
)dt
.GetYear();
254 st
.wHour
= dt
.GetHour();
255 st
.wMinute
= dt
.GetMinute();
256 st
.wSecond
= dt
.GetSecond();
257 st
.wMilliseconds
= dt
.GetMillisecond();
260 if ( !::SystemTimeToFileTime(&st
, &ftLocal
) )
262 wxLogLastError(wxT("SystemTimeToFileTime"));
265 if ( !::LocalFileTimeToFileTime(&ftLocal
, ft
) )
267 wxLogLastError(wxT("LocalFileTimeToFileTime"));
271 #endif // wxUSE_DATETIME && __WIN32__
273 // return a string with the volume par
274 static wxString
wxGetVolumeString(const wxString
& volume
, wxPathFormat format
)
278 if ( !volume
.empty() )
280 format
= wxFileName::GetFormat(format
);
282 // Special Windows UNC paths hack, part 2: undo what we did in
283 // SplitPath() and make an UNC path if we have a drive which is not a
284 // single letter (hopefully the network shares can't be one letter only
285 // although I didn't find any authoritative docs on this)
286 if ( format
== wxPATH_DOS
&& volume
.length() > 1 )
288 path
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_DOS
<< volume
;
290 else if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
292 path
<< volume
<< wxFileName::GetVolumeSeparator(format
);
300 // return true if the character is a DOS path separator i.e. either a slash or
302 inline bool IsDOSPathSep(wxUniChar ch
)
304 return ch
== wxFILE_SEP_PATH_DOS
|| ch
== wxFILE_SEP_PATH_UNIX
;
307 // return true if the format used is the DOS/Windows one and the string looks
309 static bool IsUNCPath(const wxString
& path
, wxPathFormat format
)
311 return format
== wxPATH_DOS
&&
312 path
.length() >= 4 && // "\\a" can't be a UNC path
313 IsDOSPathSep(path
[0u]) &&
314 IsDOSPathSep(path
[1u]) &&
315 !IsDOSPathSep(path
[2u]);
318 } // anonymous namespace
320 // ============================================================================
322 // ============================================================================
324 // ----------------------------------------------------------------------------
325 // wxFileName construction
326 // ----------------------------------------------------------------------------
328 void wxFileName::Assign( const wxFileName
&filepath
)
330 m_volume
= filepath
.GetVolume();
331 m_dirs
= filepath
.GetDirs();
332 m_name
= filepath
.GetName();
333 m_ext
= filepath
.GetExt();
334 m_relative
= filepath
.m_relative
;
335 m_hasExt
= filepath
.m_hasExt
;
338 void wxFileName::Assign(const wxString
& volume
,
339 const wxString
& path
,
340 const wxString
& name
,
345 // we should ignore paths which look like UNC shares because we already
346 // have the volume here and the UNC notation (\\server\path) is only valid
347 // for paths which don't start with a volume, so prevent SetPath() from
348 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
350 // note also that this is a rather ugly way to do what we want (passing
351 // some kind of flag telling to ignore UNC paths to SetPath() would be
352 // better) but this is the safest thing to do to avoid breaking backwards
353 // compatibility in 2.8
354 if ( IsUNCPath(path
, format
) )
356 // remove one of the 2 leading backslashes to ensure that it's not
357 // recognized as an UNC path by SetPath()
358 wxString
pathNonUNC(path
, 1, wxString::npos
);
359 SetPath(pathNonUNC
, format
);
361 else // no UNC complications
363 SetPath(path
, format
);
373 void wxFileName::SetPath( const wxString
& pathOrig
, wxPathFormat format
)
377 if ( pathOrig
.empty() )
385 format
= GetFormat( format
);
387 // 0) deal with possible volume part first
390 SplitVolume(pathOrig
, &volume
, &path
, format
);
391 if ( !volume
.empty() )
398 // 1) Determine if the path is relative or absolute.
399 wxChar leadingChar
= path
[0u];
404 m_relative
= leadingChar
== wxT(':');
406 // We then remove a leading ":". The reason is in our
407 // storage form for relative paths:
408 // ":dir:file.txt" actually means "./dir/file.txt" in
409 // DOS notation and should get stored as
410 // (relative) (dir) (file.txt)
411 // "::dir:file.txt" actually means "../dir/file.txt"
412 // stored as (relative) (..) (dir) (file.txt)
413 // This is important only for the Mac as an empty dir
414 // actually means <UP>, whereas under DOS, double
415 // slashes can be ignored: "\\\\" is the same as "\\".
421 // TODO: what is the relative path format here?
426 wxFAIL_MSG( wxT("Unknown path format") );
427 // !! Fall through !!
430 m_relative
= leadingChar
!= wxT('/');
434 m_relative
= !IsPathSeparator(leadingChar
, format
);
439 // 2) Break up the path into its members. If the original path
440 // was just "/" or "\\", m_dirs will be empty. We know from
441 // the m_relative field, if this means "nothing" or "root dir".
443 wxStringTokenizer
tn( path
, GetPathSeparators(format
) );
445 while ( tn
.HasMoreTokens() )
447 wxString token
= tn
.GetNextToken();
449 // Remove empty token under DOS and Unix, interpret them
453 if (format
== wxPATH_MAC
)
454 m_dirs
.Add( wxT("..") );
464 void wxFileName::Assign(const wxString
& fullpath
,
467 wxString volume
, path
, name
, ext
;
469 SplitPath(fullpath
, &volume
, &path
, &name
, &ext
, &hasExt
, format
);
471 Assign(volume
, path
, name
, ext
, hasExt
, format
);
474 void wxFileName::Assign(const wxString
& fullpathOrig
,
475 const wxString
& fullname
,
478 // always recognize fullpath as directory, even if it doesn't end with a
480 wxString fullpath
= fullpathOrig
;
481 if ( !fullpath
.empty() && !wxEndsWithPathSeparator(fullpath
) )
483 fullpath
+= GetPathSeparator(format
);
486 wxString volume
, path
, name
, ext
;
489 // do some consistency checks: the name should be really just the filename
490 // and the path should be really just a path
491 wxString volDummy
, pathDummy
, nameDummy
, extDummy
;
493 SplitPath(fullname
, &volDummy
, &pathDummy
, &name
, &ext
, &hasExt
, format
);
495 wxASSERT_MSG( volDummy
.empty() && pathDummy
.empty(),
496 wxT("the file name shouldn't contain the path") );
498 SplitPath(fullpath
, &volume
, &path
, &nameDummy
, &extDummy
, format
);
501 // This test makes no sense on an OpenVMS system.
502 wxASSERT_MSG( nameDummy
.empty() && extDummy
.empty(),
503 wxT("the path shouldn't contain file name nor extension") );
505 Assign(volume
, path
, name
, ext
, hasExt
, format
);
508 void wxFileName::Assign(const wxString
& pathOrig
,
509 const wxString
& name
,
515 SplitVolume(pathOrig
, &volume
, &path
, format
);
517 Assign(volume
, path
, name
, ext
, format
);
520 void wxFileName::AssignDir(const wxString
& dir
, wxPathFormat format
)
522 Assign(dir
, wxEmptyString
, format
);
525 void wxFileName::Clear()
531 m_ext
= wxEmptyString
;
533 // we don't have any absolute path for now
541 wxFileName
wxFileName::FileName(const wxString
& file
, wxPathFormat format
)
543 return wxFileName(file
, format
);
547 wxFileName
wxFileName::DirName(const wxString
& dir
, wxPathFormat format
)
550 fn
.AssignDir(dir
, format
);
554 // ----------------------------------------------------------------------------
556 // ----------------------------------------------------------------------------
558 bool wxFileName::FileExists() const
560 return wxFileName::FileExists( GetFullPath() );
563 bool wxFileName::FileExists( const wxString
&file
)
565 return ::wxFileExists( file
);
568 bool wxFileName::DirExists() const
570 return wxFileName::DirExists( GetPath() );
573 bool wxFileName::DirExists( const wxString
&dir
)
575 return ::wxDirExists( dir
);
578 // ----------------------------------------------------------------------------
579 // CWD and HOME stuff
580 // ----------------------------------------------------------------------------
582 void wxFileName::AssignCwd(const wxString
& volume
)
584 AssignDir(wxFileName::GetCwd(volume
));
588 wxString
wxFileName::GetCwd(const wxString
& volume
)
590 // if we have the volume, we must get the current directory on this drive
591 // and to do this we have to chdir to this volume - at least under Windows,
592 // I don't know how to get the current drive on another volume elsewhere
595 if ( !volume
.empty() )
598 SetCwd(volume
+ GetVolumeSeparator());
601 wxString cwd
= ::wxGetCwd();
603 if ( !volume
.empty() )
611 bool wxFileName::SetCwd() const
613 return wxFileName::SetCwd( GetPath() );
616 bool wxFileName::SetCwd( const wxString
&cwd
)
618 return ::wxSetWorkingDirectory( cwd
);
621 void wxFileName::AssignHomeDir()
623 AssignDir(wxFileName::GetHomeDir());
626 wxString
wxFileName::GetHomeDir()
628 return ::wxGetHomeDir();
632 // ----------------------------------------------------------------------------
633 // CreateTempFileName
634 // ----------------------------------------------------------------------------
636 #if wxUSE_FILE || wxUSE_FFILE
639 #if !defined wx_fdopen && defined HAVE_FDOPEN
640 #define wx_fdopen fdopen
643 // NB: GetTempFileName() under Windows creates the file, so using
644 // O_EXCL there would fail
646 #define wxOPEN_EXCL 0
648 #define wxOPEN_EXCL O_EXCL
652 #ifdef wxOpenOSFHandle
653 #define WX_HAVE_DELETE_ON_CLOSE
654 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
656 static int wxOpenWithDeleteOnClose(const wxString
& filename
)
658 DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
660 DWORD disposition
= OPEN_ALWAYS
;
662 DWORD attributes
= FILE_ATTRIBUTE_TEMPORARY
|
663 FILE_FLAG_DELETE_ON_CLOSE
;
665 HANDLE h
= ::CreateFile(filename
.fn_str(), access
, 0, NULL
,
666 disposition
, attributes
, NULL
);
668 return wxOpenOSFHandle(h
, wxO_BINARY
);
670 #endif // wxOpenOSFHandle
673 // Helper to open the file
675 static int wxTempOpen(const wxString
& path
, bool *deleteOnClose
)
677 #ifdef WX_HAVE_DELETE_ON_CLOSE
679 return wxOpenWithDeleteOnClose(path
);
682 *deleteOnClose
= false;
684 return wxOpen(path
, wxO_BINARY
| O_RDWR
| O_CREAT
| wxOPEN_EXCL
, 0600);
689 // Helper to open the file and attach it to the wxFFile
691 static bool wxTempOpen(wxFFile
*file
, const wxString
& path
, bool *deleteOnClose
)
694 *deleteOnClose
= false;
695 return file
->Open(path
, wxT("w+b"));
697 int fd
= wxTempOpen(path
, deleteOnClose
);
700 file
->Attach(wx_fdopen(fd
, "w+b"));
701 return file
->IsOpened();
704 #endif // wxUSE_FFILE
708 #define WXFILEARGS(x, y) y
710 #define WXFILEARGS(x, y) x
712 #define WXFILEARGS(x, y) x, y
716 // Implementation of wxFileName::CreateTempFileName().
718 static wxString
wxCreateTempImpl(
719 const wxString
& prefix
,
720 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
721 bool *deleteOnClose
= NULL
)
723 #if wxUSE_FILE && wxUSE_FFILE
724 wxASSERT(fileTemp
== NULL
|| ffileTemp
== NULL
);
726 wxString path
, dir
, name
;
727 bool wantDeleteOnClose
= false;
731 // set the result to false initially
732 wantDeleteOnClose
= *deleteOnClose
;
733 *deleteOnClose
= false;
737 // easier if it alwasys points to something
738 deleteOnClose
= &wantDeleteOnClose
;
741 // use the directory specified by the prefix
742 wxFileName::SplitPath(prefix
, &dir
, &name
, NULL
/* extension */);
746 dir
= wxFileName::GetTempDir();
749 #if defined(__WXWINCE__)
750 path
= dir
+ wxT("\\") + name
;
752 while (wxFileName::FileExists(path
))
754 path
= dir
+ wxT("\\") + name
;
759 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
760 if ( !::GetTempFileName(dir
.fn_str(), name
.fn_str(), 0,
761 wxStringBuffer(path
, MAX_PATH
+ 1)) )
763 wxLogLastError(wxT("GetTempFileName"));
771 if ( !wxEndsWithPathSeparator(dir
) &&
772 (name
.empty() || !wxIsPathSeparator(name
[0u])) )
774 path
+= wxFILE_SEP_PATH
;
779 #if defined(HAVE_MKSTEMP)
780 // scratch space for mkstemp()
781 path
+= wxT("XXXXXX");
783 // we need to copy the path to the buffer in which mkstemp() can modify it
784 wxCharBuffer
buf(path
.fn_str());
786 // cast is safe because the string length doesn't change
787 int fdTemp
= mkstemp( (char*)(const char*) buf
);
790 // this might be not necessary as mkstemp() on most systems should have
791 // already done it but it doesn't hurt neither...
794 else // mkstemp() succeeded
796 path
= wxConvFile
.cMB2WX( (const char*) buf
);
799 // avoid leaking the fd
802 fileTemp
->Attach(fdTemp
);
811 ffileTemp
->Attach(wx_fdopen(fdTemp
, "r+b"));
813 ffileTemp
->Open(path
, wxT("r+b"));
824 #else // !HAVE_MKSTEMP
828 path
+= wxT("XXXXXX");
830 wxCharBuffer buf
= wxConvFile
.cWX2MB( path
);
831 if ( !mktemp( (char*)(const char*) buf
) )
837 path
= wxConvFile
.cMB2WX( (const char*) buf
);
839 #else // !HAVE_MKTEMP (includes __DOS__)
840 // generate the unique file name ourselves
841 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
842 path
<< (unsigned int)getpid();
847 static const size_t numTries
= 1000;
848 for ( size_t n
= 0; n
< numTries
; n
++ )
850 // 3 hex digits is enough for numTries == 1000 < 4096
851 pathTry
= path
+ wxString::Format(wxT("%.03x"), (unsigned int) n
);
852 if ( !wxFileName::FileExists(pathTry
) )
861 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
863 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
865 #endif // Windows/!Windows
869 wxLogSysError(_("Failed to create a temporary file name"));
875 // open the file - of course, there is a race condition here, this is
876 // why we always prefer using mkstemp()...
878 if ( fileTemp
&& !fileTemp
->IsOpened() )
880 *deleteOnClose
= wantDeleteOnClose
;
881 int fd
= wxTempOpen(path
, deleteOnClose
);
883 fileTemp
->Attach(fd
);
890 if ( ffileTemp
&& !ffileTemp
->IsOpened() )
892 *deleteOnClose
= wantDeleteOnClose
;
893 ok
= wxTempOpen(ffileTemp
, path
, deleteOnClose
);
899 // FIXME: If !ok here should we loop and try again with another
900 // file name? That is the standard recourse if open(O_EXCL)
901 // fails, though of course it should be protected against
902 // possible infinite looping too.
904 wxLogError(_("Failed to open temporary file."));
914 static bool wxCreateTempImpl(
915 const wxString
& prefix
,
916 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
),
919 bool deleteOnClose
= true;
921 *name
= wxCreateTempImpl(prefix
,
922 WXFILEARGS(fileTemp
, ffileTemp
),
925 bool ok
= !name
->empty();
930 else if (ok
&& wxRemoveFile(*name
))
938 static void wxAssignTempImpl(
940 const wxString
& prefix
,
941 WXFILEARGS(wxFile
*fileTemp
, wxFFile
*ffileTemp
))
944 tempname
= wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, ffileTemp
));
946 if ( tempname
.empty() )
948 // error, failed to get temp file name
953 fn
->Assign(tempname
);
958 void wxFileName::AssignTempFileName(const wxString
& prefix
)
960 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, NULL
));
964 wxString
wxFileName::CreateTempFileName(const wxString
& prefix
)
966 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, NULL
));
969 #endif // wxUSE_FILE || wxUSE_FFILE
974 wxString
wxCreateTempFileName(const wxString
& prefix
,
978 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), deleteOnClose
);
981 bool wxCreateTempFile(const wxString
& prefix
,
985 return wxCreateTempImpl(prefix
, WXFILEARGS(fileTemp
, NULL
), name
);
988 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
990 wxAssignTempImpl(this, prefix
, WXFILEARGS(fileTemp
, NULL
));
995 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFile
*fileTemp
)
997 return wxCreateTempFileName(prefix
, fileTemp
);
1000 #endif // wxUSE_FILE
1005 wxString
wxCreateTempFileName(const wxString
& prefix
,
1007 bool *deleteOnClose
)
1009 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), deleteOnClose
);
1012 bool wxCreateTempFile(const wxString
& prefix
,
1016 return wxCreateTempImpl(prefix
, WXFILEARGS(NULL
, fileTemp
), name
);
1020 void wxFileName::AssignTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1022 wxAssignTempImpl(this, prefix
, WXFILEARGS(NULL
, fileTemp
));
1027 wxFileName::CreateTempFileName(const wxString
& prefix
, wxFFile
*fileTemp
)
1029 return wxCreateTempFileName(prefix
, fileTemp
);
1032 #endif // wxUSE_FFILE
1035 // ----------------------------------------------------------------------------
1036 // directory operations
1037 // ----------------------------------------------------------------------------
1039 // helper of GetTempDir(): check if the given directory exists and return it if
1040 // it does or an empty string otherwise
1044 wxString
CheckIfDirExists(const wxString
& dir
)
1046 return wxFileName::DirExists(dir
) ? dir
: wxString();
1049 } // anonymous namespace
1051 wxString
wxFileName::GetTempDir()
1053 // first try getting it from environment: this allows overriding the values
1054 // used by default if the user wants to create temporary files in another
1056 wxString dir
= CheckIfDirExists(wxGetenv("TMPDIR"));
1059 dir
= CheckIfDirExists(wxGetenv("TMP"));
1061 dir
= CheckIfDirExists(wxGetenv("TEMP"));
1064 // if no environment variables are set, use the system default
1067 #if defined(__WXWINCE__)
1068 dir
= CheckIfDirExists(wxT("\\temp"));
1069 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1070 if ( !::GetTempPath(MAX_PATH
, wxStringBuffer(dir
, MAX_PATH
+ 1)) )
1072 wxLogLastError(wxT("GetTempPath"));
1074 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1075 dir
= wxMacFindFolder(short(kOnSystemDisk
), kTemporaryFolderType
, kCreateFolder
);
1076 #endif // systems with native way
1079 // fall back to hard coded value
1082 #ifdef __UNIX_LIKE__
1083 dir
= CheckIfDirExists("/tmp");
1085 #endif // __UNIX_LIKE__
1092 bool wxFileName::Mkdir( int perm
, int flags
) const
1094 return wxFileName::Mkdir(GetPath(), perm
, flags
);
1097 bool wxFileName::Mkdir( const wxString
& dir
, int perm
, int flags
)
1099 if ( flags
& wxPATH_MKDIR_FULL
)
1101 // split the path in components
1102 wxFileName filename
;
1103 filename
.AssignDir(dir
);
1106 if ( filename
.HasVolume())
1108 currPath
<< wxGetVolumeString(filename
.GetVolume(), wxPATH_NATIVE
);
1111 wxArrayString dirs
= filename
.GetDirs();
1112 size_t count
= dirs
.GetCount();
1113 for ( size_t i
= 0; i
< count
; i
++ )
1115 if ( i
> 0 || filename
.IsAbsolute() )
1116 currPath
+= wxFILE_SEP_PATH
;
1117 currPath
+= dirs
[i
];
1119 if (!DirExists(currPath
))
1121 if (!wxMkdir(currPath
, perm
))
1123 // no need to try creating further directories
1133 return ::wxMkdir( dir
, perm
);
1136 bool wxFileName::Rmdir(int flags
) const
1138 return wxFileName::Rmdir( GetPath(), flags
);
1141 bool wxFileName::Rmdir(const wxString
& dir
, int flags
)
1144 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1146 // SHFileOperation needs double null termination string
1147 // but without separator at the end of the path
1149 if ( path
.Last() == wxFILE_SEP_PATH
)
1153 SHFILEOPSTRUCT fileop
;
1154 wxZeroMemory(fileop
);
1155 fileop
.wFunc
= FO_DELETE
;
1156 fileop
.pFrom
= path
.fn_str();
1157 fileop
.fFlags
= FOF_SILENT
| FOF_NOCONFIRMATION
;
1159 // FOF_NOERRORUI is not defined in WinCE
1160 fileop
.fFlags
|= FOF_NOERRORUI
;
1163 int ret
= SHFileOperation(&fileop
);
1166 // SHFileOperation may return non-Win32 error codes, so the error
1167 // message can be incorrect
1168 wxLogApiError(wxT("SHFileOperation"), ret
);
1174 else if ( flags
& wxPATH_RMDIR_FULL
)
1176 if ( flags
!= 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1177 #endif // !__WXMSW__
1180 if ( path
.Last() != wxFILE_SEP_PATH
)
1181 path
+= wxFILE_SEP_PATH
;
1185 if ( !d
.IsOpened() )
1190 // first delete all subdirectories
1191 bool cont
= d
.GetFirst(&filename
, "", wxDIR_DIRS
| wxDIR_HIDDEN
);
1194 wxFileName::Rmdir(path
+ filename
, flags
);
1195 cont
= d
.GetNext(&filename
);
1199 if ( flags
& wxPATH_RMDIR_RECURSIVE
)
1201 // delete all files too
1202 cont
= d
.GetFirst(&filename
, "", wxDIR_FILES
| wxDIR_HIDDEN
);
1205 ::wxRemoveFile(path
+ filename
);
1206 cont
= d
.GetNext(&filename
);
1209 #endif // !__WXMSW__
1212 return ::wxRmdir(dir
);
1215 // ----------------------------------------------------------------------------
1216 // path normalization
1217 // ----------------------------------------------------------------------------
1219 bool wxFileName::Normalize(int flags
,
1220 const wxString
& cwd
,
1221 wxPathFormat format
)
1223 // deal with env vars renaming first as this may seriously change the path
1224 if ( flags
& wxPATH_NORM_ENV_VARS
)
1226 wxString pathOrig
= GetFullPath(format
);
1227 wxString path
= wxExpandEnvVars(pathOrig
);
1228 if ( path
!= pathOrig
)
1234 // the existing path components
1235 wxArrayString dirs
= GetDirs();
1237 // the path to prepend in front to make the path absolute
1240 format
= GetFormat(format
);
1242 // set up the directory to use for making the path absolute later
1243 if ( (flags
& wxPATH_NORM_ABSOLUTE
) && !IsAbsolute(format
) )
1247 curDir
.AssignCwd(GetVolume());
1249 else // cwd provided
1251 curDir
.AssignDir(cwd
);
1255 // handle ~ stuff under Unix only
1256 if ( (format
== wxPATH_UNIX
) && (flags
& wxPATH_NORM_TILDE
) && m_relative
)
1258 if ( !dirs
.IsEmpty() )
1260 wxString dir
= dirs
[0u];
1261 if ( !dir
.empty() && dir
[0u] == wxT('~') )
1263 // to make the path absolute use the home directory
1264 curDir
.AssignDir(wxGetUserHome(dir
.c_str() + 1));
1270 // transform relative path into abs one
1271 if ( curDir
.IsOk() )
1273 // this path may be relative because it doesn't have the volume name
1274 // and still have m_relative=true; in this case we shouldn't modify
1275 // our directory components but just set the current volume
1276 if ( !HasVolume() && curDir
.HasVolume() )
1278 SetVolume(curDir
.GetVolume());
1282 // yes, it was the case - we don't need curDir then
1287 // finally, prepend curDir to the dirs array
1288 wxArrayString dirsNew
= curDir
.GetDirs();
1289 WX_PREPEND_ARRAY(dirs
, dirsNew
);
1291 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1292 // return for some reason an absolute path, then curDir maybe not be absolute!
1293 if ( !curDir
.m_relative
)
1295 // we have prepended an absolute path and thus we are now an absolute
1299 // else if (flags & wxPATH_NORM_ABSOLUTE):
1300 // should we warn the user that we didn't manage to make the path absolute?
1303 // now deal with ".", ".." and the rest
1305 size_t count
= dirs
.GetCount();
1306 for ( size_t n
= 0; n
< count
; n
++ )
1308 wxString dir
= dirs
[n
];
1310 if ( flags
& wxPATH_NORM_DOTS
)
1312 if ( dir
== wxT(".") )
1318 if ( dir
== wxT("..") )
1320 if ( m_dirs
.IsEmpty() )
1322 wxLogError(_("The path '%s' contains too many \"..\"!"),
1323 GetFullPath().c_str());
1327 m_dirs
.RemoveAt(m_dirs
.GetCount() - 1);
1335 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1336 if ( (flags
& wxPATH_NORM_SHORTCUT
) )
1339 if (GetShortcutTarget(GetFullPath(format
), filename
))
1347 #if defined(__WIN32__)
1348 if ( (flags
& wxPATH_NORM_LONG
) && (format
== wxPATH_DOS
) )
1350 Assign(GetLongPath());
1354 // Change case (this should be kept at the end of the function, to ensure
1355 // that the path doesn't change any more after we normalize its case)
1356 if ( (flags
& wxPATH_NORM_CASE
) && !IsCaseSensitive(format
) )
1358 m_volume
.MakeLower();
1362 // directory entries must be made lower case as well
1363 count
= m_dirs
.GetCount();
1364 for ( size_t i
= 0; i
< count
; i
++ )
1366 m_dirs
[i
].MakeLower();
1374 bool wxFileName::ReplaceEnvVariable(const wxString
& envname
,
1375 const wxString
& replacementFmtString
,
1376 wxPathFormat format
)
1378 // look into stringForm for the contents of the given environment variable
1380 if (envname
.empty() ||
1381 !wxGetEnv(envname
, &val
))
1386 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1387 // do not touch the file name and the extension
1389 wxString replacement
= wxString::Format(replacementFmtString
, envname
);
1390 stringForm
.Replace(val
, replacement
);
1392 // Now assign ourselves the modified path:
1393 Assign(stringForm
, GetFullName(), format
);
1399 bool wxFileName::ReplaceHomeDir(wxPathFormat format
)
1401 wxString homedir
= wxGetHomeDir();
1402 if (homedir
.empty())
1405 wxString stringForm
= GetPath(wxPATH_GET_VOLUME
, format
);
1406 // do not touch the file name and the extension
1408 stringForm
.Replace(homedir
, "~");
1410 // Now assign ourselves the modified path:
1411 Assign(stringForm
, GetFullName(), format
);
1416 // ----------------------------------------------------------------------------
1417 // get the shortcut target
1418 // ----------------------------------------------------------------------------
1420 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1421 // The .lnk file is a plain text file so it should be easy to
1422 // make it work. Hint from Google Groups:
1423 // "If you open up a lnk file, you'll see a
1424 // number, followed by a pound sign (#), followed by more text. The
1425 // number is the number of characters that follows the pound sign. The
1426 // characters after the pound sign are the command line (which _can_
1427 // include arguments) to be executed. Any path (e.g. \windows\program
1428 // files\myapp.exe) that includes spaces needs to be enclosed in
1429 // quotation marks."
1431 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1432 // The following lines are necessary under WinCE
1433 // #include "wx/msw/private.h"
1434 // #include <ole2.h>
1436 #if defined(__WXWINCE__)
1437 #include <shlguid.h>
1440 bool wxFileName::GetShortcutTarget(const wxString
& shortcutPath
,
1441 wxString
& targetFilename
,
1442 wxString
* arguments
) const
1444 wxString path
, file
, ext
;
1445 wxFileName::SplitPath(shortcutPath
, & path
, & file
, & ext
);
1449 bool success
= false;
1451 // Assume it's not a shortcut if it doesn't end with lnk
1452 if (ext
.CmpNoCase(wxT("lnk"))!=0)
1455 // create a ShellLink object
1456 hres
= CoCreateInstance(CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
1457 IID_IShellLink
, (LPVOID
*) &psl
);
1459 if (SUCCEEDED(hres
))
1462 hres
= psl
->QueryInterface( IID_IPersistFile
, (LPVOID
*) &ppf
);
1463 if (SUCCEEDED(hres
))
1465 WCHAR wsz
[MAX_PATH
];
1467 MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, shortcutPath
.mb_str(), -1, wsz
,
1470 hres
= ppf
->Load(wsz
, 0);
1473 if (SUCCEEDED(hres
))
1476 // Wrong prototype in early versions
1477 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1478 psl
->GetPath((CHAR
*) buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1480 psl
->GetPath(buf
, 2048, NULL
, SLGP_UNCPRIORITY
);
1482 targetFilename
= wxString(buf
);
1483 success
= (shortcutPath
!= targetFilename
);
1485 psl
->GetArguments(buf
, 2048);
1487 if (!args
.empty() && arguments
)
1499 #endif // __WIN32__ && !__WXWINCE__
1502 // ----------------------------------------------------------------------------
1503 // absolute/relative paths
1504 // ----------------------------------------------------------------------------
1506 bool wxFileName::IsAbsolute(wxPathFormat format
) const
1508 // unix paths beginning with ~ are reported as being absolute
1509 if ( format
== wxPATH_UNIX
)
1511 if ( !m_dirs
.IsEmpty() )
1513 wxString dir
= m_dirs
[0u];
1515 if (!dir
.empty() && dir
[0u] == wxT('~'))
1520 // if our path doesn't start with a path separator, it's not an absolute
1525 if ( !GetVolumeSeparator(format
).empty() )
1527 // this format has volumes and an absolute path must have one, it's not
1528 // enough to have the full path to be an absolute file under Windows
1529 if ( GetVolume().empty() )
1536 bool wxFileName::MakeRelativeTo(const wxString
& pathBase
, wxPathFormat format
)
1538 wxFileName fnBase
= wxFileName::DirName(pathBase
, format
);
1540 // get cwd only once - small time saving
1541 wxString cwd
= wxGetCwd();
1542 Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1543 fnBase
.Normalize(wxPATH_NORM_ALL
& ~wxPATH_NORM_CASE
, cwd
, format
);
1545 bool withCase
= IsCaseSensitive(format
);
1547 // we can't do anything if the files live on different volumes
1548 if ( !GetVolume().IsSameAs(fnBase
.GetVolume(), withCase
) )
1554 // same drive, so we don't need our volume
1557 // remove common directories starting at the top
1558 while ( !m_dirs
.IsEmpty() && !fnBase
.m_dirs
.IsEmpty() &&
1559 m_dirs
[0u].IsSameAs(fnBase
.m_dirs
[0u], withCase
) )
1562 fnBase
.m_dirs
.RemoveAt(0);
1565 // add as many ".." as needed
1566 size_t count
= fnBase
.m_dirs
.GetCount();
1567 for ( size_t i
= 0; i
< count
; i
++ )
1569 m_dirs
.Insert(wxT(".."), 0u);
1572 if ( format
== wxPATH_UNIX
|| format
== wxPATH_DOS
)
1574 // a directory made relative with respect to itself is '.' under Unix
1575 // and DOS, by definition (but we don't have to insert "./" for the
1577 if ( m_dirs
.IsEmpty() && IsDir() )
1579 m_dirs
.Add(wxT('.'));
1589 // ----------------------------------------------------------------------------
1590 // filename kind tests
1591 // ----------------------------------------------------------------------------
1593 bool wxFileName::SameAs(const wxFileName
& filepath
, wxPathFormat format
) const
1595 wxFileName fn1
= *this,
1598 // get cwd only once - small time saving
1599 wxString cwd
= wxGetCwd();
1600 fn1
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1601 fn2
.Normalize(wxPATH_NORM_ALL
| wxPATH_NORM_CASE
, cwd
, format
);
1603 if ( fn1
.GetFullPath() == fn2
.GetFullPath() )
1606 // TODO: compare inodes for Unix, this works even when filenames are
1607 // different but files are the same (symlinks) (VZ)
1613 bool wxFileName::IsCaseSensitive( wxPathFormat format
)
1615 // only Unix filenames are truely case-sensitive
1616 return GetFormat(format
) == wxPATH_UNIX
;
1620 wxString
wxFileName::GetForbiddenChars(wxPathFormat format
)
1622 // Inits to forbidden characters that are common to (almost) all platforms.
1623 wxString strForbiddenChars
= wxT("*?");
1625 // If asserts, wxPathFormat has been changed. In case of a new path format
1626 // addition, the following code might have to be updated.
1627 wxCOMPILE_TIME_ASSERT(wxPATH_MAX
== 5, wxPathFormatChanged
);
1628 switch ( GetFormat(format
) )
1631 wxFAIL_MSG( wxT("Unknown path format") );
1632 // !! Fall through !!
1638 // On a Mac even names with * and ? are allowed (Tested with OS
1639 // 9.2.1 and OS X 10.2.5)
1640 strForbiddenChars
= wxEmptyString
;
1644 strForbiddenChars
+= wxT("\\/:\"<>|");
1651 return strForbiddenChars
;
1655 wxString
wxFileName::GetVolumeSeparator(wxPathFormat
WXUNUSED_IN_WINCE(format
))
1658 return wxEmptyString
;
1662 if ( (GetFormat(format
) == wxPATH_DOS
) ||
1663 (GetFormat(format
) == wxPATH_VMS
) )
1665 sepVol
= wxFILE_SEP_DSK
;
1674 wxString
wxFileName::GetPathSeparators(wxPathFormat format
)
1677 switch ( GetFormat(format
) )
1680 // accept both as native APIs do but put the native one first as
1681 // this is the one we use in GetFullPath()
1682 seps
<< wxFILE_SEP_PATH_DOS
<< wxFILE_SEP_PATH_UNIX
;
1686 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1690 seps
= wxFILE_SEP_PATH_UNIX
;
1694 seps
= wxFILE_SEP_PATH_MAC
;
1698 seps
= wxFILE_SEP_PATH_VMS
;
1706 wxString
wxFileName::GetPathTerminators(wxPathFormat format
)
1708 format
= GetFormat(format
);
1710 // under VMS the end of the path is ']', not the path separator used to
1711 // separate the components
1712 return format
== wxPATH_VMS
? wxString(wxT(']')) : GetPathSeparators(format
);
1716 bool wxFileName::IsPathSeparator(wxChar ch
, wxPathFormat format
)
1718 // wxString::Find() doesn't work as expected with NUL - it will always find
1719 // it, so test for it separately
1720 return ch
!= wxT('\0') && GetPathSeparators(format
).Find(ch
) != wxNOT_FOUND
;
1723 // ----------------------------------------------------------------------------
1724 // path components manipulation
1725 // ----------------------------------------------------------------------------
1727 /* static */ bool wxFileName::IsValidDirComponent(const wxString
& dir
)
1731 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1736 const size_t len
= dir
.length();
1737 for ( size_t n
= 0; n
< len
; n
++ )
1739 if ( dir
[n
] == GetVolumeSeparator() || IsPathSeparator(dir
[n
]) )
1741 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1750 void wxFileName::AppendDir( const wxString
& dir
)
1752 if ( IsValidDirComponent(dir
) )
1756 void wxFileName::PrependDir( const wxString
& dir
)
1761 void wxFileName::InsertDir(size_t before
, const wxString
& dir
)
1763 if ( IsValidDirComponent(dir
) )
1764 m_dirs
.Insert(dir
, before
);
1767 void wxFileName::RemoveDir(size_t pos
)
1769 m_dirs
.RemoveAt(pos
);
1772 // ----------------------------------------------------------------------------
1774 // ----------------------------------------------------------------------------
1776 void wxFileName::SetFullName(const wxString
& fullname
)
1778 SplitPath(fullname
, NULL
/* no volume */, NULL
/* no path */,
1779 &m_name
, &m_ext
, &m_hasExt
);
1782 wxString
wxFileName::GetFullName() const
1784 wxString fullname
= m_name
;
1787 fullname
<< wxFILE_SEP_EXT
<< m_ext
;
1793 wxString
wxFileName::GetPath( int flags
, wxPathFormat format
) const
1795 format
= GetFormat( format
);
1799 // return the volume with the path as well if requested
1800 if ( flags
& wxPATH_GET_VOLUME
)
1802 fullpath
+= wxGetVolumeString(GetVolume(), format
);
1805 // the leading character
1810 fullpath
+= wxFILE_SEP_PATH_MAC
;
1815 fullpath
+= wxFILE_SEP_PATH_DOS
;
1819 wxFAIL_MSG( wxT("Unknown path format") );
1825 fullpath
+= wxFILE_SEP_PATH_UNIX
;
1830 // no leading character here but use this place to unset
1831 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1832 // as, if I understand correctly, there should never be a dot
1833 // before the closing bracket
1834 flags
&= ~wxPATH_GET_SEPARATOR
;
1837 if ( m_dirs
.empty() )
1839 // there is nothing more
1843 // then concatenate all the path components using the path separator
1844 if ( format
== wxPATH_VMS
)
1846 fullpath
+= wxT('[');
1849 const size_t dirCount
= m_dirs
.GetCount();
1850 for ( size_t i
= 0; i
< dirCount
; i
++ )
1855 if ( m_dirs
[i
] == wxT(".") )
1857 // skip appending ':', this shouldn't be done in this
1858 // case as "::" is interpreted as ".." under Unix
1862 // convert back from ".." to nothing
1863 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1864 fullpath
+= m_dirs
[i
];
1868 wxFAIL_MSG( wxT("Unexpected path format") );
1869 // still fall through
1873 fullpath
+= m_dirs
[i
];
1877 // TODO: What to do with ".." under VMS
1879 // convert back from ".." to nothing
1880 if ( !m_dirs
[i
].IsSameAs(wxT("..")) )
1881 fullpath
+= m_dirs
[i
];
1885 if ( (flags
& wxPATH_GET_SEPARATOR
) || (i
!= dirCount
- 1) )
1886 fullpath
+= GetPathSeparator(format
);
1889 if ( format
== wxPATH_VMS
)
1891 fullpath
+= wxT(']');
1897 wxString
wxFileName::GetFullPath( wxPathFormat format
) const
1899 // we already have a function to get the path
1900 wxString fullpath
= GetPath(wxPATH_GET_VOLUME
| wxPATH_GET_SEPARATOR
,
1903 // now just add the file name and extension to it
1904 fullpath
+= GetFullName();
1909 // Return the short form of the path (returns identity on non-Windows platforms)
1910 wxString
wxFileName::GetShortPath() const
1912 wxString
path(GetFullPath());
1914 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1915 DWORD sz
= ::GetShortPathName(path
.fn_str(), NULL
, 0);
1919 if ( ::GetShortPathName
1922 wxStringBuffer(pathOut
, sz
),
1934 // Return the long form of the path (returns identity on non-Windows platforms)
1935 wxString
wxFileName::GetLongPath() const
1938 path
= GetFullPath();
1940 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1942 #if wxUSE_DYNLIB_CLASS
1943 typedef DWORD (WINAPI
*GET_LONG_PATH_NAME
)(const wxChar
*, wxChar
*, DWORD
);
1945 // this is MT-safe as in the worst case we're going to resolve the function
1946 // twice -- but as the result is the same in both threads, it's ok
1947 static GET_LONG_PATH_NAME s_pfnGetLongPathName
= NULL
;
1948 if ( !s_pfnGetLongPathName
)
1950 static bool s_triedToLoad
= false;
1952 if ( !s_triedToLoad
)
1954 s_triedToLoad
= true;
1956 wxDynamicLibrary
dllKernel(wxT("kernel32"));
1958 const wxChar
* GetLongPathName
= wxT("GetLongPathName")
1963 #endif // Unicode/ANSI
1965 if ( dllKernel
.HasSymbol(GetLongPathName
) )
1967 s_pfnGetLongPathName
= (GET_LONG_PATH_NAME
)
1968 dllKernel
.GetSymbol(GetLongPathName
);
1971 // note that kernel32.dll can be unloaded, it stays in memory
1972 // anyhow as all Win32 programs link to it and so it's safe to call
1973 // GetLongPathName() even after unloading it
1977 if ( s_pfnGetLongPathName
)
1979 DWORD dwSize
= (*s_pfnGetLongPathName
)(path
.fn_str(), NULL
, 0);
1982 if ( (*s_pfnGetLongPathName
)
1985 wxStringBuffer(pathOut
, dwSize
),
1993 #endif // wxUSE_DYNLIB_CLASS
1995 // The OS didn't support GetLongPathName, or some other error.
1996 // We need to call FindFirstFile on each component in turn.
1998 WIN32_FIND_DATA findFileData
;
2002 pathOut
= GetVolume() +
2003 GetVolumeSeparator(wxPATH_DOS
) +
2004 GetPathSeparator(wxPATH_DOS
);
2006 pathOut
= wxEmptyString
;
2008 wxArrayString dirs
= GetDirs();
2009 dirs
.Add(GetFullName());
2013 size_t count
= dirs
.GetCount();
2014 for ( size_t i
= 0; i
< count
; i
++ )
2016 const wxString
& dir
= dirs
[i
];
2018 // We're using pathOut to collect the long-name path, but using a
2019 // temporary for appending the last path component which may be
2021 tmpPath
= pathOut
+ dir
;
2023 // We must not process "." or ".." here as they would be (unexpectedly)
2024 // replaced by the corresponding directory names so just leave them
2027 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2028 if ( tmpPath
.empty() || dir
== '.' || dir
== ".." ||
2029 tmpPath
.Last() == GetVolumeSeparator(wxPATH_DOS
) )
2031 tmpPath
+= wxFILE_SEP_PATH
;
2036 hFind
= ::FindFirstFile(tmpPath
.fn_str(), &findFileData
);
2037 if (hFind
== INVALID_HANDLE_VALUE
)
2039 // Error: most likely reason is that path doesn't exist, so
2040 // append any unprocessed parts and return
2041 for ( i
+= 1; i
< count
; i
++ )
2042 tmpPath
+= wxFILE_SEP_PATH
+ dirs
[i
];
2047 pathOut
+= findFileData
.cFileName
;
2048 if ( (i
< (count
-1)) )
2049 pathOut
+= wxFILE_SEP_PATH
;
2055 #endif // Win32/!Win32
2060 wxPathFormat
wxFileName::GetFormat( wxPathFormat format
)
2062 if (format
== wxPATH_NATIVE
)
2064 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2065 format
= wxPATH_DOS
;
2066 #elif defined(__VMS)
2067 format
= wxPATH_VMS
;
2069 format
= wxPATH_UNIX
;
2075 #ifdef wxHAS_FILESYSTEM_VOLUMES
2078 wxString
wxFileName::GetVolumeString(char drive
, int flags
)
2080 wxASSERT_MSG( !(flags
& ~wxPATH_GET_SEPARATOR
), "invalid flag specified" );
2082 wxString
vol(drive
);
2083 vol
+= wxFILE_SEP_DSK
;
2084 if ( flags
& wxPATH_GET_SEPARATOR
)
2085 vol
+= wxFILE_SEP_PATH
;
2090 #endif // wxHAS_FILESYSTEM_VOLUMES
2092 // ----------------------------------------------------------------------------
2093 // path splitting function
2094 // ----------------------------------------------------------------------------
2098 wxFileName::SplitVolume(const wxString
& fullpathWithVolume
,
2099 wxString
*pstrVolume
,
2101 wxPathFormat format
)
2103 format
= GetFormat(format
);
2105 wxString fullpath
= fullpathWithVolume
;
2107 // special Windows UNC paths hack: transform \\share\path into share:path
2108 if ( IsUNCPath(fullpath
, format
) )
2110 fullpath
.erase(0, 2);
2112 size_t posFirstSlash
=
2113 fullpath
.find_first_of(GetPathTerminators(format
));
2114 if ( posFirstSlash
!= wxString::npos
)
2116 fullpath
[posFirstSlash
] = wxFILE_SEP_DSK
;
2118 // UNC paths are always absolute, right? (FIXME)
2119 fullpath
.insert(posFirstSlash
+ 1, 1, wxFILE_SEP_PATH_DOS
);
2123 // We separate the volume here
2124 if ( format
== wxPATH_DOS
|| format
== wxPATH_VMS
)
2126 wxString sepVol
= GetVolumeSeparator(format
);
2128 size_t posFirstColon
= fullpath
.find_first_of(sepVol
);
2129 if ( posFirstColon
!= wxString::npos
)
2133 *pstrVolume
= fullpath
.Left(posFirstColon
);
2136 // remove the volume name and the separator from the full path
2137 fullpath
.erase(0, posFirstColon
+ sepVol
.length());
2142 *pstrPath
= fullpath
;
2146 void wxFileName::SplitPath(const wxString
& fullpathWithVolume
,
2147 wxString
*pstrVolume
,
2152 wxPathFormat format
)
2154 format
= GetFormat(format
);
2157 SplitVolume(fullpathWithVolume
, pstrVolume
, &fullpath
, format
);
2159 // find the positions of the last dot and last path separator in the path
2160 size_t posLastDot
= fullpath
.find_last_of(wxFILE_SEP_EXT
);
2161 size_t posLastSlash
= fullpath
.find_last_of(GetPathTerminators(format
));
2163 // check whether this dot occurs at the very beginning of a path component
2164 if ( (posLastDot
!= wxString::npos
) &&
2166 IsPathSeparator(fullpath
[posLastDot
- 1]) ||
2167 (format
== wxPATH_VMS
&& fullpath
[posLastDot
- 1] == wxT(']'))) )
2169 // dot may be (and commonly -- at least under Unix -- is) the first
2170 // character of the filename, don't treat the entire filename as
2171 // extension in this case
2172 posLastDot
= wxString::npos
;
2175 // if we do have a dot and a slash, check that the dot is in the name part
2176 if ( (posLastDot
!= wxString::npos
) &&
2177 (posLastSlash
!= wxString::npos
) &&
2178 (posLastDot
< posLastSlash
) )
2180 // the dot is part of the path, not the start of the extension
2181 posLastDot
= wxString::npos
;
2184 // now fill in the variables provided by user
2187 if ( posLastSlash
== wxString::npos
)
2194 // take everything up to the path separator but take care to make
2195 // the path equal to something like '/', not empty, for the files
2196 // immediately under root directory
2197 size_t len
= posLastSlash
;
2199 // this rule does not apply to mac since we do not start with colons (sep)
2200 // except for relative paths
2201 if ( !len
&& format
!= wxPATH_MAC
)
2204 *pstrPath
= fullpath
.Left(len
);
2206 // special VMS hack: remove the initial bracket
2207 if ( format
== wxPATH_VMS
)
2209 if ( (*pstrPath
)[0u] == wxT('[') )
2210 pstrPath
->erase(0, 1);
2217 // take all characters starting from the one after the last slash and
2218 // up to, but excluding, the last dot
2219 size_t nStart
= posLastSlash
== wxString::npos
? 0 : posLastSlash
+ 1;
2221 if ( posLastDot
== wxString::npos
)
2223 // take all until the end
2224 count
= wxString::npos
;
2226 else if ( posLastSlash
== wxString::npos
)
2230 else // have both dot and slash
2232 count
= posLastDot
- posLastSlash
- 1;
2235 *pstrName
= fullpath
.Mid(nStart
, count
);
2238 // finally deal with the extension here: we have an added complication that
2239 // extension may be empty (but present) as in "foo." where trailing dot
2240 // indicates the empty extension at the end -- and hence we must remember
2241 // that we have it independently of pstrExt
2242 if ( posLastDot
== wxString::npos
)
2252 // take everything after the dot
2254 *pstrExt
= fullpath
.Mid(posLastDot
+ 1);
2261 void wxFileName::SplitPath(const wxString
& fullpath
,
2265 wxPathFormat format
)
2268 SplitPath(fullpath
, &volume
, path
, name
, ext
, format
);
2272 path
->Prepend(wxGetVolumeString(volume
, format
));
2277 wxString
wxFileName::StripExtension(const wxString
& fullpath
)
2279 wxFileName
fn(fullpath
);
2281 return fn
.GetFullPath();
2284 // ----------------------------------------------------------------------------
2286 // ----------------------------------------------------------------------------
2290 bool wxFileName::SetTimes(const wxDateTime
*dtAccess
,
2291 const wxDateTime
*dtMod
,
2292 const wxDateTime
*dtCreate
) const
2294 #if defined(__WIN32__)
2295 FILETIME ftAccess
, ftCreate
, ftWrite
;
2298 ConvertWxToFileTime(&ftCreate
, *dtCreate
);
2300 ConvertWxToFileTime(&ftAccess
, *dtAccess
);
2302 ConvertWxToFileTime(&ftWrite
, *dtMod
);
2308 if ( wxGetOsVersion() == wxOS_WINDOWS_9X
)
2310 wxLogError(_("Setting directory access times is not supported "
2311 "under this OS version"));
2316 flags
= FILE_FLAG_BACKUP_SEMANTICS
;
2320 path
= GetFullPath();
2324 wxFileHandle
fh(path
, wxFileHandle::Write
, flags
);
2327 if ( ::SetFileTime(fh
,
2328 dtCreate
? &ftCreate
: NULL
,
2329 dtAccess
? &ftAccess
: NULL
,
2330 dtMod
? &ftWrite
: NULL
) )
2335 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2336 wxUnusedVar(dtCreate
);
2338 if ( !dtAccess
&& !dtMod
)
2340 // can't modify the creation time anyhow, don't try
2344 // if dtAccess or dtMod is not specified, use the other one (which must be
2345 // non NULL because of the test above) for both times
2347 utm
.actime
= dtAccess
? dtAccess
->GetTicks() : dtMod
->GetTicks();
2348 utm
.modtime
= dtMod
? dtMod
->GetTicks() : dtAccess
->GetTicks();
2349 if ( utime(GetFullPath().fn_str(), &utm
) == 0 )
2353 #else // other platform
2354 wxUnusedVar(dtAccess
);
2356 wxUnusedVar(dtCreate
);
2359 wxLogSysError(_("Failed to modify file times for '%s'"),
2360 GetFullPath().c_str());
2365 bool wxFileName::Touch() const
2367 #if defined(__UNIX_LIKE__)
2368 // under Unix touching file is simple: just pass NULL to utime()
2369 if ( utime(GetFullPath().fn_str(), NULL
) == 0 )
2374 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2377 #else // other platform
2378 wxDateTime dtNow
= wxDateTime::Now();
2380 return SetTimes(&dtNow
, &dtNow
, NULL
/* don't change create time */);
2384 bool wxFileName::GetTimes(wxDateTime
*dtAccess
,
2386 wxDateTime
*dtCreate
) const
2388 #if defined(__WIN32__)
2389 // we must use different methods for the files and directories under
2390 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2391 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2394 FILETIME ftAccess
, ftCreate
, ftWrite
;
2397 // implemented in msw/dir.cpp
2398 extern bool wxGetDirectoryTimes(const wxString
& dirname
,
2399 FILETIME
*, FILETIME
*, FILETIME
*);
2401 // we should pass the path without the trailing separator to
2402 // wxGetDirectoryTimes()
2403 ok
= wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME
),
2404 &ftAccess
, &ftCreate
, &ftWrite
);
2408 wxFileHandle
fh(GetFullPath(), wxFileHandle::Read
);
2411 ok
= ::GetFileTime(fh
,
2412 dtCreate
? &ftCreate
: NULL
,
2413 dtAccess
? &ftAccess
: NULL
,
2414 dtMod
? &ftWrite
: NULL
) != 0;
2425 ConvertFileTimeToWx(dtCreate
, ftCreate
);
2427 ConvertFileTimeToWx(dtAccess
, ftAccess
);
2429 ConvertFileTimeToWx(dtMod
, ftWrite
);
2433 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2434 // no need to test for IsDir() here
2436 if ( wxStat( GetFullPath().c_str(), &stBuf
) == 0 )
2439 dtAccess
->Set(stBuf
.st_atime
);
2441 dtMod
->Set(stBuf
.st_mtime
);
2443 dtCreate
->Set(stBuf
.st_ctime
);
2447 #else // other platform
2448 wxUnusedVar(dtAccess
);
2450 wxUnusedVar(dtCreate
);
2453 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2454 GetFullPath().c_str());
2459 #endif // wxUSE_DATETIME
2462 // ----------------------------------------------------------------------------
2463 // file size functions
2464 // ----------------------------------------------------------------------------
2469 wxULongLong
wxFileName::GetSize(const wxString
&filename
)
2471 if (!wxFileExists(filename
))
2472 return wxInvalidSize
;
2474 #if defined(__WXPALMOS__)
2476 return wxInvalidSize
;
2477 #elif defined(__WIN32__)
2478 wxFileHandle
f(filename
, wxFileHandle::Read
);
2480 return wxInvalidSize
;
2482 DWORD lpFileSizeHigh
;
2483 DWORD ret
= GetFileSize(f
, &lpFileSizeHigh
);
2484 if ( ret
== INVALID_FILE_SIZE
&& ::GetLastError() != NO_ERROR
)
2485 return wxInvalidSize
;
2487 return wxULongLong(lpFileSizeHigh
, ret
);
2488 #else // ! __WIN32__
2490 #ifndef wxNEED_WX_UNISTD_H
2491 if (wxStat( filename
.fn_str() , &st
) != 0)
2493 if (wxStat( filename
, &st
) != 0)
2495 return wxInvalidSize
;
2496 return wxULongLong(st
.st_size
);
2501 wxString
wxFileName::GetHumanReadableSize(const wxULongLong
&bs
,
2502 const wxString
&nullsize
,
2505 static const double KILOBYTESIZE
= 1024.0;
2506 static const double MEGABYTESIZE
= 1024.0*KILOBYTESIZE
;
2507 static const double GIGABYTESIZE
= 1024.0*MEGABYTESIZE
;
2508 static const double TERABYTESIZE
= 1024.0*GIGABYTESIZE
;
2510 if (bs
== 0 || bs
== wxInvalidSize
)
2513 double bytesize
= bs
.ToDouble();
2514 if (bytesize
< KILOBYTESIZE
)
2515 return wxString::Format(_("%s B"), bs
.ToString().c_str());
2516 if (bytesize
< MEGABYTESIZE
)
2517 return wxString::Format(_("%.*f kB"), precision
, bytesize
/KILOBYTESIZE
);
2518 if (bytesize
< GIGABYTESIZE
)
2519 return wxString::Format(_("%.*f MB"), precision
, bytesize
/MEGABYTESIZE
);
2520 if (bytesize
< TERABYTESIZE
)
2521 return wxString::Format(_("%.*f GB"), precision
, bytesize
/GIGABYTESIZE
);
2523 return wxString::Format(_("%.*f TB"), precision
, bytesize
/TERABYTESIZE
);
2526 wxULongLong
wxFileName::GetSize() const
2528 return GetSize(GetFullPath());
2531 wxString
wxFileName::GetHumanReadableSize(const wxString
&failmsg
, int precision
) const
2533 return GetHumanReadableSize(GetSize(), failmsg
, precision
);
2536 #endif // wxUSE_LONGLONG
2538 // ----------------------------------------------------------------------------
2539 // Mac-specific functions
2540 // ----------------------------------------------------------------------------
2542 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2547 class MacDefaultExtensionRecord
2550 MacDefaultExtensionRecord()
2556 // default copy ctor, assignment operator and dtor are ok
2558 MacDefaultExtensionRecord(const wxString
& ext
, OSType type
, OSType creator
)
2562 m_creator
= creator
;
2570 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord
, MacDefaultExtensionArray
);
2572 bool gMacDefaultExtensionsInited
= false;
2574 #include "wx/arrimpl.cpp"
2576 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray
);
2578 MacDefaultExtensionArray gMacDefaultExtensions
;
2580 // load the default extensions
2581 const MacDefaultExtensionRecord gDefaults
[] =
2583 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2584 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2585 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2588 void MacEnsureDefaultExtensionsLoaded()
2590 if ( !gMacDefaultExtensionsInited
)
2592 // we could load the pc exchange prefs here too
2593 for ( size_t i
= 0 ; i
< WXSIZEOF( gDefaults
) ; ++i
)
2595 gMacDefaultExtensions
.Add( gDefaults
[i
] ) ;
2597 gMacDefaultExtensionsInited
= true;
2601 } // anonymous namespace
2603 bool wxFileName::MacSetTypeAndCreator( wxUint32 type
, wxUint32 creator
)
2606 FSCatalogInfo catInfo
;
2609 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2611 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2613 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2614 finfo
->fileType
= type
;
2615 finfo
->fileCreator
= creator
;
2616 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
2623 bool wxFileName::MacGetTypeAndCreator( wxUint32
*type
, wxUint32
*creator
) const
2626 FSCatalogInfo catInfo
;
2629 if ( wxMacPathToFSRef( GetFullPath() , &fsRef
) == noErr
)
2631 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
2633 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
2634 *type
= finfo
->fileType
;
2635 *creator
= finfo
->fileCreator
;
2642 bool wxFileName::MacSetDefaultTypeAndCreator()
2644 wxUint32 type
, creator
;
2645 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type
,
2648 return MacSetTypeAndCreator( type
, creator
) ;
2653 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString
& ext
, wxUint32
*type
, wxUint32
*creator
)
2655 MacEnsureDefaultExtensionsLoaded() ;
2656 wxString extl
= ext
.Lower() ;
2657 for( int i
= gMacDefaultExtensions
.Count() - 1 ; i
>= 0 ; --i
)
2659 if ( gMacDefaultExtensions
.Item(i
).m_ext
== extl
)
2661 *type
= gMacDefaultExtensions
.Item(i
).m_type
;
2662 *creator
= gMacDefaultExtensions
.Item(i
).m_creator
;
2669 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString
& ext
, wxUint32 type
, wxUint32 creator
)
2671 MacEnsureDefaultExtensionsLoaded();
2672 MacDefaultExtensionRecord
rec(ext
.Lower(), type
, creator
);
2673 gMacDefaultExtensions
.Add( rec
);
2676 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON