Ifstream读取函数不加载到向量 [英] Ifstream read function doesn't load into vector
问题描述
我是一个新的编程,所以我不知道如何搜索这个问题,我知道我问了其他2个问题,但我似乎无法使它工作。
I'm somewhat new to programming, so I'm not sure how to search for this problem, and I know I asked 2 other questions about this, but I can't seem to make it work.
我有一个问题,其中有一个向量:
I got a problem, where I have a vector:
vector<Device*> Devicelist_;
在这里我尝试加载设备使用此功能(我已经做了一个保存功能, ):
Whhere I try to load Devices into using this function (I already made a Save-function, which works):
bool Devicelist::LoadFromFile() //Opdaterer vector<Device> fra fil
{
ifstream LoadFile("Devices.dat", ios::in | ios::binary);
if (!LoadFile)
{
cerr << "File could not be opened." << endl;
return false;
}
LoadFile.seekg(0, ios::end);
int numberOfDevices = LoadFile.tellg() / sizeof(Device);
for (int i = 0; i < numberOfDevices; i++)
{
Devicelist_.push_back(new Device);
LoadFile.read(reinterpret_cast<char *>(Devicelist_[i]), sizeof(Device));
}
cout << Devicelist_[0]->getName() << endl;
LoadFile.close();
return true;
}
问题是 LoadFile.read / code>不会将任何设备加载到设备列表中。
The problem is that LoadFile.read()
does not load any Devices into the devicelist.
你能看到我的问题是什么?先感谢。
Can you see what my problem is? Thanks in advance.
推荐答案
您的问题其实很简单。您忘记了重置您的获取位置:
Your problem is actually really simple. You forgot to reset your get position:
LoadFile.seekg(0, ios::end);
int numberOfDevices = LoadFile.tellg() / sizeof(Device);
for (int i = 0; i < numberOfDevices; i++)
应为
LoadFile.seekg(0, ios::end);
int numberOfDevices = LoadFile.tellg() / sizeof(Device);
LoadFile.seekg(0L, ios::beg);
for (int i = 0; i < numberOfDevices; i++)
查找数字是使用stat:
An alternative to finding the number is using stat:
#include <sys/stat.h>
int getNumberOfDevices(char *filename)
{
struct stat st;
return st.st_size / sizeof(Device);
}
或者,如果你想避免stat,你可以这样做:
or, if you wanted to avoid stat, you could do something like this:
bool Devicelist::LoadFromFile() //Opdaterer vector<Device> fra fil
{
ifstream LoadFile("Devices.dat", ios::in | ios::binary);
if (!LoadFile)
{
cerr << "File could not be opened." << endl;
return false;
}
int numberOfDevices = 0;
while (true)
{
Device *tmp = new device;
LoadFile.read(reinterpret_cast<char *>(tmp), sizeof(Device));
if (LoadFile.good()) //we successfully read one
{
++numberOfDevices;
Devicelist_.push_back(tmp);
}
else break; //get out of the infinite loop
}
cout << Devicelist_[0]->getName() << endl;
LoadFile.close();
return true;
}
这样,它读取所有的,而不会弄乱位置,保存计数完成后。
This way, it reads all of them, without messing around with positions, and keeps a count when it is finished.
这篇关于Ifstream读取函数不加载到向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!