Advertisement
Patrickquinn1212

Reading and writing a linked list to a file in C codevault

Sep 20th, 2022 (edited)
1,065
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //https://code-vault.net/lesson/nk297jhs1m:1641837289454
  4. typedef struct Node {
  5.     int x;
  6.     struct Node* next;
  7. } Node;
  8.  
  9. void deallocate(Node** root) {
  10.     Node* curr = *root;
  11.     while (curr != NULL) {
  12.         Node* aux = curr;
  13.         curr = curr->next;
  14.         free(aux);
  15.     }
  16.     *root = NULL;
  17. }
  18.  
  19. void insert_end(Node** root, int value) {
  20.     Node* new_node = malloc(sizeof(Node));
  21.     if (new_node == NULL) {
  22.         exit(1);
  23.     }
  24.     new_node->next = NULL;
  25.     new_node->x = value;
  26.  
  27.     if (*root == NULL) {
  28.         *root = new_node;
  29.         return;
  30.     }
  31.  
  32.     Node* curr = *root;
  33.     while (curr->next != NULL) {
  34.         curr = curr->next;
  35.     }
  36.     curr->next = new_node;
  37. }
  38.  
  39. void serialize(Node* root) {
  40.     FILE* file = fopen("list.txt", "w");
  41.     if (file == NULL) {
  42.         exit(1);
  43.     }
  44.  
  45.     for (Node* curr = root; curr != NULL; curr = curr->next) {
  46.         fprintf(file, "%d, ", curr->x);
  47.     }
  48.     fclose(file);
  49. }
  50.  
  51. void deserialize(Node** root) {
  52.     FILE* file = fopen("list.txt", "r");
  53.     if (file == NULL) {
  54.         exit(2);
  55.     }
  56.  
  57.     int val;
  58.     while(fscanf(file, "%d, ", &val) > 0) {
  59.         insert_end(root, val);
  60.     }
  61.     fclose(file);
  62. }
  63.  
  64. int main(int argc, char* argv[]) {
  65.     Node* root = NULL;
  66.     Node* root2 = NULL;
  67.  
  68.      insert_end(&root, -2);
  69.      insert_end(&root, 11);
  70.      insert_end(&root, 22);
  71.      serialize(root);
  72.     deserialize(&root);
  73.  
  74.     for (Node* curr = root; curr != NULL; curr = curr->next) {
  75.         printf("%d\n", curr->x);
  76.     }
  77.  
  78.     deallocate(&root);
  79.     // deallocate(&root2);
  80.  
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement