Обработка файлов с помощью LinkList в переполнении стека

ПРОБЛЕМА: Я пытаюсь записать (двоичный файл) объект двусвязного списка в файл & пиши и с этого тоже.
Мне нужно написать полное содержимое объекта, затем загрузить его из файла и сохранить в новом объекте, чтобы заново создать список в порядке FIFO.
Я думаю, что пишу правильно, но я серьезно не знаю, как загрузить (прочитать) его из файла.

ПОМНИТЕ: Я просто пытаюсь сохранить и прочитать CONTENTS узла, & NOT POINTERS.

КОД:

//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();
}
//-------------------

НЕТ ОШИБКИ КОМПЛЕКТАЦИИ.

ОШИБКА ВЫПОЛНЕНИЯ: Необработанное исключение в 0x00CD8391 в DobulyList.exe: 0xC0000005: Место записи нарушения прав доступа 0x00000004.

3

Решение

Я думаю, что вам лучше всего иметь метод класса BOOK, который может сериализовать содержимое заранее определенным способом.

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

....

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

....

};

Итак, поскольку вам нужен двоичный файл — вам нужно написать и 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

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector