I've been struggling with this for days and I can't figure out why it doesn't work.
I'm trying to read numbers from file with numbers written like this:
0 2012 1 1 2000.000000
0 2012 1 1 3000.000000
1 2012 1 1 4500.000000
my structure:
struct element{
int id;
int sign;
int year;
int month;
double amount;
struct element *next;
};
struct queue{
struct element *head;
struct element *tail;
struct element *head2;
struct element *temp;
struct element *temph;
int size;
};
(head2, temp and temph are used in sorting structure)
and reading from a file:
void read_str(struct queue *queue){
FILE *reads;
char filename[40];
int temp;
printf("Type in name of the file\n");
scanf("%s",&filename);
reads=fopen(filename, "r");
if (reads==NULL) {
perror("Error");
return 1;
}
else {
while(!feof(reads)) {
struct element *n= (struct element*)malloc(sizeof(struct element));
fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount);
n->next=NULL;
if(queue->head ==NULL) {
queue->head=n;
}
else {
queue->tail->next=n;
}
queue->tail=n;
queue->size++;
}
}
}
I can change the way the data looks in a file by changing the function that writes it, but I don't think that's the problem. My guess I'm using malloc
in a wrong way.
fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount);
The scanf
family of functions expect addresses. Change the fscanf
line to:
fscanf(reads,"%d %d %d %d %lf", &n->id, &n->sign, &n->year,
&n->month, &n->amount);
Side note, this is a seriously misleading line:
else { while(!feof(reads)) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With