0

I have tried very much to write and read linked list in file but couldn't succeed. The file is written to successfully but my program cannot read the linked list from file.

This is my code:

case 2:
    temp = first;
    while (temp != NULL)
    {
        temp->output(temp);
        temp = temp->next;
    }
    break;
case 3:  // for write in file
    fstream file;
    file.open("group.dat", ios::app | ios::out | ios::in | ios::binary);
    {
        temp = first;
        while (temp != NULL)
        {

            file.write(reinterpret_cast<char*>(&temp), sizeof(user));

            temp = temp->next;
        }
    }

    exit(-1);
case 4:  // for Read from file
    fstream file;
    file.open("group.dat", ios::app | ios::out | ios::in | ios::binary);
    file.seekg(0);

    while (!file.eof())
    {
        file.read(reinterpret_cast<char*>(&temp), sizeof(user));

    }
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
zee_k
  • 1
  • 1
    `file.write(reinterpret_cast(&temp), sizeof(user));` What is `temp`? If it's a pointer, why are writing the address of a pointer to a file? And why binary file writing? If whatever you're writing is a non-POD type, that line isn't going to work even if you fix the `temp` issue. – PaulMcKenzie May 29 '15 at 19:46
  • And it seems you almost can't not mention the very high probability that `while (!file.eof())` [is wrong as well](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – WhozCraig May 29 '15 at 19:53
  • "user" is name of class and "temp" is node of linkedlist. I also write (temp) instead of (&temp). it works but writes an extra node with garbage value in file. – zee_k Jun 14 '15 at 19:28

0 Answers0