2012-11-01 1 views
3

문제 : 이중 연결 목록의 개체를 & 파일에 쓰려고합니다 (이진 쓰기). 개체의 전체 내용을 작성한 다음 파일에서로드하고 새 개체에 저장하여 FIFO 순서로 목록을 다시 작성해야합니다. 나는 올바르게 쓰고 있다고 생각하지만, 파일에서 어떻게 읽어들이는지 전혀 모른다.C++에서 LinkList를 사용한 파일 처리

기억 : 그냥 저장하고 노드의 CONTENTS을 읽으려고하고, & NOT POINTERS.

CODE :

//template type BOOK class 

template<class mytype> 
class BOOK  
{ 
private: 
    static int count; //declaration of static variable to set ID for books 
public: 
    BOOK<mytype> *next, *prev; //BOOK type pointers; 'next' to store address of 
next BOOK & 'prev' to store address of previous BOOK 
    int ID;   //variable to store ID of a book 
    string bookName;//string to store name of a book 
    string author; //string to store name of author of book 
    string book_type;//string to store type of a book 
    long copies; //variable to store no. of copies a book 
    long price;  //variable to store price of a book 
    string status; //to store status of a book, either its in stock or not 
    dynamicQueue<string> book_queue; //created an object of queueClass as data member of each Book 

    BOOK() //Constructor 0 argument to initialize everything 
    { 
     count++; //increment counter 
     ID=count; //assign counter to ID to be ID of newly added book 

     next = prev = 0;  //Initializing both pointers to 0 

     bookName = "\0"; 
     author = "\0"; 
     book_type = "\0"; 
     copies = price = 0; 
     status= "InStock"; 
    } 

    BOOK(BOOK *n = 0, BOOK *p = 0, string book = "\0", string athr = "\0", string buk_type = "\0", long cp=0, long pr=0) //Constructor multiple arguments, to store information about a book 
    { 
     next = n;  //store contents of user-given value n into next 
     prev = p;  //store contents of user-given value p into previous 

     bookName = book;//store contents of user-given value book into bookName 
     author = athr; //store contents of user-given value athr into author 
     book_type = buk_type;//store contents of user-given value buk_type into book_type 
     copies = cp; //store contents of user-given value cp into copies 
     price = pr;  //store contents of user-given value pr into price 
     status= "InStock"; 
     count++;  //increment counter 
     ID=count;  //assign counter to ID to be ID of newly added book 
    } 
}; 

template <class mytype> // declaration of 
int BOOK<mytype>::count=0; // static variable to set ID for books 
//-------------------- 

주요 부분을 새로운 책을 추가합니다. 기능을 저장

BookStoreDataBase<char> obj; //created object of Doubly linked list 
string Book, Author, Booktype; 
long Copies=1, Price=0; 
cout<<"Enter Name of Book = "; cin>>Book; 
cout<<"Enter Author = ";  cin>>Author; 
cout<<"Enter Type of Book = "; cin>>Booktype; 
cout<<"Enter Number of Copies = "; cin>>Copies; 
cout<<"Enter Price (PKR) = "; cin>>Price; 

obj.addBook(Book, Author, Booktype, Copies, Price); 

는 이제 저장된 배열을 방해하여 각 노드 &로 파일 목록 저장 내용을 읽는 방법에 실질적으로 아무 생각이

template <class mytype> 
void DoublyLinkedList<mytype>::save_data() 
{ 
    NODE<mytype> * temp = head; //made copy of head 
    fstream file;  //created new file 
    file.open("mydata.txt", ios::binary | ios::out | ios::app); 

    while(temp->next!=0) //Until link list end 
    { 
      file.write(reinterpret_cast<char*>(&temp), sizeof(temp)); 
      temp = temp - > next; //move temp to next node 
    } 
    file.write(reinterpret_cast<char*>(&temp), sizeof(temp)); //write again for last 
                   //book's data 
    file.close(); 
} 

을 파일에 모든 데이터를 저장합니다 목록을 FIFO 순서대로 다시 만듭니다. 그래서 나중에 인쇄 할 수 있습니다. 나는 많은 연습을했지만 포럼 등으로 갔지만 구체적인 해결책을 찾지 못했습니다. 제발 도와주세요. 사전


