【发布时间】:2017-05-08 21:43:06
【问题描述】:
我正在用 c 编写一个简单的银行应用程序 它将信息保存在文件中。 我想在应用程序每次运行时加载文件,并将文件中的信息添加到结构中,为此,我编写了两个函数,分别称为“loadfile”和“allocate”
在函数“loadfile”中,如果我取消注释注释行,操作系统会在我脸上抛出“停止工作”:|
你能帮我吗? 当我在“加载文件”中使用 (acc+i) 时,会出现错误。 有语法问题吗? :o 谢谢
typedef struct {
char name[20];
int id;
int balance;
char branch[10];
} account;
account *acc;
int allocate ( account *acc ) {
int num = 0 ;
char tempname[20],tempbranch[10];
int tempid = -1 ,tempbalance;
FILE *file;
file = fopen("D://bank.txt","r");
while ( !feof(file) ) {
fscanf(file,"%s %d %d %s ",tempname, &tempid, &tempbalance, tempbranch);
if (tempid != -1)
num++;
}
acc = ( account *) realloc ( acc, num * sizeof(account) );
fclose(file);
printf(" num in allocate function : %d",num);
return num;
}
int loadfile (account *acc) {
int num = allocate(acc);
char tempname[20],tempbranch[10];
int tempid ,tempbalance;
if ( num != 0 ) {
int i = 0 ;
FILE *file;
file = fopen("D:\\bank.txt","r+");
for ( i = 0 ; !feof(file) && i < num ; i++ ) {
fscanf(file,"%s ",tempname );
fscanf(file,"%d ",&tempid );
fscanf(file,"%d ",&tempbalance );
fscanf(file,"%s ",tempbranch );
printf("\n i is %d \n",i);
/* strcpy( ((acc+i)->name) , tempname);
(acc+i)->id = tempid;
(acc+i)->balance = tempbalance;
strcpy( ((acc+i)->branch) , tempbranch); */
}
fclose(file);
}
return num;
}
【问题讨论】:
-
使用全局
account *acc;I.Eint allocate ( account *acc ) {-->int allocate (void) { -
不要投
void *函数的返回值! -
这段代码有太多错误。它不验证返回值,也不能正确使用
feof()。另外,您不知道 C 中的作用域是什么,并且您的格式样式不好。 -
@SOFUser 有两种方法可以使用 realloc: 使用它来更改先前分配的段的大小。然后,您必须将指针传递给先前分配的内存。或者你像 malloc 一样使用它来分配新内存。然后,您必须传递一个 NULL 指针。您执行后者似乎只是运气不好,因为您使用的是具有静态存储持续时间的 icky 全局变量,因为它恰好初始化为 NULL。如果您将该变量移动到应该在的本地范围内,那么除非您将指针显式初始化为 NULL,否则 realloc 将不起作用。
标签: c file struct allocation scanf