shadPS4/src/common/fs_file.cpp

97 lines
1.9 KiB
C++
Raw Normal View History

2024-02-23 23:32:32 +02:00
// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
2023-11-05 13:41:10 +02:00
#include "common/fs_file.h"
2023-05-02 18:22:19 +03:00
2023-10-26 22:55:13 +03:00
namespace Common::FS {
2023-06-22 22:48:55 -03:00
2023-10-26 22:55:13 +03:00
File::File() = default;
2023-06-22 22:48:55 -03:00
2023-10-26 22:55:13 +03:00
File::File(const std::string& path, OpenMode mode) {
open(path, mode);
2023-05-02 18:22:19 +03:00
}
2023-06-22 22:48:55 -03:00
2023-10-26 22:55:13 +03:00
File::~File() {
close();
2023-05-02 18:22:19 +03:00
}
2023-06-22 22:48:55 -03:00
2023-10-26 22:55:13 +03:00
bool File::open(const std::string& path, OpenMode mode) {
close();
#ifdef _WIN64
fopen_s(&m_file, path.c_str(), getOpenMode(mode));
#else
m_file = std::fopen(path.c_str(), getOpenMode(mode));
#endif
return isOpen();
2023-05-02 18:22:19 +03:00
}
2023-10-26 22:55:13 +03:00
bool File::close() {
if (!isOpen() || std::fclose(m_file) != 0) [[unlikely]] {
m_file = nullptr;
return false;
2023-10-26 22:55:13 +03:00
}
2023-05-02 18:22:19 +03:00
2023-10-26 22:55:13 +03:00
m_file = nullptr;
return true;
2023-05-02 18:22:19 +03:00
}
2024-02-23 23:32:32 +02:00
bool File::write(std::span<const u8> data) {
2023-10-26 22:55:13 +03:00
return isOpen() && std::fwrite(data.data(), 1, data.size(), m_file) == data.size();
2023-05-02 18:22:19 +03:00
}
2023-10-26 22:55:13 +03:00
bool File::read(void* data, u64 size) const {
return isOpen() && std::fread(data, 1, size, m_file) == size;
2023-05-02 18:22:19 +03:00
}
2023-10-26 22:55:13 +03:00
bool File::seek(s64 offset, SeekMode mode) {
#ifdef _WIN64
if (!isOpen() || _fseeki64(m_file, offset, getSeekMode(mode)) != 0) {
return false;
}
#else
if (!isOpen() || fseeko64(m_file, offset, getSeekMode(mode)) != 0) {
return false;
}
#endif
return true;
2023-05-02 18:22:19 +03:00
}
2023-10-26 22:55:13 +03:00
u64 File::tell() const {
if (isOpen()) [[likely]] {
#ifdef _WIN64
return _ftelli64(m_file);
2023-10-26 22:55:13 +03:00
#else
return ftello64(m_file);
2023-10-26 22:55:13 +03:00
#endif
}
return -1;
2023-05-02 18:22:19 +03:00
}
2023-10-26 22:55:13 +03:00
u64 File::getFileSize() {
#ifdef _WIN64
const u64 pos = _ftelli64(m_file);
if (_fseeki64(m_file, 0, SEEK_END) != 0) {
return 0;
2023-10-26 22:55:13 +03:00
}
const u64 size = _ftelli64(m_file);
if (_fseeki64(m_file, pos, SEEK_SET) != 0) {
return 0;
2023-10-26 22:55:13 +03:00
}
#else
const u64 pos = ftello64(m_file);
if (fseeko64(m_file, 0, SEEK_END) != 0) {
return 0;
2023-10-26 22:55:13 +03:00
}
const u64 size = ftello64(m_file);
if (fseeko64(m_file, pos, SEEK_SET) != 0) {
return 0;
2023-10-26 22:55:13 +03:00
}
#endif
return size;
2023-05-02 18:22:19 +03:00
}
2023-10-26 22:55:13 +03:00
} // namespace Common::FS