]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
Committing in .
[wxWidgets.git] / src / common / filename.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filename.cpp
3 // Purpose: wxFileName - encapsulates a file path
4 // Author: Robert Roebling, Vadim Zeitlin
5 // Modified by:
6 // Created: 28.12.2000
7 // RCS-ID: $Id$
8 // Copyright: (c) 2000 Robert Roebling
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "filename.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/intl.h"
33 #include "wx/log.h"
34 #endif
35
36 #include "wx/filename.h"
37 #include "wx/tokenzr.h"
38 #include "wx/config.h" // for wxExpandEnvVars
39 #include "wx/utils.h"
40
41 #if wxUSE_DYNLIB_CLASS
42 #include "wx/dynlib.h"
43 #endif
44
45 // For GetShort/LongPathName
46 #ifdef __WIN32__
47 #include <windows.h>
48
49 #include "wx/msw/winundef.h"
50 #endif
51
52 // utime() is POSIX so should normally be available on all Unices
53 #ifdef __UNIX_LIKE__
54 #include <sys/types.h>
55 #include <utime.h>
56 #include <sys/stat.h>
57 #include <unistd.h>
58 #endif
59
60 // ----------------------------------------------------------------------------
61 // private classes
62 // ----------------------------------------------------------------------------
63
64 // small helper class which opens and closes the file - we use it just to get
65 // a file handle for the given file name to pass it to some Win32 API function
66 #ifdef __WIN32__
67
68 class wxFileHandle
69 {
70 public:
71 wxFileHandle(const wxString& filename)
72 {
73 m_hFile = ::CreateFile
74 (
75 filename, // name
76 GENERIC_READ, // access mask
77 0, // no sharing
78 NULL, // no secutity attr
79 OPEN_EXISTING, // creation disposition
80 0, // no flags
81 NULL // no template file
82 );
83
84 if ( m_hFile == INVALID_HANDLE_VALUE )
85 {
86 wxLogSysError(_("Failed to open '%s' for reading"),
87 filename.c_str());
88 }
89 }
90
91 ~wxFileHandle()
92 {
93 if ( m_hFile != INVALID_HANDLE_VALUE )
94 {
95 if ( !::CloseHandle(m_hFile) )
96 {
97 wxLogSysError(_("Failed to close file handle"));
98 }
99 }
100 }
101
102 // return TRUE only if the file could be opened successfully
103 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
104
105 // get the handle
106 operator HANDLE() const { return m_hFile; }
107
108 private:
109 HANDLE m_hFile;
110 };
111
112 #endif // __WIN32__
113
114 // ----------------------------------------------------------------------------
115 // private functions
116 // ----------------------------------------------------------------------------
117
118 #ifdef __WIN32__
119
120 // convert between wxDateTime and FILETIME which is a 64-bit value representing
121 // the number of 100-nanosecond intervals since January 1, 1601.
122
123 // the number of milliseconds between the Unix Epoch (January 1, 1970) and the
124 // FILETIME reference point (January 1, 1601)
125 static const wxLongLong FILETIME_EPOCH_OFFSET = wxLongLong(0xa97, 0x30b66800);
126
127 static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
128 {
129 wxLongLong ll(ft.dwHighDateTime, ft.dwLowDateTime);
130
131 // convert 100ns to ms
132 ll /= 10000;
133
134 // move it to our Epoch
135 ll -= FILETIME_EPOCH_OFFSET;
136
137 *dt = wxDateTime(ll);
138 }
139
140 static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
141 {
142 // do the reverse of ConvertFileTimeToWx()
143 wxLongLong ll = dt.GetValue();
144 ll *= 10000;
145 ll += FILETIME_EPOCH_OFFSET;
146
147 ft->dwHighDateTime = ll.GetHi();
148 ft->dwLowDateTime = ll.GetLo();
149 }
150
151 #endif // __WIN32__
152
153 // ============================================================================
154 // implementation
155 // ============================================================================
156
157 // ----------------------------------------------------------------------------
158 // wxFileName construction
159 // ----------------------------------------------------------------------------
160
161 void wxFileName::Assign( const wxFileName &filepath )
162 {
163 m_ext = filepath.GetExt();
164 m_name = filepath.GetName();
165 m_dirs = filepath.GetDirs();
166 }
167
168 void wxFileName::Assign( const wxString& path,
169 const wxString& name,
170 const wxString& ext,
171 wxPathFormat format )
172 {
173 wxStringTokenizer tn(path, GetPathSeparators(format),
174 wxTOKEN_RET_EMPTY_ALL);
175 int i = 0;
176 m_dirs.Clear();
177 while ( tn.HasMoreTokens() )
178 {
179 wxString token = tn.GetNextToken();
180
181 // If the path starts with a slash (or two for a network path),
182 // we need the first dir entry to be an empty for later reassembly.
183 if ((i < 2) || !token.IsEmpty())
184 m_dirs.Add( token );
185
186 i ++;
187 }
188
189 m_ext = ext;
190 m_name = name;
191 }
192
193 void wxFileName::Assign(const wxString& fullpath,
194 wxPathFormat format)
195 {
196 wxString path, name, ext;
197 SplitPath(fullpath, &path, &name, &ext, format);
198
199 Assign(path, name, ext, format);
200 }
201
202 void wxFileName::Assign(const wxString& path,
203 const wxString& fullname,
204 wxPathFormat format)
205 {
206 wxString name, ext;
207 SplitPath(fullname, NULL /* no path */, &name, &ext, format);
208
209 Assign(path, name, ext, format);
210 }
211
212 void wxFileName::Clear()
213 {
214 m_dirs.Clear();
215 m_name =
216 m_ext = wxEmptyString;
217 }
218
219 /* static */
220 wxFileName wxFileName::FileName(const wxString& file)
221 {
222 return wxFileName(file);
223 }
224
225 /* static */
226 wxFileName wxFileName::DirName(const wxString& dir)
227 {
228 wxFileName fn;
229 fn.AssignDir(dir);
230 return fn;
231 }
232
233 // ----------------------------------------------------------------------------
234 // existence tests
235 // ----------------------------------------------------------------------------
236
237 bool wxFileName::FileExists()
238 {
239 return wxFileName::FileExists( GetFullPath() );
240 }
241
242 bool wxFileName::FileExists( const wxString &file )
243 {
244 return ::wxFileExists( file );
245 }
246
247 bool wxFileName::DirExists()
248 {
249 return wxFileName::DirExists( GetFullPath() );
250 }
251
252 bool wxFileName::DirExists( const wxString &dir )
253 {
254 return ::wxDirExists( dir );
255 }
256
257 // ----------------------------------------------------------------------------
258 // CWD and HOME stuff
259 // ----------------------------------------------------------------------------
260
261 void wxFileName::AssignCwd()
262 {
263 AssignDir(wxFileName::GetCwd());
264 }
265
266 /* static */
267 wxString wxFileName::GetCwd()
268 {
269 return ::wxGetCwd();
270 }
271
272 bool wxFileName::SetCwd()
273 {
274 return wxFileName::SetCwd( GetFullPath() );
275 }
276
277 bool wxFileName::SetCwd( const wxString &cwd )
278 {
279 return ::wxSetWorkingDirectory( cwd );
280 }
281
282 void wxFileName::AssignHomeDir()
283 {
284 AssignDir(wxFileName::GetHomeDir());
285 }
286
287 wxString wxFileName::GetHomeDir()
288 {
289 return ::wxGetHomeDir();
290 }
291
292 void wxFileName::AssignTempFileName( const wxString &prefix )
293 {
294 wxString fullname;
295 if ( wxGetTempFileName(prefix, fullname) )
296 {
297 Assign(fullname);
298 }
299 else // error
300 {
301 Clear();
302 }
303 }
304
305 // ----------------------------------------------------------------------------
306 // directory operations
307 // ----------------------------------------------------------------------------
308
309 bool wxFileName::Mkdir( int perm, bool full )
310 {
311 return wxFileName::Mkdir( GetFullPath(), perm, full );
312 }
313
314 bool wxFileName::Mkdir( const wxString &dir, int perm, bool full )
315 {
316 if (full)
317 {
318 wxFileName filename(dir);
319 wxArrayString dirs = filename.GetDirs();
320 dirs.Add(filename.GetName());
321
322 size_t count = dirs.GetCount();
323 size_t i;
324 wxString currPath;
325 int noErrors = 0;
326 for ( i = 0; i < count; i++ )
327 {
328 currPath += dirs[i];
329
330 if (currPath.Last() == wxT(':'))
331 {
332 // Can't create a root directory so continue to next dir
333 currPath += wxFILE_SEP_PATH;
334 continue;
335 }
336
337 if (!DirExists(currPath))
338 if (!wxMkdir(currPath, perm))
339 noErrors ++;
340
341 if ( (i < (count-1)) )
342 currPath += wxFILE_SEP_PATH;
343 }
344
345 return (noErrors == 0);
346
347 }
348 else
349 return ::wxMkdir( dir, perm );
350 }
351
352 bool wxFileName::Rmdir()
353 {
354 return wxFileName::Rmdir( GetFullPath() );
355 }
356
357 bool wxFileName::Rmdir( const wxString &dir )
358 {
359 return ::wxRmdir( dir );
360 }
361
362 // ----------------------------------------------------------------------------
363 // path normalization
364 // ----------------------------------------------------------------------------
365
366 bool wxFileName::Normalize(wxPathNormalize flags,
367 const wxString& cwd,
368 wxPathFormat format)
369 {
370 // the existing path components
371 wxArrayString dirs = GetDirs();
372
373 // the path to prepend in front to make the path absolute
374 wxFileName curDir;
375
376 format = GetFormat(format);
377
378 // make the path absolute
379 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute() )
380 {
381 if ( cwd.empty() )
382 curDir.AssignCwd();
383 else
384 curDir.AssignDir(cwd);
385 }
386
387 // handle ~ stuff under Unix only
388 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
389 {
390 if ( !dirs.IsEmpty() )
391 {
392 wxString dir = dirs[0u];
393 if ( !dir.empty() && dir[0u] == _T('~') )
394 {
395 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
396
397 dirs.RemoveAt(0u);
398 }
399 }
400 }
401
402 if ( curDir.IsOk() )
403 {
404 wxArrayString dirsNew = curDir.GetDirs();
405 size_t count = dirs.GetCount();
406 for ( size_t n = 0; n < count; n++ )
407 {
408 dirsNew.Add(dirs[n]);
409 }
410
411 dirs = dirsNew;
412 }
413
414 // now deal with ".", ".." and the rest
415 m_dirs.Empty();
416 size_t count = dirs.GetCount();
417 for ( size_t n = 0; n < count; n++ )
418 {
419 wxString dir = dirs[n];
420
421 if ( flags && wxPATH_NORM_DOTS )
422 {
423 if ( dir == wxT(".") )
424 {
425 // just ignore
426 continue;
427 }
428
429 if ( dir == wxT("..") )
430 {
431 if ( m_dirs.IsEmpty() )
432 {
433 wxLogError(_("The path '%s' contains too many \"..\"!"),
434 GetFullPath().c_str());
435 return FALSE;
436 }
437
438 m_dirs.Remove(m_dirs.GetCount() - 1);
439 continue;
440 }
441 }
442
443 if ( flags & wxPATH_NORM_ENV_VARS )
444 {
445 dir = wxExpandEnvVars(dir);
446 }
447
448 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
449 {
450 dir.MakeLower();
451 }
452
453 m_dirs.Add(dir);
454 }
455
456 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
457 {
458 // VZ: expand env vars here too?
459
460 m_name.MakeLower();
461 m_ext.MakeLower();
462 }
463
464 #if defined(__WXMSW__) && defined(__WIN32__)
465 if (flags & wxPATH_NORM_LONG)
466 {
467 Assign(GetLongPath());
468 }
469 #endif
470
471 return TRUE;
472 }
473
474 // ----------------------------------------------------------------------------
475 // filename kind tests
476 // ----------------------------------------------------------------------------
477
478 bool wxFileName::SameAs( const wxFileName &filepath, wxPathFormat format)
479 {
480 wxFileName fn1 = *this,
481 fn2 = filepath;
482
483 // get cwd only once - small time saving
484 wxString cwd = wxGetCwd();
485 fn1.Normalize(wxPATH_NORM_ALL, cwd, format);
486 fn2.Normalize(wxPATH_NORM_ALL, cwd, format);
487
488 if ( fn1.GetFullPath() == fn2.GetFullPath() )
489 return TRUE;
490
491 // TODO: compare inodes for Unix, this works even when filenames are
492 // different but files are the same (symlinks) (VZ)
493
494 return FALSE;
495 }
496
497 /* static */
498 bool wxFileName::IsCaseSensitive( wxPathFormat format )
499 {
500 // only DOS and OpenVMS filenames are case-sensitive
501 return ( GetFormat(format) != wxPATH_DOS &
502 GetFormat(format) != wxPATH_VMS );
503 }
504
505 bool wxFileName::IsRelative( wxPathFormat format )
506 {
507 return !IsAbsolute(format);
508 }
509
510 bool wxFileName::IsAbsolute( wxPathFormat format )
511 {
512 wxChar ch = m_dirs.IsEmpty() ? _T('\0') : m_dirs[0u][0u];
513
514 // Hack to cope with e.g. c:\thing - need something better
515 wxChar driveSep = _T('\0');
516 if (!m_dirs.IsEmpty() && m_dirs[0].Length() > 1)
517 driveSep = m_dirs[0u][1u];
518
519 // the path is absolute if it starts with a path separator or, only for
520 // Unix filenames, with "~" or "~user"
521 return IsPathSeparator(ch, format) ||
522 driveSep == _T(':') ||
523 (GetFormat(format) == wxPATH_UNIX && ch == _T('~') );
524 }
525
526 /* static */
527 wxString wxFileName::GetPathSeparators(wxPathFormat format)
528 {
529 wxString seps;
530 switch ( GetFormat(format) )
531 {
532 case wxPATH_DOS:
533 // accept both as native APIs do
534 seps << wxFILE_SEP_PATH_UNIX << wxFILE_SEP_PATH_DOS;
535 break;
536
537 default:
538 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
539 // fall through
540
541 case wxPATH_UNIX:
542 seps = wxFILE_SEP_PATH_UNIX;
543 break;
544
545 case wxPATH_MAC:
546 seps = wxFILE_SEP_PATH_MAC;
547 break;
548
549 case wxPATH_VMS:
550 seps = wxFILE_SEP_PATH_VMS;
551 break;
552 }
553
554 return seps;
555 }
556
557 /* static */
558 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
559 {
560 return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
561 }
562
563 bool wxFileName::IsWild( wxPathFormat format )
564 {
565 // FIXME: this is probably false for Mac and this is surely wrong for most
566 // of Unix shells (think about "[...]")
567 (void)format;
568 return m_name.find_first_of(_T("*?")) != wxString::npos;
569 }
570
571 // ----------------------------------------------------------------------------
572 // path components manipulation
573 // ----------------------------------------------------------------------------
574
575 void wxFileName::AppendDir( const wxString &dir )
576 {
577 m_dirs.Add( dir );
578 }
579
580 void wxFileName::PrependDir( const wxString &dir )
581 {
582 m_dirs.Insert( dir, 0 );
583 }
584
585 void wxFileName::InsertDir( int before, const wxString &dir )
586 {
587 m_dirs.Insert( dir, before );
588 }
589
590 void wxFileName::RemoveDir( int pos )
591 {
592 m_dirs.Remove( (size_t)pos );
593 }
594
595 // ----------------------------------------------------------------------------
596 // accessors
597 // ----------------------------------------------------------------------------
598
599 void wxFileName::SetFullName(const wxString& fullname)
600 {
601 SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
602 }
603
604 wxString wxFileName::GetFullName() const
605 {
606 wxString fullname = m_name;
607 if ( !m_ext.empty() )
608 {
609 fullname << wxFILE_SEP_EXT << m_ext;
610 }
611
612 return fullname;
613 }
614
615 wxString wxFileName::GetPath( bool add_separator, wxPathFormat format ) const
616 {
617 format = GetFormat( format );
618
619 wxString ret;
620 size_t count = m_dirs.GetCount();
621 for ( size_t i = 0; i < count; i++ )
622 {
623 ret += m_dirs[i];
624 if ( add_separator || (i < count) )
625 ret += wxFILE_SEP_PATH;
626 }
627
628 return ret;
629 }
630
631 wxString wxFileName::GetFullPath( wxPathFormat format ) const
632 {
633 format = GetFormat( format );
634
635 wxString ret;
636 if (format == wxPATH_DOS)
637 {
638 for (size_t i = 0; i < m_dirs.GetCount(); i++)
639 {
640 ret += m_dirs[i];
641 ret += '\\';
642 }
643 }
644 else
645 if (format == wxPATH_UNIX)
646 {
647 for (size_t i = 0; i < m_dirs.GetCount(); i++)
648 {
649 ret += m_dirs[i];
650 ret += '/';
651 }
652 }
653 else
654 if (format == wxPATH_VMS)
655 {
656 ret += '[';
657 for (size_t i = 0; i < m_dirs.GetCount(); i++)
658 {
659 ret += '.';
660 ret += m_dirs[i];
661 }
662 ret += ']';
663 }
664 else
665 {
666 for (size_t i = 0; i < m_dirs.GetCount(); i++)
667 {
668 ret += m_dirs[i];
669 ret += ':';
670 }
671 }
672
673 ret += m_name;
674
675 if (!m_ext.IsEmpty())
676 {
677 ret += '.';
678 ret += m_ext;
679 }
680
681 return ret;
682 }
683
684 // Return the short form of the path (returns identity on non-Windows platforms)
685 wxString wxFileName::GetShortPath() const
686 {
687 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
688 wxString path(GetFullPath());
689 wxString pathOut;
690 DWORD sz = ::GetShortPathName(path, NULL, 0);
691 bool ok = sz != 0;
692 if ( ok )
693 {
694 ok = ::GetShortPathName
695 (
696 path,
697 pathOut.GetWriteBuf(sz),
698 sz
699 ) != 0;
700 pathOut.UngetWriteBuf();
701 }
702 if (ok)
703 return pathOut;
704
705 return path;
706 #else
707 return GetFullPath();
708 #endif
709 }
710
711 // Return the long form of the path (returns identity on non-Windows platforms)
712 wxString wxFileName::GetLongPath() const
713 {
714 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
715 wxString path(GetFullPath());
716 wxString pathOut;
717 bool success = FALSE;
718
719 // VZ: this code was disabled, why?
720 #if 0 // wxUSE_DYNLIB_CLASS
721 typedef DWORD (*GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
722
723 static bool s_triedToLoad = FALSE;
724
725 if ( !s_triedToLoad )
726 {
727 s_triedToLoad = TRUE;
728 wxDllType dllKernel = wxDllLoader::LoadLibrary(_T("kernel32"));
729 if ( dllKernel )
730 {
731 // may succeed or fail depending on the Windows version
732 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
733 #ifdef _UNICODE
734 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) wxDllLoader::GetSymbol(dllKernel, _T("GetLongPathNameW"));
735 #else
736 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) wxDllLoader::GetSymbol(dllKernel, _T("GetLongPathNameA"));
737 #endif
738
739 wxDllLoader::UnloadLibrary(dllKernel);
740
741 if ( s_pfnGetLongPathName )
742 {
743 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
744 bool ok = dwSize > 0;
745
746 if ( ok )
747 {
748 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
749 ok = sz != 0;
750 if ( ok )
751 {
752 ok = (*s_pfnGetLongPathName)
753 (
754 path,
755 pathOut.GetWriteBuf(sz),
756 sz
757 ) != 0;
758 pathOut.UngetWriteBuf();
759
760 success = TRUE;
761 }
762 }
763 }
764 }
765 }
766 if (success)
767 return pathOut;
768 #endif // wxUSE_DYNLIB_CLASS
769
770 if (!success)
771 {
772 // The OS didn't support GetLongPathName, or some other error.
773 // We need to call FindFirstFile on each component in turn.
774
775 WIN32_FIND_DATA findFileData;
776 HANDLE hFind;
777 pathOut = wxEmptyString;
778
779 wxArrayString dirs = GetDirs();
780 dirs.Add(GetFullName());
781
782 size_t count = dirs.GetCount();
783 size_t i;
784 wxString tmpPath;
785
786 for ( i = 0; i < count; i++ )
787 {
788 // We're using pathOut to collect the long-name path,
789 // but using a temporary for appending the last path component which may be short-name
790 tmpPath = pathOut + dirs[i];
791
792 if (tmpPath.Last() == wxT(':'))
793 {
794 // Can't pass a drive and root dir to FindFirstFile,
795 // so continue to next dir
796 tmpPath += wxFILE_SEP_PATH;
797 pathOut = tmpPath;
798 continue;
799 }
800
801 hFind = ::FindFirstFile(tmpPath, &findFileData);
802 if (hFind == INVALID_HANDLE_VALUE)
803 {
804 // Error: return immediately with the original path
805 return path;
806 }
807 else
808 {
809 pathOut += findFileData.cFileName;
810 if ( (i < (count-1)) )
811 pathOut += wxFILE_SEP_PATH;
812
813 ::FindClose(hFind);
814 }
815 }
816 }
817
818 return pathOut;
819 #else
820 return GetFullPath();
821 #endif
822 }
823
824 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
825 {
826 if (format == wxPATH_NATIVE)
827 {
828 #if defined(__WXMSW__) || defined(__WXPM__)
829 format = wxPATH_DOS;
830 #elif defined(__WXMAC__) && !defined(__DARWIN__)
831 format = wxPATH_MAC;
832 #elif defined(__VMS)
833 format = wxPATH_VMS;
834 #else
835 format = wxPATH_UNIX;
836 #endif
837 }
838 return format;
839 }
840
841 // ----------------------------------------------------------------------------
842 // path splitting function
843 // ----------------------------------------------------------------------------
844
845 void wxFileName::SplitPath(const wxString& fullpath,
846 wxString *pstrPath,
847 wxString *pstrName,
848 wxString *pstrExt,
849 wxPathFormat format)
850 {
851 format = GetFormat(format);
852
853 // find the positions of the last dot and last path separator in the path
854 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
855 size_t posLastSlash = fullpath.find_last_of(GetPathSeparators(format));
856
857 if ( (posLastDot != wxString::npos) && (format == wxPATH_UNIX) )
858 {
859 if ( (posLastDot == 0) ||
860 (fullpath[posLastDot - 1] == wxFILE_SEP_PATH_UNIX) )
861 {
862 // under Unix, dot may be (and commonly is) the first character of
863 // the filename, don't treat the entire filename as extension in
864 // this case
865 posLastDot = wxString::npos;
866 }
867 }
868 else
869 if ( (posLastDot != wxString::npos) && (format == wxPATH_VMS) )
870 {
871 if ( (posLastDot == 0) ||
872 (fullpath[posLastDot - 1] == ']' ) )
873 {
874 // under OpenVMS, dot may be (and commonly is) the first character of
875 // the filename, don't treat the entire filename as extension in
876 // this case
877 posLastDot = wxString::npos;
878 }
879 }
880
881 // if we do have a dot and a slash, check that the dot is in the name part
882 if ( (posLastDot != wxString::npos) &&
883 (posLastSlash != wxString::npos) &&
884 (posLastDot < posLastSlash) )
885 {
886 // the dot is part of the path, not the start of the extension
887 posLastDot = wxString::npos;
888 }
889
890 // now fill in the variables provided by user
891 if ( pstrPath )
892 {
893 if ( posLastSlash == wxString::npos )
894 {
895 // no path at all
896 pstrPath->Empty();
897 }
898 else
899 {
900 // take all until the separator
901 *pstrPath = fullpath.Left(posLastSlash);
902 }
903 }
904
905 if ( pstrName )
906 {
907 // take all characters starting from the one after the last slash and
908 // up to, but excluding, the last dot
909 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
910 size_t count;
911 if ( posLastDot == wxString::npos )
912 {
913 // take all until the end
914 count = wxString::npos;
915 }
916 else if ( posLastSlash == wxString::npos )
917 {
918 count = posLastDot;
919 }
920 else // have both dot and slash
921 {
922 count = posLastDot - posLastSlash - 1;
923 }
924
925 *pstrName = fullpath.Mid(nStart, count);
926 }
927
928 if ( pstrExt )
929 {
930 if ( posLastDot == wxString::npos )
931 {
932 // no extension
933 pstrExt->Empty();
934 }
935 else
936 {
937 // take everything after the dot
938 *pstrExt = fullpath.Mid(posLastDot + 1);
939 }
940 }
941 }
942
943 // ----------------------------------------------------------------------------
944 // time functions
945 // ----------------------------------------------------------------------------
946
947 bool wxFileName::SetTimes(const wxDateTime *dtCreate,
948 const wxDateTime *dtAccess,
949 const wxDateTime *dtMod)
950 {
951 #if defined(__UNIX_LIKE__)
952 if ( !dtAccess && !dtMod )
953 {
954 // can't modify the creation time anyhow, don't try
955 return TRUE;
956 }
957
958 // if dtAccess or dtMod is not specified, use the other one (which must be
959 // non NULL because of the test above) for both times
960 utimbuf utm;
961 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
962 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
963 if ( utime(GetFullPath(), &utm) == 0 )
964 {
965 return TRUE;
966 }
967 #elif defined(__WIN32__)
968 wxFileHandle fh(GetFullPath());
969 if ( fh.IsOk() )
970 {
971 FILETIME ftAccess, ftCreate, ftWrite;
972
973 if ( dtCreate )
974 ConvertWxToFileTime(&ftCreate, *dtCreate);
975 if ( dtAccess )
976 ConvertWxToFileTime(&ftAccess, *dtAccess);
977 if ( dtMod )
978 ConvertWxToFileTime(&ftWrite, *dtMod);
979
980 if ( ::SetFileTime(fh,
981 dtCreate ? &ftCreate : NULL,
982 dtAccess ? &ftAccess : NULL,
983 dtMod ? &ftWrite : NULL) )
984 {
985 return TRUE;
986 }
987 }
988 #else // other platform
989 #endif // platforms
990
991 wxLogSysError(_("Failed to modify file times for '%s'"),
992 GetFullPath().c_str());
993
994 return FALSE;
995 }
996
997 bool wxFileName::Touch()
998 {
999 #if defined(__UNIX_LIKE__)
1000 // under Unix touching file is simple: just pass NULL to utime()
1001 if ( utime(GetFullPath(), NULL) == 0 )
1002 {
1003 return TRUE;
1004 }
1005
1006 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1007
1008 return FALSE;
1009 #else // other platform
1010 wxDateTime dtNow = wxDateTime::Now();
1011
1012 return SetTimes(NULL /* don't change create time */, &dtNow, &dtNow);
1013 #endif // platforms
1014 }
1015
1016 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1017 wxDateTime *dtMod,
1018 wxDateTime *dtChange) const
1019 {
1020 #if defined(__UNIX_LIKE__)
1021 wxStructStat stBuf;
1022 if ( wxStat(GetFullPath(), &stBuf) == 0 )
1023 {
1024 if ( dtAccess )
1025 dtAccess->Set(stBuf.st_atime);
1026 if ( dtMod )
1027 dtMod->Set(stBuf.st_mtime);
1028 if ( dtChange )
1029 dtChange->Set(stBuf.st_ctime);
1030
1031 return TRUE;
1032 }
1033 #elif defined(__WIN32__)
1034 wxFileHandle fh(GetFullPath());
1035 if ( fh.IsOk() )
1036 {
1037 FILETIME ftAccess, ftCreate, ftWrite;
1038
1039 if ( ::GetFileTime(fh,
1040 dtMod ? &ftCreate : NULL,
1041 dtAccess ? &ftAccess : NULL,
1042 dtChange ? &ftWrite : NULL) )
1043 {
1044 if ( dtMod )
1045 ConvertFileTimeToWx(dtMod, ftCreate);
1046 if ( dtAccess )
1047 ConvertFileTimeToWx(dtAccess, ftAccess);
1048 if ( dtChange )
1049 ConvertFileTimeToWx(dtChange, ftWrite);
1050
1051 return TRUE;
1052 }
1053 }
1054 #else // other platform
1055 #endif // platforms
1056
1057 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1058 GetFullPath().c_str());
1059
1060 return FALSE;
1061 }
1062