C Program to Read/Write Linked List to a File

In this article, we will discuss how we can read/write a linked list to a file in C programming language.

Given below is the structure of the node of the linked list that we are going to use in our example

struct node
{
	int val;
	char name[100];
	struct node *next;
};
Writing Linked List to a File

We are using FILE object and fwrite() to write data to the file.

  • FILE object have all the necessary information to control the file stream. It allows us to open a file and perform read/write operations on the file.
  • fwrite(const void *ptr, size_t size, size_t n, FILE *fp) write the data specified by ptr to the file fp.
    • ptr: points to the data we want to write.
    • size: size of data to be written in bytes.
    • n: number of items to be written.
    • fp: FILE pointer that points to the file in which we want to write the data.

Given below is the function that writes a linked list to a file. The function writes each node of the linked list to the file in serial order.

// function to write linked list to a file
void writeLinkedList(char filename[], node* head){
	
	struct node* temp = head;
	
	FILE* file;
	file = fopen (filename, "w");
    if (file == NULL)
    {
        fprintf(stderr, "\nCouldn't Open File'\n");
        exit (1);
    }
	
	// writing all the nodes of the linked list to the file
	while(temp!=NULL)
	{
		fwrite(temp, sizeof(struct node), 1, file);
		temp = temp->next;
	}
	
	if(fwrite != 0)
	{
		printf("Linked List stored in the file successfully\n");
	}
   	else
	{
   		printf("Error While Writing\n");
	}
	
	fclose(file);
	
}
Reading Linked List From a File

We used fread() to read each node of the linked list from the file one by one. We use these nodes to create a new linked list and after reading all the nodes from the file we return the head of the newly created linked list.

  • fread(void *ptr, size_t size, size_t n, FILE *fp)
    • ptr: address of the memory block where we want to store data after reading from the file.
    • size: size of data we want to read in bytes.
    • n: number of items we want to read.
    • fp: FILE pointer that points to the file from which we want to read the data.

Given below is the function that reads a linked list from a file and returns the head pointer.

struct node* readLinkedList(char filename[]){
	
	struct node* temp = (struct node *)malloc(sizeof(struct node));;
	struct node* head; // points to the first node of the linked list in the file
	struct node* last; // points to the last node of the linked list in the file
	last = head = NULL;
	
	FILE* file;
	file = fopen (filename, "r");
    if (file == NULL)
    {
        fprintf(stderr, "\nCouldn't Open File'\n");
        exit (1);
    }
	
	// reading nodes from the file
	// nodes are read in the same order as they were stored
	// we are using the data stored in the file to create a new linked list
	while(fread(temp, sizeof(struct node), 1, file))
	{
		
		if(head==NULL)
		{
			head = last = (struct node *)malloc(sizeof(struct node));
		}
		else
		{
			last->next = (struct node *)malloc(sizeof(struct node));
			last = last->next;
		}
		last->val = temp->val;
		strcpy(last->name, temp->name);
		last->next = NULL;
		
	}
	
	fclose(file);
	
	return head;
	
}
Complete Program
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct node
{
	int val;
	char name[100];
	struct node *next;
};

// function to display linked list
void displayLinkedList(struct node *root)
{
	struct node *temp = root;
	printf("\nLinkedList: ");
	while(temp!=NULL)
	{
		printf("%d %s -> ",temp->val, temp->name);
		temp = temp->next;
	}
	printf("NULL\n\n");
}

// insert node at the beginning of the linked list
struct node* insertAtBegin(node *head, int val, char *name)
{
	
	struct node *ptr;
	struct node *temp = (struct node *)malloc(sizeof(struct node));
	temp->val = val;
	strcpy(temp->name, name);
	temp->next = NULL;
	
	if(head==NULL)
	{
		head = temp;	
	}
	else 
	{
		temp->next = head;
		head = temp;
	}	
	
	return head;
	
}

// function to write linked list to a file
void writeLinkedList(char filename[], node* head){
	
	struct node* temp = head;
	
	FILE* file;
	file = fopen (filename, "w");
    if (file == NULL)
    {
        fprintf(stderr, "\nCouldn't Open File'\n");
        exit (1);
    }
	
	// writing all the nodes of the linked list to the file
	while(temp!=NULL)
	{
		fwrite(temp, sizeof(struct node), 1, file);
		temp = temp->next;
	}
	
	if(fwrite != 0)
	{
		printf("Linked List stored in the file successfully\n");
	}
   	else
	{
   		printf("Error While Writing\n");
	}
	
	fclose(file);
	
}

struct node* readLinkedList(char filename[]){
	
	struct node* temp = (struct node *)malloc(sizeof(struct node));;
	struct node* head; // points to the first node of the linked list in the file
	struct node* last; // points to the last node of the linked list in the file
	last = head = NULL;
	
	FILE* file;
	file = fopen (filename, "r");
    if (file == NULL)
    {
        fprintf(stderr, "\nCouldn't Open File'\n");
        exit (1);
    }
	
	// reading nodes from the file
	// nodes are read in the same order as they were stored
	// we are using the data stored in the file to create a new linked list
	while(fread(temp, sizeof(struct node), 1, file))
	{
		
		if(head==NULL)
		{
			head = last = (struct node *)malloc(sizeof(struct node));
		}
		else
		{
			last->next = (struct node *)malloc(sizeof(struct node));
			last = last->next;
		}
		last->val = temp->val;
		strcpy(last->name, temp->name);
		last->next = NULL;
		
	}
	
	fclose(file);
	
	return head;
	
}

int main() {

	struct node *head = NULL;
    head = insertAtBegin(head, 1, "John");
    head = insertAtBegin(head, 3, "George");
    head = insertAtBegin(head, 6, "Ravil");
    
    displayLinkedList(head);
    writeLinkedList("Hello.txt", head);
    
	printf("\nReading Linked List from the file!!\n");
	struct node* newHead = readLinkedList("Hello.txt");
	printf("\nPrint the New Linked List\n");
	displayLinkedList(newHead);
}

Output

LinkedList: 6 Ravil -> 3 George -> 1 John -> NULL

Linked List stored in the file successfully

Reading Linked List from the file!!

Print the New Linked List

LinkedList: 6 Ravil -> 3 George -> 1 John -> NULL

References

Leave a Comment

Your email address will not be published. Required fields are marked *