code update

This commit is contained in:
Quella777
2025-08-11 11:40:28 +08:00
parent 417f8822be
commit d1287fe234
3 changed files with 34 additions and 4 deletions

View File

@@ -15,3 +15,15 @@ c/c++基本开发库
可以计算特定符号最后一个字节所在位置
所有操作都添加mutex锁机制 ,保障线程安全
# 读文件操作
支持全文读取(文本和二进制模式)
支持按行读取文本内容
支持按指定字节数读取数据
支持计算第一个指定字节序列结束位置(包含该序列本身)的字节数
提供文件是否存在和文件大小查询
支持重置文件读取位置,实现多次读取

View File

@@ -198,6 +198,7 @@ namespace QCL
* - 与 WriteFile 类风格保持一致
* - 支持文本文件与二进制文件
* - 自动关闭文件(析构时)
* - 内部使用 std::mutex 实现线程安全
*/
class ReadFile
{
@@ -280,6 +281,7 @@ namespace QCL
private:
std::string filename_; // 文件路径
std::ifstream file_; // 文件流对象
mutable std::mutex mtx_; // 可变,保证 const 方法也能加锁
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

View File

@@ -344,11 +344,15 @@ namespace QCL
ReadFile::~ReadFile()
{
std::lock_guard<std::mutex> lock(mtx_);
Close();
}
bool ReadFile::Open()
{
std::lock_guard<std::mutex> lock(mtx_);
if (file_.is_open())
file_.close();
file_.open(filename_, std::ios::in | std::ios::binary);
return file_.is_open();
}
@@ -356,16 +360,21 @@ namespace QCL
void ReadFile::Close()
{
if (file_.is_open())
{
std::lock_guard<std::mutex> lock(mtx_);
file_.close();
}
}
bool ReadFile::IsOpen() const
{
std::lock_guard<std::mutex> lock(mtx_);
return file_.is_open();
}
std::string ReadFile::ReadAllText()
{
std::lock_guard<std::mutex> lock(mtx_);
if (!file_.is_open() && !Open())
return "";
@@ -376,6 +385,7 @@ namespace QCL
std::vector<char> ReadFile::ReadAllBinary()
{
std::lock_guard<std::mutex> lock(mtx_);
if (!file_.is_open() && !Open())
return {};
@@ -384,6 +394,7 @@ namespace QCL
std::vector<std::string> ReadFile::ReadLines()
{
std::lock_guard<std::mutex> lock(mtx_);
if (!file_.is_open() && !Open())
return {};
@@ -398,17 +409,19 @@ namespace QCL
std::vector<char> ReadFile::ReadBytes(size_t count)
{
std::lock_guard<std::mutex> lock(mtx_);
if (!file_.is_open() && !Open())
return {};
std::vector<char> buffer(count);
file_.read(buffer.data(), count);
buffer.resize(file_.gcount()); // 实际读取的字节数
buffer.resize(file_.gcount());
return buffer;
}
size_t ReadFile::GetBytesBefore(const std::string &marker)
{
std::lock_guard<std::mutex> lock(mtx_);
if (!file_.is_open() && !Open())
return 0;
@@ -425,11 +438,13 @@ namespace QCL
bool ReadFile::FileExists() const
{
std::lock_guard<std::mutex> lock(mtx_);
return std::filesystem::exists(filename_);
}
size_t ReadFile::GetFileSize() const
{
std::lock_guard<std::mutex> lock(mtx_);
if (!FileExists())
return 0;
return std::filesystem::file_size(filename_);
@@ -437,9 +452,10 @@ namespace QCL
void ReadFile::Reset()
{
std::lock_guard<std::mutex> lock(mtx_);
if (file_.is_open())
{
file_.clear(); // 清除 EOF 标志
file_.clear();
file_.seekg(0, std::ios::beg);
}
}