此任务是获取第一行作为标题,然后从文件中计算数据,减号在括号中。它将打印标题和这些数据的总和。每行都以换行符终止。我不知道问题是什么。我不知道如何处理“总线错误 10”。也许是因为内存的分配,我不知道......谁能帮帮我?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Our definition of a structure to represent department data.
struct dept {
int id;
char *name;
int balance;
struct dept *next;
};
typedef struct dept dept_t;
// For (a)
dept_t *create_dept(int dept_id, char *dept_name, int dept_balance);
// For (b)
dept_t *load_dept(int id);
// For (c)
void free_dept(dept_t *dept);
// For (d)
void print_dept(dept_t *dept);
int main(int argc, char *argv[])
{
dept_t *d = load_dept(51423);
print_dept(d);
free_dept(d);
}
// (a)
dept_t *create_dept(int dept_id, char *dept_name, int dept_balance)
{
dept_t *d = malloc(sizeof(dept_t));
d->id = dept_id;
d->name = dept_name;
d->balance = dept_balance;
d->next = NULL;
return d;
}
// (b)
char *prompt(FILE *fp)
{
char ch;
// skip leading whitespace
do
{
fscanf(fp, "%c", &ch);
if(feof(fp))
{
return NULL;
}
} while(ch == '\n');
// read in until whitespace
int cur_size = 8;
char *str = malloc(sizeof(char) * cur_size);
int cur_pos = 0;
str[cur_pos] = ch;
cur_pos++;
do
{
fscanf(fp, "%c", &ch);
if(feof(fp))
{
str[cur_pos] = '\0';
return str;
}
str[cur_pos] = ch;
cur_pos++;
if(cur_pos >= cur_size - 1)
{
cur_size = cur_size * 2;
str = realloc(str, sizeof(char) * cur_size);
}
} while(ch != '\n');
str[cur_pos - 1] = '\0';
return str;
}
dept_t *load_dept(int id)
{
FILE *fp;
char *filename;
int balance = 0;
char *name;
char *string;
int i;
dept_t *d;
filename = malloc(sizeof(char)*10);
sprintf(filename,"%d.txt",id);
if((fp = fopen(filename,"r")) == NULL)
{
fprintf (stdout,"Can't open \"%s\"file.\n",filename);
exit(1);
}
name = prompt(fp);
int value;
for(i=0;i<6;i++)
{
string = prompt(fp);
if (string[0]=='(')
{
value = atoi(&string[1]);
balance = balance - value;
}
else
{
value = atoi(string);
balance = balance + value;
}
}
free(string);
free(filename);
if(fclose(fp)!=0)
{
fprintf(stderr,"Error closing file\n");
}
d = create_dept(id,name,balance);
return d;
}
// For (c)
void free_dept(dept_t *dept)
{
free(dept->name);
free(dept);
}
// For (d)
void print_dept(dept_t *dept)
{
printf("Department: %s",dept->name);
printf(" %d",dept->balance);
}