自己在做一个项目的时候,报了下面的这个问题:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_replace_aux
经过自己的研究,发现是在读取文件的时候没有加上错误判断。
通过网站直接访问一个服务器中的一个html文件时,对html文件进行修饰的css,js,favicon.ico文件通样也会被请求。但是我对应的保存前端的文件夹中并没有favicon.ico文件,直接给它拼上与html,css,js文件相同的文件路径前缀导致favicon.ico文件路径错误,打开文件失败。
在读取文件内容的代码中加入判断打开文件失败返回的语句即可解决此问题。
本来读取文件内容的代码我是这样写的:
static bool read(const std::string& filename, std::string& body)
{
//打开文件
std::ifstream ifs(filename, std::ios::binary);
//获取文件大小
size_t fsize = 0;
ifs.seekg(0, std::ios::end);
fsize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
//读取文件所有数据
body.resize(fsize);
ifs.read(&body[0], fsize);
if(!ifs.good())
{
LOG(ERROR, "file read failed!\n");
ifs.close();
return false;
}
//关闭文件
ifs.close();
return true;
}
加上打开失败判断即可:
static bool read(const std::string& filename, std::string& body)
{
//打开文件
std::ifstream ifs(filename, std::ios::binary);
if (ifs.is_open() == false) {
LOG(ERROR,"%s file open failed!!", filename.c_str());
return false;
}
//获取文件大小
size_t fsize = 0;
ifs.seekg(0, std::ios::end);
fsize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
//读取文件所有数据
body.resize(fsize);
ifs.read(&body[0], fsize);
if(!ifs.good())
{
LOG(ERROR, "file read failed!\n");
ifs.close();
return false;
}
//关闭文件
ifs.close();
return true;
}