我试图读取位于所需位置的二进制文件。实际上,我正在尝试从中读取一个类并将数据放入列表中,为此我创建了一个函数。这是该函数的主体。
list <string> getlist() {
list <string> menu;
string name = "test.bin";
ifstream infile;
infile.open((char*)(&name), ios::binary);
if (!infile.is_open())
cout << "error1"; // brinting error
Elements elements = {};
infile.read((char*)&elements, sizeof(Elements));
for (int i = 0; i < 3; i++) {
menu.push_back(elements.item1);
}
infile.close();
return menu;
}
虽然整个过程成功完成,但执行了错误消息,并且该函数将数据返回到列表中!!
if (!infile.is_open())
cout << "error" << endl; // brinting error
为了使用流对象打开文件,这是功能定义:
void open (const char * filename, openmode mode);
请更新以下行:
infile.open((char*)(&name), ios::binary);
to
char name[]="test.bin";
infile.open(name, ios::binary);
您需要更改此:
infile.open((char*)(&name), ios::binary);
为此,改为:
infile.open(name.c_str(), ios::binary);
强制类型转换std::string
对象的地址不会为您提供有效的指向字符串字符数据的指针。这就是字符串的c_str()
(和data()
)方法的用途。
如果使用的是C ++ 11或更高版本的编译器,则甚至不需要直接访问字符数据,因为open()
具有一个以std::string
作为输入的重载:
infile.open(name, ios::binary);
[无论哪种方式,如果is_open()
返回false,那么之后都不要继续调用read()
。 elements
的内容将无效。您没有检查这种可能性,例如:
if (!infile.is_open())
{
cout << "error opening the file";
return menu; // <-- ADD THIS!
// or better, 'throw' an exception instead...
}
if (!infile.read((char*)&elements, sizeof(Elements))) // <-- ADD FAILURE CHECK!
{
cout << "error reading from the file";
return menu; // <-- ADD THIS!
// or better, 'throw' an exception instead...
}
...
[除此之外,您对infile.read()
的使用值得怀疑,这取决于Elements
类的实际声明方式,您没有显示。很多时候,读取这样的整个类并不安全。您正在尝试将std::string
对象存储在std::list
中,因此,除非Elements::item1
成员是固定大小的char[]
数组,否则您对read()
的使用可能无法按预期方式工作。