I wrote a function to write the linked list data to a file, when I write main()
and the WriteData()
in a single file, then it works just fine. But when I write the WriteData()
in a different file and include it in main
file using a header file, it gives me segmentation fault. Here's my code
abcd.h:
#ifndef _ABCD_H_
#define _ABCD_H_
struct node{
char word[50];
char sort[50];
struct node *next;
}
void WriteData(struct node *head);
void read_data(struct node **head, FILE *fp);
#endif
main.c:
#include"abcd.h"
int main(int argc, char *argv[]) //file is given as command line argument
{
FILE *fp = fopen(argv[1], "r");
struct node *head = NULL;
read_data(&head, fp); //loads the contents of the file to the list
WriteData(head);
}
writeData.c:
#include"abcd.h"
void WriteData(struct node *head)
{
FILE *fp = fopen("dictionary.txt", "w");
if(fp == NULL){
printf("Error opening file..\n");
return;
}
while(head != NULL){
fprintf(fp, "\n%s:", head->word);
fprintf(fp, "%s", head->sort);
head = head->next;
}
fclose(fp);
printf("Data saved successfully..\n");
}
readData.c:
#include "abcd.h"
void read_data(struct node **head, FILE *fp)
{
if(fp == NULL){
printf("Error opening file..\n");
return;
}
struct node temp;
temp.next = NULL;
struct node *hp, *curr;
hp = *head;
while(!feof(fp)){
fscanf(fp, " %[^:]", temp.word);
fseek(fp, 1, SEEK_CUR);
fscanf(fp, " %[^\n]", temp.sort);
struct node *temp2 = (struct node*)malloc(sizeof(struct node));
if(temp2 == NULL){
printf("Couldn't make new node by malloc:");
return;
}
*temp2 = temp;
if(hp == NULL){
curr = hp = temp2;
}
else
curr = curr->next = temp2;
}
fclose(fp);
*head = hp;
printf("Data loaded successfully..\n");
}
Error:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a5cc80 in _IO_vfprintf_internal (s=0x604830,
format=<optimized out>, ap=ap@entry=0x7fffffffd928) at vfprintf.c:1632
1632 vfprintf.c: No such file or directory.