how to copy/print the linkedlist node data into a file?
// code
#include<stdio.h>
#include<stdlib.h>
struct linkedlist{
int data;
struct linkedlist *next;
};
int main()
{
int i=1;
// form a single linked list having numbers from 1 to 10
struct linkedlist *point=NULL,*head=NULL,*temp;
point=(struct linkedlist*)malloc(sizeof(struct linkedlist));
point->data=i;
head=point; // to store the address of first node
for(i=2;i<=10;i++)
{
point->next=(struct linkedlist*)malloc(sizeof(struct linkedlist));
point->next->data=i;
point=point->next;
point->next=NULL;
}
FILE *fp; // create a file pointer
fp = fopen("./test.txt", "w"); // open the file in write mode
temp=head;
while(temp!=NULL) // traverse along the linked list
{
fprintf(fp,"%d ",temp->data); // print the content of linked list in file test.txt
temp=temp->next;
}
fclose(fp); // close the file
return 0;
}
1 Like