我必须构建一个从文件中读取Template.register.events({
'click .register': function(e) {
e.preventDefault();
var getUser = $("#username").val();
var getEmail = $("#email").val();
var getPassword = $("#password").val();
}
});
和backer
信息(结构)的函数。如果文件不存在,请通知用户,创建新文件并显示主菜单。文件打开后,通过为从文件读取的每个条目动态分配足够的内存,将数据读入结构数组。这是我走了多远。我不确定如何处理结构数组或正确分配内存。这是一个我不那么强大的话题。
reward
答案 0 :(得分:1)
用于将文件加载到struct backer
的数组中,其格式为:
int i;
FILE *backers;
struct backer *backer_array = NULL;
size_t backer_size = 0;
size_t bytes_read;
if ((backers = fopen("backers.txt", "rb")) == NULL) {
printf("File not found \n New backers file created \n");
}
else{
/* Get the file size. */
fseek(backers, 0 , SEEK_END);
backer_size = ftell(backers);
rewind(backers);
/* Make sure that file size is an integral number of records. */
backer_size = backer_size - (backer_size % sizeof(struct backer));
/* Allocate space. */
if (backer_size > 0) {
backer_array = malloc(backer_size);
}
/* Read the entire file in one read. */
if (backer_array) {
bytes_read = fread (backer_array, 1, backer_size, backers);
/* backer_size will now represent the number of elements in the array. */
backer_size = backer_size / sizeof(struct backer);
}
/* Close the file. */
fclose(backers);
}
if (backer_array) {
for (i = 0; i < backer_size; i++) {
/* Do stuff with backer_array[i]; */
}
free(backer_array);
}
答案 1 :(得分:1)
这是一个更好的代码。结构支持者和奖励的实例是指针:
struct backer_info {
int backer_ID;
char *backer_name[40];
char *email[40];
char *country[20];
} backer;
struct reward_info {
int reward_number;
int backer_ID;
float price;
int num_drones;
int priority;
} reward;
void load_data(){
int i;
int j;
FILE *backers;
FILE *rewards;
struct backer_info *backer;
if ((backers = fopen("backers.txt", "rb")) == NULL) {
printf("File not found \n New backers file created \n");
}
else{
if (backer = malloc(sizeof(struct backer_info)) == NULL) {
printf("Memory could't be allocated\n");
for (i = 1; !feof(backers); i++) {
fread(&backer, sizeof(struct backer_info), 1, backers);
backer = realloc(backer, (i + 1) * sizeof(struct backer_info));
}
fclose(backers);
}
struct reward_info *reward;
if ((rewards = fopen("rewards.txt", "rb")) == NULL) {
printf("File not found \n, New rewards file created \n");
}
else{
if (reward = malloc(sizeof(struct reward_info)) == NULL) {
printf("Memory could't be allocated\n");
}
for (j = 1; !feof(rewards); j++) {
fread(reward, sizeof(struct reward_info), 1, rewards);
reward = realloc(reward, (i + 1) * sizeof(struct reward_info));
}
fclose(rewards);
}
/* Use the allocated space */
}