我正在为一个包含“info”类型信息的简单数据库编写代码。
这是我的代码:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define NAME_LENGTH 20
#define EMAIL_LENGTH 15
struct info {
char name[NAME_LENGTH];
char email[EMAIL_LENGTH];
int flag;
};
int createDB(char *name) {
FILE * file = fopen(name, "w+b");
return fclose(file);
}
FILE *openDB(char *name) {
FILE* file = fopen(name, "r+b");
if(file != NULL) return file;
return NULL;
}
int closeDB(FILE *f) {
return fclose(f);
}
struct info *get(FILE *file, int index) {
struct info* temp;
fseek(file, index*sizeof(struct info), SEEK_SET);
fread(temp, 1, sizeof(struct info), file);
if(feof(file) != 0) return NULL;
return temp;
}
int put(FILE *file, int index, struct info *record) {
fseek(file, index*sizeof(struct info), SEEK_SET);
int res = fwrite(record, 1, sizeof(struct info), file);
if(res) return 0;
else return EOF;
}
struct info *search(FILE *file, char *name) {
int k = 0;
struct info* temp = get(file, 0);
do {
if(temp -> flag == 1 && strcmp(temp -> name,name) == 0) return temp;
k++;
temp = get(file, k);
}while(temp != NULL);
return temp;
}
当我从文件中“放置”、“获取”信息时,一切正常。但是,当我尝试根据名称搜索时,我收到Segmentation fault (core dumped)错误。
请你在这里显示我的错误好吗?