Merge pull request #5720 from JosJuice/file-metadata

FileUtil: Redesign Exists/IsDirectory/GetSize
This commit is contained in:
Leo Lam 2017-07-11 00:28:34 +02:00 committed by GitHub
commit b6c3479bb4
21 changed files with 175 additions and 177 deletions

View File

@ -51,38 +51,67 @@
// REMEMBER: strdup considered harmful!
namespace File
{
// Returns true if file filename exists
bool Exists(const std::string& filename)
{
struct stat file_info;
#ifdef _WIN32
int result = _tstat64(UTF8ToTStr(filename).c_str(), &file_info);
#else
int result = stat(filename.c_str(), &file_info);
#endif
return (result == 0);
FileInfo::FileInfo(const std::string& path)
{
m_exists = _tstat64(UTF8ToTStr(path).c_str(), &m_stat) == 0;
}
// Returns true if filename is a directory
bool IsDirectory(const std::string& filename)
FileInfo::FileInfo(const char* path) : FileInfo(std::string(path))
{
struct stat file_info;
#ifdef _WIN32
int result = _tstat64(UTF8ToTStr(filename).c_str(), &file_info);
}
#else
int result = stat(filename.c_str(), &file_info);
FileInfo::FileInfo(const std::string& path) : FileInfo(path.c_str())
{
}
FileInfo::FileInfo(const char* path)
{
m_exists = stat(path, &m_stat) == 0;
}
#endif
if (result < 0)
{
WARN_LOG(COMMON, "IsDirectory: stat failed on %s: %s", filename.c_str(), strerror(errno));
return false;
}
FileInfo::FileInfo(int fd)
{
m_exists = fstat(fd, &m_stat);
}
return S_ISDIR(file_info.st_mode);
bool FileInfo::Exists() const
{
return m_exists;
}
bool FileInfo::IsDirectory() const
{
return m_exists ? S_ISDIR(m_stat.st_mode) : false;
}
bool FileInfo::IsFile() const
{
return m_exists ? !S_ISDIR(m_stat.st_mode) : false;
}
u64 FileInfo::GetSize() const
{
return IsFile() ? m_stat.st_size : 0;
}
// Returns true if the path exists
bool Exists(const std::string& path)
{
return FileInfo(path).Exists();
}
// Returns true if the path exists and is a directory
bool IsDirectory(const std::string& path)
{
return FileInfo(path).IsDirectory();
}
// Returns true if the path exists and is a file
bool IsFile(const std::string& path)
{
return FileInfo(path).IsFile();
}
// Deletes a given filename, return true on success
@ -91,16 +120,18 @@ bool Delete(const std::string& filename)
{
INFO_LOG(COMMON, "Delete: file %s", filename.c_str());
const FileInfo file_info(filename);
// Return true because we care about the file no
// being there, not the actual delete.
if (!Exists(filename))
if (!file_info.Exists())
{
WARN_LOG(COMMON, "Delete: %s does not exist", filename.c_str());
return true;
}
// We can't delete a directory
if (IsDirectory(filename))
if (file_info.IsDirectory())
{
WARN_LOG(COMMON, "Delete failed: %s is a directory", filename.c_str());
return false;
@ -163,7 +194,7 @@ bool CreateFullPath(const std::string& fullPath)
int panicCounter = 100;
INFO_LOG(COMMON, "CreateFullPath: path %s", fullPath.c_str());
if (File::Exists(fullPath))
if (Exists(fullPath))
{
INFO_LOG(COMMON, "CreateFullPath: path exists %s", fullPath.c_str());
return true;
@ -181,7 +212,7 @@ bool CreateFullPath(const std::string& fullPath)
// Include the '/' so the first call is CreateDir("/") rather than CreateDir("")
std::string const subPath(fullPath.substr(0, position + 1));
if (!File::IsDirectory(subPath))
if (!IsDirectory(subPath))
File::CreateDir(subPath);
// A safety check
@ -201,7 +232,7 @@ bool DeleteDir(const std::string& filename)
INFO_LOG(COMMON, "DeleteDir: directory %s", filename.c_str());
// check if a directory
if (!File::IsDirectory(filename))
if (!IsDirectory(filename))
{
ERROR_LOG(COMMON, "DeleteDir: Not a directory %s", filename.c_str());
return false;
@ -344,46 +375,16 @@ bool Copy(const std::string& srcFilename, const std::string& destFilename)
#endif
}
// Returns the size of filename (64bit)
u64 GetSize(const std::string& filename)
// Returns the size of a file (or returns 0 if the path isn't a file that exists)
u64 GetSize(const std::string& path)
{
if (!Exists(filename))
{
WARN_LOG(COMMON, "GetSize: failed %s: No such file", filename.c_str());
return 0;
}
if (IsDirectory(filename))
{
WARN_LOG(COMMON, "GetSize: failed %s: is a directory", filename.c_str());
return 0;
}
struct stat buf;
#ifdef _WIN32
if (_tstat64(UTF8ToTStr(filename).c_str(), &buf) == 0)
#else
if (stat(filename.c_str(), &buf) == 0)
#endif
{
DEBUG_LOG(COMMON, "GetSize: %s: %lld", filename.c_str(), (long long)buf.st_size);
return buf.st_size;
}
ERROR_LOG(COMMON, "GetSize: Stat failed %s: %s", filename.c_str(), GetLastErrorMsg().c_str());
return 0;
return FileInfo(path).GetSize();
}
// Overloaded GetSize, accepts file descriptor
u64 GetSize(const int fd)
{
struct stat buf;
if (fstat(fd, &buf) != 0)
{
ERROR_LOG(COMMON, "GetSize: stat failed %i: %s", fd, GetLastErrorMsg().c_str());
return 0;
}
return buf.st_size;
return FileInfo(fd).GetSize();
}
// Overloaded GetSize, accepts FILE*
@ -458,7 +459,8 @@ FSTEntry ScanDirectoryTree(const std::string& directory, bool recursive)
continue;
auto physical_name = directory + DIR_SEP + virtual_name;
FSTEntry entry;
entry.isDirectory = IsDirectory(physical_name);
const FileInfo file_info(physical_name);
entry.isDirectory = file_info.IsDirectory();
if (entry.isDirectory)
{
if (recursive)
@ -469,7 +471,7 @@ FSTEntry ScanDirectoryTree(const std::string& directory, bool recursive)
}
else
{
entry.size = GetSize(physical_name);
entry.size = file_info.GetSize();
}
entry.virtualName = virtual_name;
entry.physicalName = physical_name;
@ -561,9 +563,9 @@ void CopyDir(const std::string& source_path, const std::string& dest_path)
{
if (source_path == dest_path)
return;
if (!File::Exists(source_path))
if (!Exists(source_path))
return;
if (!File::Exists(dest_path))
if (!Exists(dest_path))
File::CreateFullPath(dest_path);
#ifdef _WIN32
@ -596,11 +598,11 @@ void CopyDir(const std::string& source_path, const std::string& dest_path)
std::string dest = dest_path + DIR_SEP + virtualName;
if (IsDirectory(source))
{
if (!File::Exists(dest))
if (!Exists(dest))
File::CreateFullPath(dest + DIR_SEP);
CopyDir(source, dest);
}
else if (!File::Exists(dest))
else if (!Exists(dest))
File::Copy(source, dest);
#ifdef _WIN32
} while (FindNextFile(hFind, &ffd) != 0);
@ -852,12 +854,12 @@ void SetUserPath(unsigned int dir_index, const std::string& path)
std::string GetThemeDir(const std::string& theme_name)
{
std::string dir = File::GetUserPath(D_THEMES_IDX) + theme_name + "/";
if (File::Exists(dir))
if (Exists(dir))
return dir;
// If the theme doesn't exist in the user dir, load from shared directory
dir = GetSysDirectory() + THEMES_DIR "/" + theme_name + "/";
if (File::Exists(dir))
if (Exists(dir))
return dir;
// If the theme doesn't exist at all, load the default theme

View File

@ -9,6 +9,8 @@
#include <string>
#include <vector>
#include <sys/stat.h>
#include "Common/CommonTypes.h"
#include "Common/NonCopyable.h"
@ -78,14 +80,42 @@ struct FSTEntry
std::vector<FSTEntry> children;
};
// Returns true if file filename exists
bool Exists(const std::string& filename);
// The functions in this class are functionally identical to the standalone functions
// below, but if you are going to be calling more than one of the functions using the
// same path, creating a single FileInfo object and calling its functions multiple
// times is faster than calling standalone functions multiple times.
class FileInfo final
{
public:
explicit FileInfo(const std::string& path);
explicit FileInfo(const char* path);
explicit FileInfo(int fd);
// Returns true if filename is a directory
bool IsDirectory(const std::string& filename);
// Returns true if the path exists
bool Exists() const;
// Returns true if the path exists and is a directory
bool IsDirectory() const;
// Returns true if the path exists and is a file
bool IsFile() const;
// Returns the size of a file (or returns 0 if the path doesn't refer to a file)
u64 GetSize() const;
// Returns the size of filename (64bit)
u64 GetSize(const std::string& filename);
private:
struct stat m_stat;
bool m_exists;
};
// Returns true if the path exists
bool Exists(const std::string& path);
// Returns true if the path exists and is a directory
bool IsDirectory(const std::string& path);
// Returns true if the path exists and is a file
bool IsFile(const std::string& path);
// Returns the size of a file (or returns 0 if the path isn't a file that exists)
u64 GetSize(const std::string& path);
// Overloaded GetSize, accepts file descriptor
u64 GetSize(const int fd);

View File

@ -56,8 +56,7 @@ void SysConf::Load()
{
Clear();
if (!File::Exists(m_file_name) || File::GetSize(m_file_name) != SYSCONF_SIZE ||
!LoadFromFile(m_file_name))
if (File::GetSize(m_file_name) != SYSCONF_SIZE || !LoadFromFile(m_file_name))
{
WARN_LOG(CORE, "No valid SYSCONF detected. Creating a new one.");
InsertDefaultEntries();

View File

@ -466,8 +466,8 @@ bool CBoot::BootUp(std::unique_ptr<BootParameters> boot)
BootExecutableReader::BootExecutableReader(const std::string& file_name)
{
m_bytes.resize(File::GetSize(file_name));
File::IOFile file{file_name, "rb"};
m_bytes.resize(file.GetSize());
file.ReadBytes(m_bytes.data(), m_bytes.size());
}

View File

@ -52,9 +52,6 @@ void AXUCode::LoadResamplingCoefficients()
for (fidx = 0; fidx < ArraySize(filenames); ++fidx)
{
filename = filenames[fidx];
if (!File::Exists(filename))
continue;
if (File::GetSize(filename) != 0x1000)
continue;

View File

@ -204,30 +204,26 @@ void CEXIIPL::LoadFontFile(const std::string& filename, u32 offset)
if (ipl_rom_path.empty())
ipl_rom_path = FindIPLDump(File::GetSysDirectory() + GC_SYS_DIR);
if (File::Exists(ipl_rom_path))
{
// The user has an IPL dump, load the font from it
File::IOFile stream(ipl_rom_path, "rb");
if (!stream)
return;
// Official Windows-1252 and Shift JIS fonts present on the IPL dumps are 0x2575 and 0x4a24d
// bytes long respectively, so, determine the size of the font being loaded based on the offset
u64 fontsize = (offset == 0x1aff00) ? 0x4a24d : 0x2575;
INFO_LOG(BOOT, "Found IPL dump, loading %s font from %s",
((offset == 0x1aff00) ? "Shift JIS" : "Windows-1252"), (ipl_rom_path).c_str());
stream.Seek(offset, 0);
stream.ReadBytes(m_pIPL + offset, fontsize);
m_FontsLoaded = true;
}
else
// If the user has an IPL dump, load the font from it
File::IOFile stream(ipl_rom_path, "rb");
if (!stream)
{
// No IPL dump available, load bundled font instead
LoadFileToIPL(filename, offset);
return;
}
// Official Windows-1252 and Shift JIS fonts present on the IPL dumps are 0x2575 and 0x4a24d
// bytes long respectively, so, determine the size of the font being loaded based on the offset
u64 fontsize = (offset == 0x1aff00) ? 0x4a24d : 0x2575;
INFO_LOG(BOOT, "Found IPL dump, loading %s font from %s",
((offset == 0x1aff00) ? "Shift JIS" : "Windows-1252"), (ipl_rom_path).c_str());
stream.Seek(offset, 0);
stream.ReadBytes(m_pIPL + offset, fontsize);
m_FontsLoaded = true;
}
void CEXIIPL::SetCS(int _iCS)

View File

@ -176,11 +176,12 @@ void CEXIMemoryCard::SetupGciFolder(u16 sizeMb)
strDirectoryName = strDirectoryName + SConfig::GetDirectoryForRegion(region) + DIR_SEP +
StringFromFormat("Card %c", 'A' + card_index);
if (!File::Exists(strDirectoryName)) // first use of memcard folder, migrate automatically
const File::FileInfo file_info(strDirectoryName);
if (!file_info.Exists()) // first use of memcard folder, migrate automatically
{
MigrateFromMemcardFile(strDirectoryName + DIR_SEP, card_index);
}
else if (!File::IsDirectory(strDirectoryName))
else if (!file_info.IsDirectory())
{
if (File::Rename(strDirectoryName, strDirectoryName + ".original"))
{

View File

@ -142,10 +142,8 @@ GCMemcardDirectory::GCMemcardDirectory(const std::string& directory, int slot, u
m_save_directory(directory), m_exiting(false)
{
// Use existing header data if available
if (File::Exists(m_save_directory + MC_HDR))
{
File::IOFile hdr_file((m_save_directory + MC_HDR), "rb");
hdr_file.ReadBytes(&m_hdr, BLOCK_SIZE);
File::IOFile((m_save_directory + MC_HDR), "rb").ReadBytes(&m_hdr, BLOCK_SIZE);
}
std::vector<std::string> filenames = Common::DoFileSearch({m_save_directory}, {".gci"});

View File

@ -343,6 +343,7 @@ void CWiiSaveCrypted::ImportWiiSaveFiles()
std::string file_path_full = m_wii_title_path + file_path;
File::CreateFullPath(file_path_full);
const File::FileInfo file_info(file_path_full);
if (file_hdr_tmp.type == 1)
{
file_size = Common::swap32(file_hdr_tmp.size);
@ -361,7 +362,7 @@ void CWiiSaveCrypted::ImportWiiSaveFiles()
mbedtls_aes_crypt_cbc(&m_aes_ctx, MBEDTLS_AES_DECRYPT, file_size_rounded, m_iv,
static_cast<const u8*>(file_data_enc.data()), file_data.data());
if (!File::Exists(file_path_full) ||
if (!file_info.Exists() ||
AskYesNoT("%s already exists, overwrite?", file_path_full.c_str()))
{
INFO_LOG(CONSOLE, "Creating file %s", file_path_full.c_str());
@ -372,12 +373,12 @@ void CWiiSaveCrypted::ImportWiiSaveFiles()
}
else if (file_hdr_tmp.type == 2)
{
if (!File::Exists(file_path_full))
if (!file_info.Exists())
{
if (!File::CreateDir(file_path_full))
ERROR_LOG(CONSOLE, "Failed to create directory %s", file_path_full.c_str());
}
else if (!File::IsDirectory(file_path_full))
else if (!file_info.IsDirectory())
{
ERROR_LOG(CONSOLE,
"Failed to create directory %s because a file with the same name exists",
@ -399,13 +400,14 @@ void CWiiSaveCrypted::ExportWiiSaveFiles()
memset(&file_hdr_tmp, 0, FILE_HDR_SZ);
u32 file_size = 0;
if (File::IsDirectory(m_files_list[i]))
const File::FileInfo file_info(m_files_list[i]);
if (file_info.IsDirectory())
{
file_hdr_tmp.type = 2;
}
else
{
file_size = static_cast<u32>(File::GetSize(m_files_list[i]));
file_size = static_cast<u32>(file_info.GetSize());
file_hdr_tmp.type = 1;
}

View File

@ -524,13 +524,15 @@ IPCCommandResult FS::ReadDirectory(const IOCtlVRequest& request)
INFO_LOG(IOS_FILEIO, "FS: IOCTL_READ_DIR %s", DirName.c_str());
if (!File::Exists(DirName))
const File::FileInfo file_info(DirName);
if (!file_info.Exists())
{
WARN_LOG(IOS_FILEIO, "FS: Search not found: %s", DirName.c_str());
return GetFSReply(FS_ENOENT);
}
if (!File::IsDirectory(DirName))
if (!file_info.IsDirectory())
{
// It's not a directory, so error.
// Games don't usually seem to care WHICH error they get, as long as it's <

View File

@ -102,7 +102,7 @@ ReturnCode FileIO::Open(const OpenRequest& request)
// The file must exist before we can open it
// It should be created by ISFS_CreateFile, not here
if (!File::Exists(m_filepath) || File::IsDirectory(m_filepath))
if (!File::IsFile(m_filepath))
{
WARN_LOG(IOS_FILEIO, "FileIO: Open (%s) failed - File doesn't exist %s", Modes[m_Mode],
m_filepath.c_str());

View File

@ -27,22 +27,15 @@ NWC24Config::NWC24Config()
void NWC24Config::ReadConfig()
{
if (File::Exists(m_path))
if (!File::IOFile(m_path, "rb").ReadBytes(&m_data, sizeof(m_data)))
{
if (!File::IOFile(m_path, "rb").ReadBytes(&m_data, sizeof(m_data)))
{
ResetConfig();
}
else
{
const s32 config_error = CheckNwc24Config();
if (config_error)
ERROR_LOG(IOS_WC24, "There is an error in the config for for WC24: %d", config_error);
}
ResetConfig();
}
else
{
ResetConfig();
const s32 config_error = CheckNwc24Config();
if (config_error)
ERROR_LOG(IOS_WC24, "There is an error in the config for for WC24: %d", config_error);
}
}

View File

@ -27,15 +27,8 @@ WiiNetConfig::WiiNetConfig()
void WiiNetConfig::ReadConfig()
{
if (File::Exists(m_path))
{
if (!File::IOFile(m_path, "rb").ReadBytes(&m_data, sizeof(m_data)))
ResetConfig();
}
else
{
if (!File::IOFile(m_path, "rb").ReadBytes(&m_data, sizeof(m_data)))
ResetConfig();
}
}
void WiiNetConfig::WriteConfig() const

View File

@ -40,9 +40,9 @@ void BackUpBTInfoSection(const SysConf* sysconf)
void RestoreBTInfoSection(SysConf* sysconf)
{
const std::string filename = File::GetUserPath(D_SESSION_WIIROOT_IDX) + DIR_SEP WII_BTDINF_BACKUP;
if (!File::Exists(filename))
return;
File::IOFile backup(filename, "rb");
if (!backup)
return;
std::vector<u8> section(BT_INFO_SECTION_LENGTH);
if (!backup.ReadBytes(section.data(), section.size()))
{

View File

@ -960,20 +960,13 @@ bool PlayInput(const std::string& filename)
if (s_playMode != MODE_NONE)
return false;
if (!File::Exists(filename))
File::IOFile recording_file(filename, "rb");
if (!recording_file.ReadArray(&tmpHeader, 1))
return false;
File::IOFile g_recordfd;
if (!g_recordfd.Open(filename, "rb"))
return false;
g_recordfd.ReadArray(&tmpHeader, 1);
if (!IsMovieHeader(tmpHeader.filetype))
{
PanicAlertT("Invalid recording file");
g_recordfd.Close();
return false;
}
@ -993,11 +986,11 @@ bool PlayInput(const std::string& filename)
Core::UpdateWantDeterminism();
s_totalBytes = g_recordfd.GetSize() - 256;
s_totalBytes = recording_file.GetSize() - 256;
EnsureTmpInputSize((size_t)s_totalBytes);
g_recordfd.ReadArray(tmpInput, (size_t)s_totalBytes);
recording_file.ReadArray(tmpInput, (size_t)s_totalBytes);
s_currentByte = 0;
g_recordfd.Close();
recording_file.Close();
// Load savestate (and skip to frame data)
if (tmpHeader.bFromSaveState)

View File

@ -163,7 +163,7 @@ bool NANDContentLoader::Initialize(const std::string& name)
return false;
}
std::vector<u8> bytes(File::GetSize(tmd_filename));
std::vector<u8> bytes(tmd_file.GetSize());
tmd_file.ReadBytes(bytes.data(), bytes.size());
m_tmd.SetBytes(std::move(bytes));

View File

@ -46,7 +46,7 @@ bool IsWiiWAD(BlobReader& reader)
WiiWAD::WiiWAD(const std::string& name) : m_reader(CreateBlobReader(name))
{
if (m_reader == nullptr || File::IsDirectory(name))
if (m_reader == nullptr)
{
m_valid = false;
return;

View File

@ -359,18 +359,15 @@ void GameCubeConfigPane::ChooseSlotPath(bool is_slot_a, ExpansionInterface::TEXI
if (!filename.empty())
{
if (File::Exists(filename))
if (memcard && File::Exists(filename))
{
if (memcard)
GCMemcard memorycard(filename);
if (!memorycard.IsValid())
{
GCMemcard memorycard(filename);
if (!memorycard.IsValid())
{
WxUtils::ShowErrorDialog(wxString::Format(_("Cannot use that file as a memory card.\n%s\n"
"is not a valid GameCube memory card file"),
filename.c_str()));
return;
}
WxUtils::ShowErrorDialog(wxString::Format(_("Cannot use that file as a memory card.\n%s\n"
"is not a valid GameCube memory card file"),
filename.c_str()));
return;
}
}

View File

@ -4,6 +4,7 @@
#include "DolphinWX/ISOProperties/ISOProperties.h"
#include <algorithm>
#include <cinttypes>
#include <cstddef>
#include <cstdio>
@ -442,16 +443,12 @@ void CISOProperties::CreateGUIControls()
sButtons->GetAffirmativeButton()->SetLabel(_("Close"));
// If there is no default gameini, disable the button.
bool game_ini_exists = false;
for (const std::string& ini_filename :
SConfig::GetGameIniFilenames(game_id, m_open_iso->GetRevision()))
{
if (File::Exists(File::GetSysDirectory() + GAMESETTINGS_DIR DIR_SEP + ini_filename))
{
game_ini_exists = true;
break;
}
}
const std::vector<std::string> ini_names =
SConfig::GetGameIniFilenames(game_id, m_open_iso->GetRevision());
const bool game_ini_exists =
std::any_of(ini_names.cbegin(), ini_names.cend(), [](const std::string& name) {
return File::Exists(File::GetSysDirectory() + GAMESETTINGS_DIR DIR_SEP + name);
});
if (!game_ini_exists)
EditConfigDefault->Disable();

View File

@ -856,11 +856,9 @@ void InputConfigDialog::LoadProfile(wxCommandEvent&)
std::string fname;
InputConfigDialog::GetProfilePath(fname);
if (!File::Exists(fname))
return;
IniFile inifile;
inifile.Load(fname);
if (!inifile.Load(fname))
return;
controller->LoadConfig(inifile.GetOrCreateSection("Profile"));
controller->UpdateReferences(g_controller_interface);

View File

@ -424,7 +424,7 @@ void TextureCacheBase::DumpTexture(TCacheEntry* entry, std::string basename, uns
std::string szDir = File::GetUserPath(D_DUMPTEXTURES_IDX) + SConfig::GetInstance().GetGameID();
// make sure that the directory exists
if (!File::Exists(szDir) || !File::IsDirectory(szDir))
if (!File::IsDirectory(szDir))
File::CreateDir(szDir);
if (level > 0)