내 노력

template <class mytype> 
void DoublyLinkedList<mytype>::load_data() 
{ 
    fstream file; 
    file.open("mydata.txt", ios::binary | ios::in); 
    while(!file.eof()) 
    { 
     NODE<mytype> *temp = new NODE<mytype>; 
     file.read(reinterpret_cast<char*>(&temp), sizeof(temp)); 
     if(is_Empty()) 
     { 
      head = tail = temp; 
     } 
     else 
     { 
      temp->prev->next = temp; 
      temp->next=0; 
     } 
    } 
    file.close(); 
} 
//------------------- 

NO 컴파일시 에러의 샘플 감사드립니다.

런타임 오류 : DobulyList.exe의 0x00CD8391에서 처리되지 않은 예외 : 0xC0000005 : 0x00000004 위치 쓰기 액세스 위반입니다.

+0

std :: strings가 포함 된 클래스를 이진 파일로 쓰고 문자열 데이터를 출력에 포함시킬 수 있다고 생각하지 않습니다. Book이 템플릿 클래스 인 이유는 무엇입니까? – Scooter

+0

Book 클래스는 독창적 인 DoublyClass (DataBase Class)와 함께 사용되어 단일 노드/책을 관리하는 NODE 클래스 또는 구조체처럼 작동합니다. – InamTaj

답변

0

미리 정의 된 방식으로 내용을 serialize 할 수있는 BOOK 클래스의 메서드를 사용하는 것이 가장 좋습니다. 이진 원하기 때문에

template<class mytype> 
class BOOK  
{ 
private: 
    //members 
public: 
    //more members 

    .... 

    bool read(istream& in); 
    bool write(ostream& out); 

    .... 

}; 

그래서 - 당신은

그런 다음 당신이이 역 ... 문자열 (들) 등을위한 바이트, 가지고와 ID, 다음 크기를 위해 작성하는 int 필요할 것 독서. int를 읽은 다음 읽기 크기, ID에 할당 크기의 문자를 읽고 문자열 등에 할당 ...

예를 들어

//fill in template stuff I'm lazy... 
bool Book::read(istream& in) 
{ 
    size_t stringSize; //you need to think about what types you read/write 
    char buffer[SomeArbitrarySize]; 
    file.read(ID ,sizeof(int)); 
    file.read(stringSize ,sizeof(size_t)); 
    file.read(buffer, stringSize); 
    mStringMember = buffer; 
    ... etc ... 
} 

는 목록의 각 항목에 대한 읽기에 대한 호출을 위임/노드에 쓰기. 노드 수만큼 항목을 쓰거나 읽고 싶을 수도 있습니다.

template <class mytype> 
void DoublyLinkedList<mytype>::load_data() 
{ 
    fstream file; 
    file.open("mydata.txt", ios::binary | ios::in); 
    while(!file.eof()) 
    { 
     NODE<mytype> *temp = new NODE<mytype>; 
     temp->read(file); 
     if(is_Empty()) 
     { 
      head = tail = temp; 
     } 
     else 
     { 
      temp->prev->next = temp; 
      temp->next=0; 
     } 
    } 
    file.close(); 
} 
+0

Bro 나는 방금 말한 것을 이해하지 못했습니다. D count는 _BookStoreDatabase Class_에서 책을 만들 때마다 증가 할 정적 변수입니다.& 증분되면 책의 노드에 ID의 사본을 넣습니다. 따라서 책의 ID가 자동으로 생성됩니다. 샘플 : 도서 ID 1 -> OOP in C++ 도서 ID 2 -> DataStructures in C++ 또한 책을 ID #, 이름으로 또는 저자별로 검색하려면 _BookStoreDataBasse Class_에 메소드를 작성했습니다. – InamTaj

+0

좋아, 내가 게시했을 때 나는 서두른 상태였다. 즉, Book 클래스의 각 요소가 미리 정해진 순서대로 파일에 개별적으로 쓰여지고 동일한 순서로 다시 읽혀질 필요가 있다는 것을 의미한다. 나는 대답을 더 읽기 쉽게 만들 것이다 ... – Caribou