I am writing a program that is supposed to look through a file load it up and you are supposed to search for a name in the list using the command ./main (searchedname) after compilation. While compiling I get no errors. But when I try to search for a name I get a segfault immediately and the program terminates. Here is my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct _data {
char *name;
long number;
};
int SCAN(FILE *(*stream)) {
int lines = 0;
*stream = fopen("hw5.data", "r");
char c_temp[100];
long l_temp;
while(!feof(*stream)) {
fscanf(*stream, "%s %ld", c_temp, &l_temp);
lines++;
}
return lines;
}
struct _data *LOAD(FILE *stream, int size) {
struct _data *temp;
stream = fopen("hw5.data", "r");
char c_temp[100];
long l_temp;
int i;
rewind(stream);
for(i = 0; i < size; i++) {
fscanf(stream, "%s %ld", c_temp, &l_temp);
temp[i].name = calloc(strlen(c_temp), sizeof(char));
strcpy(temp[i].name, c_temp);
}
return temp;
}
void SEARCH(struct _data *Blackbox, char *name, int size) {
int found = 0, i, entry;
for(i = 0; i < size; i++) {
if((strcmp(Blackbox[i].name, name)) == 0) {
found = 1;
entry = i;
}
}
if(found == 1) {
printf("The name you are looking for has been found at entry: %d\n", entry);
} else {
printf("Entry not found.\n");
}
}
void FREE(struct _data *Blackbox, int size) {
int i;
for(i = 0; i < size; i++) {
free(Blackbox[i].name);
}
}
int main(int argv, char **argc) {
struct _data *Blackbox;
if(argv == 1) {
printf("*******************************************\n");
printf("*You must include a name to search for. *\n");
printf("*******************************************\n");
} else {
FILE *(*data);
int lines = SCAN(data);
printf("%d", lines);
Blackbox = LOAD(*data, lines);
SEARCH(Blackbox, argc, lines);
}
}
The file looks like this
foo 7894898,
bar 7895497
.
.
.