My code is supposed to read file and store its contents in a linked list. Then, search for the user input word and print its location. Here is my try on it. I am kind of confused with the strcmp as well. Another thing i am not sure about is how to print the node (index) in the linked list where the word is found.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list {
char *string;
struct list *next;
};
typedef struct list LIST;
int main() {
FILE *fp;
char line[128];
LIST *current, *head;
head = current = NULL;
fp = fopen("words.dat", "r");
while(fgets(line, sizeof(line), fp)){
LIST *node =(LIST*) malloc(sizeof(LIST));
node->string = strdup(line);//note : strdup is not standard function
node->next =NULL;
if(head == NULL){
current = head = node;
} else {
current = current->next = node;
}
}
fclose(fp);
//test print
for(current = head; current ; current=current->next){
printf("%s", current->string);
}
//searching for a word
char string[50];
printf("\nEnter the word to be searched\n");
scanf("%s",&string);
LIST *tp1;
int flag;
tp1 = head;
while(tp1 != NULL)
{
if(strcmp(tp1->string,string)==0)
{
flag = 0;
printf("%d",(tp1->string)) ;
break;
}
tp1 = tp1->next;
}
if (flag)
printf("\nThe name to be searched is not in the linked list\n");
else
printf("\nThe name to be searched is in the linked list\n");
return 0;
}