I am pretty new to concept of file handling. I am trying to make a To-do list which keeps tracks of every modification in a file. I was unsure on how to implement this so I made a simple linked list and tried reading and writing it to a file but I failed. Here's my code ->
#include <iostream>
#include <fstream>
struct node{
    int val;
    node *next = NULL;
};
void add(node *&head, int val){
    node *newPtr = new node;
    if(head==NULL){
        newPtr->val = val;
        head = newPtr;
    }
    else{
        newPtr->val = val;
        newPtr->next = head;
        head = newPtr;
    }
}
void print(node *head){
    node *temp;
    temp = head;
    while(temp!=0){
        std::cout << (*temp).val << " ";
        temp = temp->next;
    }
    std::cout << std::endl;
}
int main(){
    node *head = NULL;
    int val;
    std::ofstream filout;
    filout.open("data.txt",std::ios::out|std::ios::app|std::ios::binary);
    while(true){
        std::cin>>val;
        if(val==0)
            break;
        else{
            add(head,val);
            filout.write((char*)&head, sizeof(head));
        }
    }
    std::ifstream filin;
    filin.open("data.txt",std::ios::in|std::ios::binary);
    filin.read((char*)&head, sizeof(head));
    print(head);
    return 0;
}
What modifications should I be making to my code in order to get this correct ?
Aucun commentaire:
Enregistrer un commentaire