2014-05-12 2 views
-4

장치의 벡터로 수행하는 데비 스리스트를 만들고 싶을 때이 문제가 발생합니다. 하지만 제대로 읽고 쓸 수는 없습니다.개체의 벡터를 파일에 쓰거나 읽는 데 문제가 있습니다.

이 제 기능입니다 :

#include "Devicelist.h" 

bool Devicelist::AddDevice(const char *deviceName, char *type) 
{ 
    Device tempDevice(deviceName, type, ++id_); 
    Devicelist_.push_back(tempDevice); 
    return true; 
} 

bool Devicelist::deleteDevice(const char *deviceName) 
{ 
    for (int i = 0; i < Devicelist_.size(); i++) 
    { 
     if (strcmp(deviceName, Devicelist_[i].getName()) == 0) 
     { 
      Devicelist_.erase(Devicelist_.begin() + i); 
      return true; 
     } 
     else 
     { 
      cout << "No Device found with that Devicename." << endl; 
      return false; 
     } 
    } 
} 

bool Devicelist::SaveToFile() 
{ 
    //remove("Devices.dat"); 

    ofstream SaveFile("Devices.dat", ios::out | ios::binary); 

    if (!SaveFile) 
    { 
     cerr << "File could not be opened." << endl; 
     return false; 
    } 
    for (int i = 0; i < Devicelist_.size(); i++) 
     SaveFile.write((const char *)(&Devicelist_[i]), sizeof(Devicelist_[i])); 


    SaveFile.close(); 
    return true; 
} 

bool Devicelist::LoadFromFile() 
{ 
    ifstream LoadFile("Devices.dat", ios::in | ios::binary); 

    if (!LoadFile) 
    { 
     cerr << "File could not be opened." << endl; 
     return false; 
    } 

    for (int i = 0; i < Devicelist_.size(); i++) 
     LoadFile.read((char *)(&Devicelist_[i]), sizeof(Devicelist_[i])); 


    LoadFile.close(); 
    return true; 
} 

Device Devicelist::findDevice(const char *deviceName) 
{ 
    for (int i = 0; i < Devicelist_.size(); i++) 
    { 
     if (strcmp(deviceName, Devicelist_[i].getName()) == 0) 
      return Devicelist_[i]; 
     else 
      cout << "Couldn't find device." << endl; 
    } 
} 

그리고 이것은 내 주요입니다 :

#include "Devicelist.h" 

void main() 
{ 
    Devicelist list; 
    list.AddDevice("Lampe3", "Lampe"); 
    list.AddDevice("Lampe4", "Lampe"); 
    list.SaveToFile(); 


    Devicelist list2; 
    list2.LoadFromFile(); 

    Device lampe = list2.findDevice("Lampe"); 

    cout << lampe.getName() << endl; 
    cout << lampe.getID() << endl; 
    cout << lampe.getType() << endl; 
} 

사람이 내 문제가 무엇인지 볼 수 있을까요?

미리 감사드립니다.

EDIT1 :

Devicelist에 대한 나의 .H 파일은 다음과 같습니다

#ifndef DEVICELIST_H 
#define DEVICELIST_H 

#include "Device.h" 
#include <vector> 
#include <string> 
#include <iostream> 
#include <fstream> 

class Devicelist 
{ 
public: 
    Devicelist(); 
    bool SaveToFile(); 
    bool LoadFromFile(); 
    bool AddDevice(const char *deviceName, char *type); 
    bool deleteDevice(const char *deviceName); 
    Device findDevice(const char *devicename); 
private: 
    vector<Device> Devicelist_; 
    int id_; 
}; 

#endif 

이 내 장치 .H-파일입니다

#ifndef DEVICE_H 
#define DEVICE_H 

#include <iostream> 
#include <string> 

#define DNAME_SIZE 33 

using namespace std; 

class Device 
{ 
public: 
    Device(const char *devicename = "Default", char *type = "type", int id = 0); 
    const char *getName(); 
    int getID(); 
    int getType(); 
private: 
    char deviceName_[DNAME_SIZE]; 
    int id_; 
    int type_; 
}; 

#endif 

그리고 장치의 .cpp 파일 :

#include "Device.h" 

Device::Device(const char *deviceName, char *type, int id) 
{ 
    strncpy_s(deviceName_, deviceName, DNAME_SIZE); 

    if (type == "Lampe") 
     type_ = 1; 
    else if (type == "Roegalarm") 
     type_ = 2; 
    else if (type == "Tyverialarm") 
     type_ = 3; 
    else 
    { 
     type_ = 0; 
     cout << "Type does not exists." << endl; 
    } 

    id_ = id; 
} 

const char *Device::getName() 
{ 
    return deviceName_; 
} 

int Device::getID() 
{ 
    return id_; 
} 

int Device::getType() 
{ 
    return type_; 
} 

문제는 암탉 내가 파일에 저장되는 내용보기를 읽으려고, 이것은 출력 : http://imgur.com/P8WEAKq

+2

** ** 귀하가 직면 한 문제는 무엇입니까? – streppel

+0

컴파일러 오류가 발생합니까? –

+0

'DeviceList.h '를 게시하십시오. – PaulMcKenzie

답변

0

문제는 LoadFromFile 기능에 여기, 내 생각 :

for (int i = 0; i < Devicelist_.size(); i++) 
    LoadFile.read((char *)(&Devicelist_[i]), sizeof(Devicelist_[i])); 

DeviceList이 비어, 또는이 잘못된 크기. 당신은 AddDevice에서와 비슷한 작성할 수

Device tempDevice(); 
LoadFile.read((char *)(&tempDevice), sizeof(tempDevice)); 
Devicelist_.push_back(tempDevice); 

을하지만 파일의 크기 (얼마나 많은 장치) 알려진해야합니다.

주석에서 언급했듯이 Device에 다른 개체에 대한 포인터가없는 경우에만 작동합니다. 그것은 POD (Plain Old Data) 객체 여야합니다.

우아한 솔루션은 Device::StoreToFile 각 장치를 쓰기 전에 장치의 수를 적게 할 필요가있을 것이다 Device

+0

'sizeof (tempDevice)'는 아마 혼동을 피하기 위해'sizeof (Device)'여야합니다. 비록이 방법으로 데이터를 직렬화 하였지만, 아주 나쁜 충고를 하시길! –

+0

@ πάντα ῥεῖ'sizeof (tempDevice)'는 대부분의 컴파일러에서 작동합니다. 더 쉽기 때문에 사용합니다. 네, 더 나은 해결책이 있습니다. 방금 제안을 추가했습니다. – alain

0

스트리밍 통신을 구현하는 것입니다. 이렇게하면 Device::LoadFromFile에서 파일에서 읽을 장치 인스턴스 수를 알 수 있습니다.

파일의 비트에 대한 클래스 또는 구조 비트를 쓰지 말 것을 강력히 권장합니다. 클래스 또는 구조체에 std::string 또는 std::vector과 같은 고급 데이터 구조가있는 경우 이진 형식으로 쓸 수 없습니다. 그들은 메모리에 포인터를 사용할 수 있습니다. 포인터는로드 할 때 같지 않습니다.

더 나은 해결책은 다음과 같습니다.
1. uint8_t의 버퍼를로드 및 저장 메소드에 전달하십시오.
2. 메서드는 버퍼 또는 저장소에서로드 (append)합니다.
3. 호출자가 버퍼를 읽거나 파일에 씁니다.
4.클래스에는 구조체 크기와 다를 수있는 파일에있는 공간을 반환하는 "파일에 크기"메서드도 있습니다.

웹에서 "boost :: serialization"을 검색하십시오.

관련 문제