hello every body
i want to know how to save a linked list int a text file and how to load a file in a linked list ??
any one can help me and give me a simple example code
thanks in advance

Dani AI

Generated

Good starts from and — both the simple record-per-line idea and using XML/structured text are valid choices. The single, most important rule is: never save raw pointer values. Persist only the node data and any identifiers you will use to re-link nodes when loading.

A practical plan:

  • Pick the on-disk format first (plain text CSV/JSON/XML for readability, or a compact binary format for speed). Add a tiny header with a format/version number so future changes can be detected.
  • For simple singly-linked lists write either a count or stream records in order. For strings use length-prefixing or proper escaping so embedded newlines or separators do not corrupt the record.
  • For graphs or lists with cross-links, assign each node a stable ID when writing. Write nodes (ID + data) first, then write references as IDs. On load, create all nodes, store them in a map by ID, then do a second pass to resolve references.

Example (binary, int + string fields — demonstrates length-prefixing and re-linking):

struct Node { int value; std::string name; Node* next; };

void save(Node* head, const std::string& fn) {
    std::ofstream ofs(fn, std::ios::binary);
    for (Node* p = head; p; p = p->next) {
        uint32_t len = uint32_t(p->name.size());
        ofs.write(reinterpret_cast<char*>(&p->value), sizeof(p->value));
        ofs.write(reinterpret_cast<char*>(&len), sizeof(len));
        ofs.write(p->name.data(), len);
    }
}

Node* load(const std::string& fn) {
    std::ifstream ifs(fn, std::ios::binary);
    Node* head = nullptr; Node* tail = nullptr;
    while (true) {
        int value;
        if (!ifs.read(reinterpret_cast<char*>(&value), sizeof(value))) break;
        uint32_t len; ifs.read(reinterpret_cast<char*>(&len), sizeof(len));
        std::string name(len, '\0'); ifs.read(&name[0], len);
        Node* n = new Node{value, name, nullptr};
        if (!head) head = tail = n; else tail->next = n, tail = n;
    }
    return head;
}

Cautions and tips: use fixed-width integer types to avoid platform differences; binary formats must consider endianness and struct padding; text formats need escaping or quoting rules. For production code, consider Boost.Serialization or cereal to avoid boilerplate and get versioning/pointer-handling for free. 's prompt about the data shape is the right next question — the exact format should follow the node fields you actually need to persist.

Recommended Answers

All 3 Replies

Too many possible options to say the best way. Here is one way: For writing:
write a header into the file, something like "<singly linked list follows>"
iterate through the linked list writing one item per line
write a footer into the file, something like "<end of singly linked list>"
Then, when reading, look for the header, and append an element for each line until you see the footer.
Of course you still have issues about how to encode/decode the actual data. You could end up reinventing SOAP (or CORBA) if you aren't careful!

griswolf is heading in the right direction. Use an XML structure for your collection, which is basically what a singly linked list is, an ordered collection of similar things/objects. That's very easy in XML form:

<list>
    <element>
        <field1>1</field1>
        <field2>my name</field2>
    </element>
    <element>
        <field1>2</field1>
        <field2>your name</field2>
    </element>
    .
    .
    .
</list>

So, you walk through the list, writing each element and its data members as you go. To reconstitute the list, each time you find the opening <element> tag (or whatever you name it), you allocate a buffer of the appropriate structure type, then for each field in the element, you parse out the data as a string, and convert if necessary, setting the appropriate structure member field. If it is the first element, it becomes the head of the list, and each subsequent element in the list is linked to the previous one. Voila! You have now reconstituted your list from the text (xml) file.

FWIW, I have had to do this numerous times in my work as a software engineer, so perhaps it is second nature to me. In any case, if you do use XML, there are a lot of good C and C++ xml parsing tools such as xerces to use.

What does you data look like?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.