今天我正在替换一个低级的 C 风格的方法,该方法将缓冲区保存到文件中。整个事情看起来像这样:
bool Profile::save(const char* path)
{
FILE* pFile = fopen(path, "w");
BOOST_SCOPE_EXIT((pFile)) {
fclose(pFile);
pFile=NULL;
} BOOST_SCOPE_EXIT_END
if(pFile == 0)
{
LOG_ERROR("could not open profile");
return false;
}
size_t nWriteSize = fwrite(DataBlock, 1, sizeof(DataBlock), pFile);
if(nWriteSize != sizeof(DataBlock))
{
LOG_ERROR("Only " << nWriteSize << " of " << sizeof(DataBlock) << "bytes written");
return false;
}
return true;
}
这个方法实际上包含一个错误,如果找不到要打开的文件,它会出现段错误(在 BOOST_SCOPE_EXIT 中,我们忽略了检查 pFile!=NULL 是否存在)。所以我想我会用更惯用的 C++ 方式重写整个东西。这是我想出的:
bool Profile::save(const char* path)
{
std::ofstream profile(path, std::ios::out | std::ios::binary);
if(!profile)
{
LOG_ERROR("could not open " << path);
return false;
}
const char* pBeginOfBlock = reinterpret_cast<char*>(DataBlock);
const char* pEndOfBlock = reinterpret_cast<char*>(DataBlock + sizeof(DataBlock));
std::ostreambuf_iterator<char> begin_file = std::ostreambuf_iterator<char>(profile);
std::ostreambuf_iterator<char> end_file = std::copy(pBeginOfBlock,
pEndOfBlock,
begin_file);
const unsigned int BytesWritten = std::distance(begin_file, end_file);
if(BytesWritten != sizeof(DataBlock))
{
LOG_ERROR("Only " << BytesWritten << " of " << sizeof(DataBlock) << "bytes written");
return false;
}
return true;
}
但是,这不会编译。对于我尝试获取 ostreambuf_iterators 的距离的行,它给了我一个错误:
error: void value not ignored as it ought to be
显然 difference_type ostreambuf_iterator 是无效的。如何检查所有字节是否已实际写入文件?检查是否必要或 std::copy 是否提供某种保证?
最佳答案
ostreambuf_iterator
是一个输出迭代器,std::distance
需要输入迭代器。
错误可能有点神秘,但这是由于 difference_type
被 typedef
编辑为 void
,即试图测量之间的距离两个 ostreambuf_iterator
毫无意义,它们甚至不能相互比较。
关于c++ - ostreambuf_iterator<char> 的 difference_type 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26503502/