Ifstream read function doesn't load into vector

前端 未结 2 1712
既然无缘
既然无缘 2021-01-26 21:20

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

2条回答
  •  不知归路
    2021-01-26 21:37

    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++)
    

    should be

    LoadFile.seekg(0, ios::end);
    int numberOfDevices = LoadFile.tellg() / sizeof(Device);
    LoadFile.seekg(0L, ios::beg);
    for (int i = 0; i < numberOfDevices; i++)
    

    An alternative to finding the number is using stat:

    #include 
    int getNumberOfDevices(char *filename)
    {
        struct stat st;
        return st.st_size / sizeof(Device);
    }
    

    or, if you wanted to avoid stat, you could do something like this:

    bool Devicelist::LoadFromFile() //Opdaterer vector 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(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.

提交回复
热议问题