Reputation: 159
I plan on reading an input file that has a name and a number separated by an indent such as
Ben 4
Mary 12
Anna 20
Gary 10
Jane 2
and then later perform a heap sort on the data. I'm having trouble copying the data and storing it into a struct array however.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxcustomers 100
struct customer{
char name[20];
int service;
};
int main()
{
struct customer list[maxcustomers];
int i;
char c;
FILE *input;
FILE *output;
input = fopen("input-file.txt","r");
output = fopen("output-file.txt","w");
if(input == NULL){
printf("Error reading file\n");
exit(0);
}
else{
printf("file loaded.");
}
while((c=fgetc(input))!=EOF){
fscanf(input, "%s %d", &list[i].name,&list[i].service);
printf("%s %d", list[i].name,list[i].service);
i++;
}
fclose(input);
//heapsort(a,n);
//print to output.txt
fclose(output);
return 0;
}
so far it registers it opens a file and prints "file loaded" but fails after. im obviously not saving data to the struct.
Upvotes: 2
Views: 101
Reputation: 280
in addition to what @Keine Lust said,
i
have no initial value, you cant use/increment integer without value as you did.
try:
int i=0
Upvotes: 3
Reputation: 41017
You are consuming/walking the file with both fgetc
and fscanf
, use only fscanf
:
while (fscanf(input, "%19s %d", list[i].name, &list[i].service) == 2) {
printf("%s %d", list[i].name, list[i].service);
i++;
}
Notice that you don't need the address of operator in &list[i].name
because it is already (decays into) a pointer.
Upvotes: 5