1 // Copyright (C) 2002-2012 Nikolaus Gebhardt
\r
2 // This file is part of the "Irrlicht Engine".
\r
3 // For conditions of distribution and use, see copyright notice in irrlicht.h
\r
6 #include "CFileSystem.h"
\r
7 #include "IReadFile.h"
\r
8 #include "IWriteFile.h"
\r
9 #include "CZipReader.h"
\r
10 #include "CFileList.h"
\r
13 #include "CReadFile.h"
\r
14 #include "CMemoryFile.h"
\r
15 #include "CLimitReadFile.h"
\r
16 #include "CWriteFile.h"
\r
19 #if defined (__STRICT_ANSI__)
\r
20 #error Compiling with __STRICT_ANSI__ not supported. g++ does set this when compiling with -std=c++11 or -std=c++0x. Use instead -std=gnu++11 or -std=gnu++0x. Or use -U__STRICT_ANSI__ to disable strict ansi.
\r
23 #if defined (_IRR_WINDOWS_API_)
\r
24 #include <direct.h> // for _chdir
\r
25 #include <io.h> // for _access
\r
27 #elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_) || defined(_IRR_ANDROID_PLATFORM_))
\r
32 #include <sys/types.h>
\r
34 #include <sys/stat.h>
\r
36 #elif defined(_IRR_EMSCRIPTEN_PLATFORM_)
\r
46 CFileSystem::CFileSystem()
\r
49 setDebugName("CFileSystem");
\r
52 setFileListSystem(FILESYSTEM_NATIVE);
\r
53 //! reset current working directory
\r
54 getWorkingDirectory();
\r
56 ArchiveLoader.push_back(new CArchiveLoaderZIP(this));
\r
62 CFileSystem::~CFileSystem()
\r
66 for ( i=0; i < FileArchives.size(); ++i)
\r
68 FileArchives[i]->drop();
\r
71 for ( i=0; i < ArchiveLoader.size(); ++i)
\r
73 ArchiveLoader[i]->drop();
\r
78 //! opens a file for read access
\r
79 IReadFile* CFileSystem::createAndOpenFile(const io::path& filename)
\r
81 if ( filename.empty() )
\r
84 IReadFile* file = 0;
\r
87 for (i=0; i< FileArchives.size(); ++i)
\r
89 file = FileArchives[i]->createAndOpenFile(filename);
\r
94 // Create the file using an absolute path so that it matches
\r
95 // the scheme used by CNullDriver::getTexture().
\r
96 return CReadFile::createReadFile(getAbsolutePath(filename));
\r
100 //! Creates an IReadFile interface for treating memory like a file.
\r
101 IReadFile* CFileSystem::createMemoryReadFile(const void* memory, s32 len,
\r
102 const io::path& fileName, bool deleteMemoryWhenDropped)
\r
107 return new CMemoryReadFile(memory, len, fileName, deleteMemoryWhenDropped);
\r
111 //! Creates an IReadFile interface for reading files inside files
\r
112 IReadFile* CFileSystem::createLimitReadFile(const io::path& fileName,
\r
113 IReadFile* alreadyOpenedFile, long pos, long areaSize)
\r
115 if (!alreadyOpenedFile)
\r
118 return new CLimitReadFile(alreadyOpenedFile, pos, areaSize, fileName);
\r
122 //! Creates an IReadFile interface for treating memory like a file.
\r
123 IWriteFile* CFileSystem::createMemoryWriteFile(void* memory, s32 len,
\r
124 const io::path& fileName, bool deleteMemoryWhenDropped)
\r
129 return new CMemoryWriteFile(memory, len, fileName, deleteMemoryWhenDropped);
\r
133 //! Opens a file for write access.
\r
134 IWriteFile* CFileSystem::createAndWriteFile(const io::path& filename, bool append)
\r
136 return CWriteFile::createWriteFile(filename, append);
\r
140 //! Adds an external archive loader to the engine.
\r
141 void CFileSystem::addArchiveLoader(IArchiveLoader* loader)
\r
147 ArchiveLoader.push_back(loader);
\r
150 //! Returns the total number of archive loaders added.
\r
151 u32 CFileSystem::getArchiveLoaderCount() const
\r
153 return ArchiveLoader.size();
\r
156 //! Gets the archive loader by index.
\r
157 IArchiveLoader* CFileSystem::getArchiveLoader(u32 index) const
\r
159 if (index < ArchiveLoader.size())
\r
160 return ArchiveLoader[index];
\r
165 //! move the hirarchy of the filesystem. moves sourceIndex relative up or down
\r
166 bool CFileSystem::moveFileArchive(u32 sourceIndex, s32 relative)
\r
169 const s32 dest = (s32) sourceIndex + relative;
\r
170 const s32 dir = relative < 0 ? -1 : 1;
\r
171 const s32 sourceEnd = ((s32) FileArchives.size() ) - 1;
\r
174 for (s32 s = (s32) sourceIndex;s != dest; s += dir)
\r
176 if (s < 0 || s > sourceEnd || s + dir < 0 || s + dir > sourceEnd)
\r
179 t = FileArchives[s + dir];
\r
180 FileArchives[s + dir] = FileArchives[s];
\r
181 FileArchives[s] = t;
\r
188 //! Adds an archive to the file system.
\r
189 bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase,
\r
190 bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
\r
191 const core::stringc& password,
\r
192 IFileArchive** retArchive)
\r
194 IFileArchive* archive = 0;
\r
197 // see if archive is already added
\r
201 // do we know what type it should be?
\r
202 if (archiveType == EFAT_UNKNOWN || archiveType == EFAT_FOLDER)
\r
204 // try to load archive based on file name
\r
205 for (i = ArchiveLoader.size()-1; i >=0 ; --i)
\r
207 if (ArchiveLoader[i]->isALoadableFileFormat(filename))
\r
209 archive = ArchiveLoader[i]->createArchive(filename, ignoreCase, ignorePaths);
\r
215 // try to load archive based on content
\r
218 io::IReadFile* file = createAndOpenFile(filename);
\r
221 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
224 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
227 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
238 // try to open archive based on archive loader type
\r
240 io::IReadFile* file = 0;
\r
242 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
244 if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
\r
246 // attempt to open file
\r
248 file = createAndOpenFile(filename);
\r
250 // is the file open?
\r
253 // attempt to open archive
\r
255 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
258 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
265 // couldn't open file
\r
271 // if open, close the file
\r
278 FileArchives.push_back(archive);
\r
279 if (password.size())
\r
280 archive->Password=password;
\r
282 *retArchive = archive;
\r
287 os::Printer::log("Could not create archive for", filename, ELL_ERROR);
\r
294 bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase,
\r
295 bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
\r
296 const core::stringc& password, IFileArchive** retArchive)
\r
298 if (!file || archiveType == EFAT_FOLDER)
\r
303 IFileArchive* archive = 0;
\r
306 if (archiveType == EFAT_UNKNOWN)
\r
308 // try to load archive based on file name
\r
309 for (i = ArchiveLoader.size()-1; i >=0 ; --i)
\r
311 if (ArchiveLoader[i]->isALoadableFileFormat(file->getFileName()))
\r
313 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
319 // try to load archive based on content
\r
322 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
325 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
328 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
337 // try to open archive based on archive loader type
\r
338 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
340 if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
\r
342 // attempt to open archive
\r
344 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
347 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
357 FileArchives.push_back(archive);
\r
358 if (password.size())
\r
359 archive->Password=password;
\r
361 *retArchive = archive;
\r
366 os::Printer::log("Could not create archive for", file->getFileName(), ELL_ERROR);
\r
374 //! Adds an archive to the file system.
\r
375 bool CFileSystem::addFileArchive(IFileArchive* archive)
\r
379 for (u32 i=0; i < FileArchives.size(); ++i)
\r
381 if (archive == FileArchives[i])
\r
386 FileArchives.push_back(archive);
\r
396 //! removes an archive from the file system.
\r
397 bool CFileSystem::removeFileArchive(u32 index)
\r
400 if (index < FileArchives.size())
\r
402 FileArchives[index]->drop();
\r
403 FileArchives.erase(index);
\r
410 //! removes an archive from the file system.
\r
411 bool CFileSystem::removeFileArchive(const io::path& filename)
\r
413 const path absPath = getAbsolutePath(filename);
\r
414 for (u32 i=0; i < FileArchives.size(); ++i)
\r
416 if (absPath == FileArchives[i]->getFileList()->getPath())
\r
417 return removeFileArchive(i);
\r
423 //! Removes an archive from the file system.
\r
424 bool CFileSystem::removeFileArchive(const IFileArchive* archive)
\r
426 for (u32 i=0; i < FileArchives.size(); ++i)
\r
428 if (archive == FileArchives[i])
\r
430 return removeFileArchive(i);
\r
437 //! gets an archive
\r
438 u32 CFileSystem::getFileArchiveCount() const
\r
440 return FileArchives.size();
\r
444 IFileArchive* CFileSystem::getFileArchive(u32 index)
\r
446 return index < getFileArchiveCount() ? FileArchives[index] : 0;
\r
450 //! Returns the string of the current working directory
\r
451 const io::path& CFileSystem::getWorkingDirectory()
\r
453 EFileSystemType type = FileSystemType;
\r
455 if (type != FILESYSTEM_NATIVE)
\r
457 type = FILESYSTEM_VIRTUAL;
\r
461 #if defined(_IRR_WINDOWS_API_)
\r
462 fschar_t tmp[_MAX_PATH];
\r
463 _getcwd(tmp, _MAX_PATH);
\r
464 WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
\r
465 WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/');
\r
468 #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
470 // getting the CWD is rather complex as we do not know the size
\r
471 // so try it until the call was successful
\r
472 // Note that neither the first nor the second parameter may be 0 according to POSIX
\r
475 char *tmpPath = new char[pathSize];
\r
476 while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize)))
\r
480 tmpPath = new char[pathSize];
\r
484 WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
\r
489 WorkingDirectory[type].validate();
\r
492 return WorkingDirectory[type];
\r
496 //! Changes the current Working Directory to the given string.
\r
497 bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory)
\r
499 bool success=false;
\r
501 if (FileSystemType != FILESYSTEM_NATIVE)
\r
503 WorkingDirectory[FILESYSTEM_VIRTUAL] = newDirectory;
\r
504 // is this empty string constant really intended?
\r
505 flattenFilename(WorkingDirectory[FILESYSTEM_VIRTUAL], _IRR_TEXT(""));
\r
510 WorkingDirectory[FILESYSTEM_NATIVE] = newDirectory;
\r
512 #if defined(_MSC_VER)
\r
513 success = (_chdir(newDirectory.c_str()) == 0);
\r
515 success = (chdir(newDirectory.c_str()) == 0);
\r
523 io::path CFileSystem::getAbsolutePath(const io::path& filename) const
\r
525 if ( filename.empty() )
\r
527 #if defined(_IRR_WINDOWS_API_)
\r
529 fschar_t fpath[_MAX_PATH];
\r
530 p = _fullpath(fpath, filename.c_str(), _MAX_PATH);
\r
531 core::stringc tmp(p);
\r
532 tmp.replace('\\', '/');
\r
534 #elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
538 p = realpath(filename.c_str(), fpath);
\r
541 // content in fpath is unclear at this point
\r
542 if (!fpath[0]) // seems like fpath wasn't altered, use our best guess
\r
544 io::path tmp(filename);
\r
545 return flattenFilename(tmp);
\r
548 return io::path(fpath);
\r
550 if (filename[filename.size()-1]=='/')
\r
551 return io::path(p)+_IRR_TEXT("/");
\r
553 return io::path(p);
\r
555 return io::path(filename);
\r
560 //! returns the directory part of a filename, i.e. all until the first
\r
561 //! slash or backslash, excluding it. If no directory path is prefixed, a '.'
\r
563 io::path CFileSystem::getFileDir(const io::path& filename) const
\r
565 // find last forward or backslash
\r
566 s32 lastSlash = filename.findLast('/');
\r
567 const s32 lastBackSlash = filename.findLast('\\');
\r
568 lastSlash = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
\r
570 if ((u32)lastSlash < filename.size())
\r
571 return filename.subString(0, lastSlash);
\r
573 return _IRR_TEXT(".");
\r
577 //! returns the base part of a filename, i.e. all except for the directory
\r
578 //! part. If no directory path is prefixed, the full name is returned.
\r
579 io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtension) const
\r
581 // find last forward or backslash
\r
582 s32 lastSlash = filename.findLast('/');
\r
583 const s32 lastBackSlash = filename.findLast('\\');
\r
584 lastSlash = core::max_(lastSlash, lastBackSlash);
\r
586 // get number of chars after last dot
\r
588 if (!keepExtension)
\r
590 // take care to search only after last slash to check only for
\r
591 // dots in the filename
\r
592 end = filename.findLast('.');
\r
593 if (end == -1 || end < lastSlash)
\r
596 end = filename.size()-end;
\r
599 if ((u32)lastSlash < filename.size())
\r
600 return filename.subString(lastSlash+1, filename.size()-lastSlash-1-end);
\r
602 return filename.subString(0, filename.size()-end);
\r
608 //! flatten a path and file name for example: "/you/me/../." becomes "/you"
\r
609 io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root) const
\r
611 directory.replace('\\', '/');
\r
612 if (directory.lastChar() != '/')
\r
613 directory.append('/');
\r
620 bool lastWasRealDir=false;
\r
622 while ((pos = directory.findNext('/', lastpos)) >= 0)
\r
624 subdir = directory.subString(lastpos, pos - lastpos + 1);
\r
626 if (subdir == _IRR_TEXT("../"))
\r
628 if (lastWasRealDir)
\r
630 deletePathFromPath(dir, 2);
\r
631 lastWasRealDir=(dir.size()!=0);
\r
635 dir.append(subdir);
\r
636 lastWasRealDir=false;
\r
639 else if (subdir == _IRR_TEXT("/"))
\r
643 else if (subdir != _IRR_TEXT("./"))
\r
645 dir.append(subdir);
\r
646 lastWasRealDir=true;
\r
656 //! Get the relative filename, relative to the given directory
\r
657 path CFileSystem::getRelativeFilename(const path& filename, const path& directory) const
\r
659 if ( filename.empty() || directory.empty() )
\r
662 io::path path1, file, ext;
\r
663 core::splitFilename(getAbsolutePath(filename), &path1, &file, &ext);
\r
664 io::path path2(getAbsolutePath(directory));
\r
665 std::list<io::path> list1, list2;
\r
666 path1.split(list1, _IRR_TEXT("/\\"), 2);
\r
667 path2.split(list2, _IRR_TEXT("/\\"), 2);
\r
668 std::list<io::path>::const_iterator it1,it2;
\r
672 #if defined (_IRR_WINDOWS_API_)
\r
673 fschar_t partition1 = 0, partition2 = 0;
\r
674 io::path prefix1, prefix2;
\r
675 if ( it1 != list1.end() )
\r
677 if ( it2 != list2.end() )
\r
679 if ( prefix1.size() > 1 && prefix1[1] == _IRR_TEXT(':') )
\r
680 partition1 = core::locale_lower(prefix1[0]);
\r
681 if ( prefix2.size() > 1 && prefix2[1] == _IRR_TEXT(':') )
\r
682 partition2 = core::locale_lower(prefix2[0]);
\r
684 // must have the same prefix or we can't resolve it to a relative filename
\r
685 if ( partition1 != partition2 )
\r
692 for (; it1 != list1.end() && it2 != list2.end()
\r
693 #if defined (_IRR_WINDOWS_API_)
\r
694 && (io::path(*it1).make_lower()==io::path(*it2).make_lower())
\r
703 path1=_IRR_TEXT("");
\r
704 for (; it2 != list2.end(); ++it2)
\r
705 path1 += _IRR_TEXT("../");
\r
706 while (it1 != list1.end())
\r
709 path1 += _IRR_TEXT('/');
\r
714 path1 += _IRR_TEXT('.');
\r
721 //! Sets the current file systen type
\r
722 EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType)
\r
724 EFileSystemType current = FileSystemType;
\r
725 FileSystemType = listType;
\r
730 //! Creates a list of files and directories in the current working directory
\r
731 IFileList* CFileSystem::createFileList()
\r
734 io::path Path = getWorkingDirectory();
\r
735 Path.replace('\\', '/');
\r
736 if (!Path.empty() && Path.lastChar() != '/')
\r
739 //! Construct from native filesystem
\r
740 if (FileSystemType == FILESYSTEM_NATIVE)
\r
742 // --------------------------------------------
\r
743 //! Windows version
\r
744 #ifdef _IRR_WINDOWS_API_
\r
746 r = new CFileList(Path, true, false);
\r
748 // TODO: Should be unified once mingw adapts the proper types
\r
749 #if defined(__GNUC__)
\r
750 long hFile; //mingw return type declaration
\r
755 struct _tfinddata_t c_file;
\r
756 if( (hFile = _tfindfirst( _T("*"), &c_file )) != -1L )
\r
760 r->addItem(Path + c_file.name, 0, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0);
\r
762 while( _tfindnext( hFile, &c_file ) == 0 );
\r
764 _findclose( hFile );
\r
769 // --------------------------------------------
\r
771 #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
774 r = new CFileList(Path, false, false);
\r
776 r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0);
\r
778 //! We use the POSIX compliant methods instead of scandir
\r
779 DIR* dirHandle=opendir(Path.c_str());
\r
782 struct dirent *dirEntry;
\r
783 while ((dirEntry=readdir(dirHandle)))
\r
786 bool isDirectory = false;
\r
788 if((strcmp(dirEntry->d_name, ".")==0) ||
\r
789 (strcmp(dirEntry->d_name, "..")==0))
\r
794 if (stat(dirEntry->d_name, &buf)==0)
\r
796 size = buf.st_size;
\r
797 isDirectory = S_ISDIR(buf.st_mode);
\r
799 #if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__)
\r
800 // only available on some systems
\r
803 isDirectory = dirEntry->d_type == DT_DIR;
\r
807 r->addItem(Path + dirEntry->d_name, 0, size, isDirectory, 0);
\r
809 closedir(dirHandle);
\r
815 //! create file list for the virtual filesystem
\r
816 r = new CFileList(Path, false, false);
\r
818 //! add relative navigation
\r
823 r->addItem(Path + _IRR_TEXT("."), 0, 0, true, 0);
\r
826 r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0);
\r
829 for (u32 i=0; i < FileArchives.size(); ++i)
\r
831 const IFileList *merge = FileArchives[i]->getFileList();
\r
833 for (u32 j=0; j < merge->getFileCount(); ++j)
\r
835 if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0)
\r
837 r->addItem(merge->getFullFileName(j), merge->getFileOffset(j), merge->getFileSize(j), merge->isDirectory(j), 0);
\r
848 //! Creates an empty filelist
\r
849 IFileList* CFileSystem::createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths)
\r
851 return new CFileList(path, ignoreCase, ignorePaths);
\r
855 //! determines if a file exists and would be able to be opened.
\r
856 bool CFileSystem::existFile(const io::path& filename) const
\r
858 for (u32 i=0; i < FileArchives.size(); ++i)
\r
859 if (FileArchives[i]->getFileList()->findFile(filename)!=-1)
\r
862 #if defined(_MSC_VER)
\r
863 return (_access(filename.c_str(), 0) != -1);
\r
864 #elif defined(F_OK)
\r
865 return (access(filename.c_str(), F_OK) != -1);
\r
867 return (access(filename.c_str(), 0) != -1);
\r
872 //! creates a filesystem which is able to open files from the ordinary file system,
\r
873 //! and out of zipfiles, which are able to be added to the filesystem.
\r
874 IFileSystem* createFileSystem()
\r
876 return new CFileSystem();
\r
880 } // end namespace irr
\r
881 } // end namespace io
\r