C++ 如何确保数据结构能够适应大文件中的数据?

C++ 如何确保数据结构能够适应大文件中的数据?,c++,C++,我有一个系统,streampos是64位的,但是size\u t是32位的。我需要加载大文件。项目有时编译为32位,有时编译为64位 如果文件太大,无法存储在单个数据结构中,我希望编写失败的代码。我担心尺码类型可能会以错误的方式铸造。请看一下示例代码,并对如何使其在这种情况下安全发表意见 ifstream file; vector<char> data; // find size of file streampos beg = file.tellg(); file.seekg(0,

我有一个系统,
streampos
是64位的,但是
size\u t
是32位的。我需要加载大文件。项目有时编译为32位,有时编译为64位

如果文件太大,无法存储在单个数据结构中,我希望编写失败的代码。我担心尺码类型可能会以错误的方式铸造。请看一下示例代码,并对如何使其在这种情况下安全发表意见

ifstream file;
vector<char> data;

// find size of file
streampos beg = file.tellg();
file.seekg(0, ios_base::end);
streampos end = file.tellg();
file.seekg(0, ios_base::beg);

// prepare vector
if (data.max_size() > (end - beg)) { throw "blah"; } // warning: signed/unsigned mismatch
data.resize(static_cast<vector<char>::size_type>(end - beg)); // what happens if the size is more than 32-bits?

// copy data
file.read(&data[0], data.size());
ifstream文件;
矢量数据;
//查找文件大小
streampos beg=file.tellg();
seekg(0,ios_base::end);
streampos end=file.tellg();
seekg(0,ios_base::beg);
//准备载体
if(data.max_size()>(end-beg)){throw“blah”}//警告:有符号/无符号不匹配
data.resize(静态_cast(end-beg));//如果大小超过32位,会发生什么情况?
//复制数据
file.read(&data[0],data.size());

首先,在您的文本中,我知道如果文件内容大于数据的最大大小,您希望抛出

所以不是

if (data.max_size() > (end - beg)) // triggered whenever the file could fit in memory !!
    { throw "blah"; } 
我强烈推荐

if (data.max_size() <  (end - beg)) // < instead of > 
    ...

if(静态转换(data.max\u size()<(end-beg))
现在令人惊讶的是,您的编译器本身没有进行转换。在MSVC13下,我没有得到警告

最后一句话:如果(end beg)大于size_type所允许的值,则会引发异常。因此,如果到达下一行:

data.resize(static_cast<vector<char>::size_type>(end - beg)); // if unsafe, the previous line would already have thrown an exception ! 
data.resize(static_cast(end-beg));//如果不安全,前一行可能已经抛出异常!

如果
end beg
不能放入
向量::size\u type
,那么它必然也会大于
向量::max\u size()
。我认为你在这里完全没有问题。(好吧,假设它是正的,但这也是一个安全的假设)不相关,我总是使用
无符号字符
表示字节,因此,如果没有显式转换,则无法将其传递给任何字符串函数。@MooingDuck Hi。我需要在这里进行转换,因为这里有一个警告。您有什么建议吗?另外,如何在不重新解释转换的情况下有效地将文件加载到无符号字符向量中?我认为您的转换很好t、 这正是
static\u cast
的作用。要从一个静态类型转换到另一个静态类型,在您确定它肯定会成功后。要将文件读入
无符号字符的向量,您应该使用
重新解释\u cast
,而不是回避它。@MooingDuck我需要在指定行上进行另一个转换
 if (static_cast<std::streamoff>(data.max_size() < (end - beg))
data.resize(static_cast<vector<char>::size_type>(end - beg)); // if unsafe, the previous line would already have thrown an exception !