在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误

terminate called after throwing an instance of 'std::runtime_error' what(): I/O error with filebuf & ostream

本文关键字:Filebuf what 错误 ostream 实例 runtime std error 终止 调用      更新时间:2023-10-16

我正在尝试序列化几个文本文件,我有一个这样的函数:

void to_file_px(Ciphertext* encryptedPx, int index) {
// Serialize Pixel i
//red
filebuf* fbCipherR; // EDIT: THIS LINE IS PROBLEMATIC
string* filenameR = new string("../serialization/pixels/px" + to_string(index) + "R.txt");
fbCipherR -> open((*filenameR).c_str(), std::ios::out|std::ios::binary);
ostream* osCipherR = new ostream(fbCipherR);
encryptedPx[0].Ciphertext::save((*osCipherR));
fbCipherR -> close();
delete filenameR;
delete fbCipherR;
delete osCipherR;
//green
//blue
delete[] encryptedPx;
}

但是,此函数会导致错误,如Segmentation fault (core dumped)

我可以知道导致错误的确切原因吗?

注:Ciphertext::save来自海豹突击队Microsoft


好吧,我犯了一个错误。我没有初始化filebuf*.

所以我更改了filebuf* fbCipherR = new filebuf();,并收到一条新的错误消息:

terminate called after throwing an instance of 'std::runtime_error'
what():  I/O error
Aborted (core dumped)

您应该在堆栈而不是堆中分配变量,因为这样它们就是默认构造的并自动销毁。

filebuf fbCipherR;
string filenameR = "../serialization/pixels/px" + to_string(index) + "R.txt";
fbCipherR.open(filenameR.c_str(), std::ios::out|std::ios::binary);
ostream osCipherR(fbCipherR);
encryptedPx[0].Ciphertext::save(osCipherR);
fbCipherR.close();

程序已终止,因为存在未捕获的异常。您应该在每个线程中处理异常。如何捕获异常。

您的异常可能是由于打开文件失败,您应该在使用之前检查缓冲区/流的状态。

您可以通过使用ofstream而不是filebuf以及将所有内容放在堆栈上而不是堆分配来简化代码:

void to_file_px(Ciphertext* encryptedPx, int index) {
// Serialize Pixel i
//red
string filenameR = "../serialization/pixels/px" + to_string(index) + "R.txt";
ofstream osCipherR(filenameR.c_str(), std::ios::out|std::ios::binary);
if (!osCipherR)
{
std::cout << "error opening output filen";
}
else
{
encryptedPx[0].Ciphertext::save(osCipherR);
}
//green
//blue
delete[] encryptedPx;
}

尝试使用此方法初始化 filebuf。

std::ifstream is;
std::filebuf * fb = is.rdbuf();
fb->open ("test.txt",std::ios::out|std::ios::app);
// >> appending operations here <<
fb->close();

对于字符串,您不需要创建指向字符串的指针,因为您只是在此函数中使用字符串,只需像这样编写即可

//string* filenameR = new string("../serialization/pixels/px" + to_string(index) + "R.txt");
//use a local variable string instead of a "new" string since you are not using this string anymore after this function
string filenameR = "../serialization/pixels/px" + to_string(index) + "R.txt";