Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node nodeType; //data structure
struct node
{
char name;
nodeType *next;
};
//adds a new character in the linked list with each character read.
nodeType*
chinsert(nodeType* ptr,char c)
{
nodeType *p;
nodeType *new = (nodeType *)(malloc(sizeof(struct node))); //malloc to create the memory space that's needed to store the new character.
new->name = c;
new->next = NULL;
if(ptr==NULL)
return new;
else
{
for(p=ptr; p->next!=NULL; p=p->next);
p->next= new;
return ptr;
}
}
//When EOF is detected, traverse the linked list printing out the list of characters stored in the list
void
prnList(nodeType *ptr)
{
nodeType *n = ptr;
printf("\n");
while(n != NULL)
{
printf("%c",n->name);
n = n->next;
}
printf("\n");
}
//add underscore replacing space key
void
prn(nodeType *ptr)
{
nodeType *n = ptr;
while(n != NULL)
{
if(n->name == ' ')
printf("%c",n->name='_');
else
printf("%c",n->name);
n = n->next;
}
printf("\n");
}
//return any memory used back to the system before to the system before exiting program.
void
cleanUp(nodeType *ptr)
{
nodeType *n;
while(ptr->next != NULL)
{
n = ptr->next;
ptr->next = n->next;
free(n);
}
n = ptr;
free(n);
}
int
main(int argc, char *argv[])
{
char c;
nodeType *ptr = NULL;
while((c=getchar())!=EOF) //loop that reads in a character at a time, terminating the loop when it sees an EOF.
{
ptr = chinsert(ptr,c);
}
prnList(ptr);
prn(ptr);
cleanUp(ptr);
return 0;
}
this program uses linked list to print the input replacing the space key with underscore.
how do i modify this program so it takes lines from a file?
do i just replace getchar with fgets?