Saturday, September 28, 2013

C Programming: Linked Lists To File

Leave a Comment
C Programming: Linked Lists To File. This program creates a linked list of 5 integers and stores it in a txt file. The function -linkedlisttofile() (accepts the linked list as a parameter). This function opens a file list.txt and copies the element in the linked list to the file.


#include <stdio.h>
#include <conio.h>
#include <stdlib.h>


typedef struct node
{
        int n;
        struct node *next;
}*List;

void linkedlisttofile(List L);
int main()
{
    int ctr, num;
    List L, *trav, p;
   
    L = NULL;
    L = (List)malloc(sizeof(struct node));
    *trav = L;
   
    printf("Enter 5 integers: ");
    for(ctr = 0; ctr < 5; ctr++)
    {
            scanf("%d", &(*trav)->n);
            (*trav)->next = (List)malloc(sizeof(struct node));
            *trav = (*trav)->next;
    }
    (*trav)->next = NULL;
    printf("\nContents of the List: ");
    for(p = L; p->next != NULL; p = p->next)
    {
          printf("%d ", p->n);
    }
   
    linkedlisttofile(L);
    printf("\n\nFile Copy Complete!");
    getch();
    return 0;
}
void linkedlisttofile(List L)
{
     FILE *fp;
     List p;
    
     fp = fopen("list.txt", "w");
    
     for(p = L; p->next != NULL; p = p->next)
     {
          fprintf(fp, "%d ", p->n);
     }
     fclose(fp);
}

Here's the output of the program: 



0 comments:

Post a Comment