Populate Arrays of Structures from a File - c

I have a .dat file filled with ints and doubles that I need to populate an array of structures with, and I'm having issues figuring out the syntax.
Here is the file:
9383 8.86
2777 69.15
7793 83.35
5386 4.92
6649 14.21
2362 0.27
8690 0.59
7763 39.26
540 34.26
9172 57.36
5211 53.68
2567 64.29
5782 15.30
2862 51.23
4067 31.35
3929 98.02
4022 30.58
3069 81.67
1393 84.56
5011 80.42
6229 73.73
4421 49.19
3784 85.37
5198 43.24
8315 43.70
6413 35.26
6091 89.80
9956 18.73
6862 91.70
6996 72.81
Here is my code:
typedef struct student
{
double score;
int id;
char grades;
} Student;
int getScores(FILE *input, Student class);
void main(void)
{
char filename[] = "scores.dat";
FILE *input;
Student class[MAXNUM];
int numScores;
double average;
input = fopen("scores.dat", "r");
if (input == NULL)
{
printf("EOF");
exit(1);
}
}
int getScores(FILE *input, Student class)
{
double s;
int i, count = 0;
while(fscanf(input, "%d %lf", &i, &s) == 2)
{
class[count].score = s;
class[count].id = i;
count++;
}
My main issue lies in the while loop where I am trying to populate the array with the int and doubles of the scores.dat file.
I get the following error when I compile:
lab5.c:53:8: error: subscripted value is neither array nor pointer nor
vector
class[count].score = s;
^
lab5.c:54:8: error: subscripted value is neither array nor pointer nor
vector
class[count].id
Thank you for any help or tips.

Just change function getScores definition and declaration argument class from
`int getScores(FILE *input, Student class);`
to
`int getScores(FILE *input, Student *class);`

Related

my binary file is always empty when i try to fill it with an array

typedef struct equipement_agricole{
char type[20];
char marque[20];
char modele[20];
char numero_serie[30];
char panne[20];
char status[20];
int nb_status;
int nb_panne;
}equipement_agricole;
typedef struct eq_util{
char numero_s[30];
char type_u[20];
char marque_u[20];
char modele_u[20];
int nb_util;
int ordre;
}eq_util;
typedef struct verif{
char id[30];
int nb;
}verif
void equipement_plus_util()
{
FILE *f;
FILE *g;
int i=0;
int taille=0;
f=fopen("equipement.bin","rb");
g=fopen("equipement_util.bin","wb");
equipement_agricole E;
eq_util U;
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
{
taille+=1;
}
verif tab1[taille];
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
{
strcpy(tab1[i].id,E.numero_serie);
tab1[i].nb=E.nb_status;
i++;
}
int j,k;
verif T;
for(j=0;j<taille-1;j++)
{
for(k=j+1;k<taille;k++)
{
if(tab1[j].nb<tab1[k].nb)
{
strcpy(T.id,tab1[j].id);
T.nb=tab1[j].nb;
strcpy(tab1[j].id,tab1[k].id);
tab1[j].nb=tab1[k].nb;
strcpy(tab1[k].id,T.id);
tab1[k].nb=T.nb;
}
}
}
int a;
for(a=0;a<taille;a++)
{
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
{
if(strcmp(tab1[a].id,E.numero_serie)==0)
{
strcpy(U.marque_u,E.marque);
strcpy(U.modele_u,E.modele);
strcpy(U.numero_s,E.numero_serie);
strcpy(U.type_u,E.type);
U.nb_util=E.nb_status;
U.ordre=a+1;
fwrite(&U,sizeof(eq_util),1,g);
}
}
}
fclose(f);
fclose(g);
}
hi guys i need your help i've been stuck in this sccince 2 days i can't find a solution for this so my problem is
after i take the necessair information from equipement.bin bianry file and put it inside an array than i sort that array after that i put the array whit is i think sorted in the equipement_util.bin but i always find that it is always empty i tried every thin that i know thank you
regarding:
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
{
taille+=1;
}
verif tab1[taille];
while(fread(&E,sizeof(equipement_agricole),1,f)!=0)
When the first 'while()' loop exits, the 'file pointer' will be at the end of the file, So the second while() loop will exit immediately.
To fix this problem:
after the first while() loop exits, reset the 'file pointer' to the beginning of the file. Suggest:
rewind( f );
the above will result in the data from the file being set into the array tab1[]
There may be other problems, however the above correction will get your code started in the right direction

scanf a structure from a function, call from same function to scan other structures

Im trying to scanf a structure from file input within a function, and print it using another function.
Ultimately I need to be able to print out the same information that I would from the code that I commented out, but doing so from the functions I have listed in the function prototypes declaration area. I only un-commented 2 of those so I could try baby steps to get something to scan and print using functions. The functions themselves are located at the very bottom.
To finish the scan_auto function, somehow I need to scanf 2 other structures that are part of the main structure. I assume I need to call the functions scan_date and scan_tank from scan_auto, however I am unsure how to do that properly.
Here is the code I have so far...
#include <stdio.h>
#define STRSIZE 20
/* Structure definitions */
typedef struct {
int month,
day,
year;
} date_t;
typedef struct {
double capacity,
current;
} tank_t;
typedef struct {
char make[STRSIZE],
model[STRSIZE];
int odometer;
date_t manuf,
purch;
tank_t tank;
} auto_t;
/* Function prototypes */
/*
int scan_date(date_t *date);
int scan_tank(tank_t *tank);
*/
int scan_auto(auto_t *vehicle, FILE *inp);
/*
void print_date(date_t date);
void print_tank(tank_t tank);
*/
void print_auto(auto_t vehicle);
int main()
{
auto_t vehicle;
int number=0,
i=0,
status=1;
FILE *inp = fopen("autos.txt","r"); /* defining file input */
/* Check to make sure input file is found and readable. */
if(inp==NULL){
printf("Error: Input file - autos.txt - not found!\n");
getch();
return 0;
}
printf("Vehicle Vehicle Odometer Date Date Tank Current\n");
printf("Make Model Reading Purchased Manufactured Capacity Fuel Level\n");
printf("\n----------------------------------------------------------------------------\n\n");
/*******************COMMENTED OUT*************************************
while(status>0){
status=fscanf(inp, "%s%s%d%d%d%d%d%d%d%lf%lf", vehicle.make,
vehicle.model,
&vehicle.odometer,
&vehicle.manuf.month,
&vehicle.manuf.day,
&vehicle.manuf.year,
&vehicle.purch.month,
&vehicle.purch.day,
&vehicle.purch.year,
&vehicle.tank.capacity,
&vehicle.tank.current);
if(status==11){
printf("%-10s%-9s%-10d%2d/%d/%-6d%2d/%d/%-8d%-11.1lf%.1lf\n", vehicle.make,
vehicle.model,
vehicle.odometer,
vehicle.manuf.month,
vehicle.manuf.day,
vehicle.manuf.year,
vehicle.purch.month,
vehicle.purch.day,
vehicle.purch.year,
vehicle.tank.capacity,
vehicle.tank.current);
i++;}
else if(status <11 && status>0){
printf("\nInvalid Input - The next line of data is corrupt.\n");
}
}
******************************************************************************/
scan_auto(&vehicle, inp);
print_auto(vehicle);
/*
print_auto(vehicle);
*/
getch();
return 0;
}
/*********************************************************************************/
int scan_date(date_t *date)
{
int result;
result=scanf("%d%d%d", &(*date).month,
&(*date).day,
&(*date).year);
if (result==3)
result=1;
else if(result !=EOF)
result=0;
return (result);
}
/*********************************************************************************/
double scan_tank(tank_t *tank)
{
int result;
result=scanf("%lf%lf", &(*tank).capacity,
&(*tank).current);
if (result==2)
result=1;
else if(result !=EOF)
result=0;
return (result);
}
/*********************************************************************************/
int scan_auto(auto_t *vehicle, FILE *inp)
{
int result;
result=fscanf(inp, "%s%s%d", (*vehicle).make,
(*vehicle).model,
&(*vehicle).odometer);
if (result==3)
result=1;
else if(result !=EOF)
result=0;
return (result);
}
/*********************************************************************************/
void print_auto(auto_t vehicle)
{
printf("%-10s%-9s%-10d", vehicle.make,
vehicle.model,
vehicle.odometer);
}
The text file (autos.txt) I am using....
Mercury Sable 99842 1 18 2001 5 30 1991 16 12.5
Mazda Navajo 123961 2 20 1993 6 15 1993 19.3 16.7
however I am unsure how to do that properly.
Can you elaborate on what you're unsure? If you're not sure how to assign value to struct member of struct, perhaps this sample code will help you? I combined all of the things together...
Oh, and I changed your *vehicle to *v to make it shorter and easier to read.
Also, since you're accessing member of struct pointer, why don't you use v->xxx instead of (*v).xxx ?
UPDATE 1: You asked how to do it separately. Here it is:
int scan_date(date_t *date, FILE *inp)
{
int result = fscanf(
inp,
"%d%d%d",
&(date->day),
&(date->month),
&(date->year));
return (result == 3);
}
int scan_tank(tank_t *tank, FILE *inp)
{
int result = fscanf(
inp,
"%lf%lf",
&(tank->capacity),
&(tank->current));
return (result == 2);
}
int scan_auto(auto_t *v, FILE *inp)
{
int result = fscanf(
inp,
"%s%s%d",
v->make,
v->model,
&(v->odometer));
result += scan_date(&(v->purch), inp);
result += scan_date(&(v->manuf), inp);
result += scan_tank(&(v->tank), inp);
return (result == 11); // return 0 if true
}

Currency conversion database structure from text file

I've been working on a program for a data structure that reads in a file of different currencies, which I then call to use for conversion. I've been running over this for days on end and tried fgets, fscanfs, and such, and I'm just lost at this point as I am pretty new to programming.
the dat. file is outlined on separate lines like this:
dollar 1.00
yen 0.0078
franc 0.20
mark 0.68
pound 1.96
my code so far:
typedef struct {
string currency;
double rate;
} currencyT;
typedef struct {
currencyT cur[MaxCurrencyTypes];
int nCurrency;
} *currencyDB;
static currencyDB ReadDataBase(void);
static ReadOneLine(FILE *infile, currencyDB db);
static currencyDB ReadDataBase(void)
{
FILE *infile;
currencyDB db;
int nCurrency;
db = New(currencyDB);
infile = fopen(ExchangeFile, "r");
while (ReadOneLine(infile, db));
fclose(infile);
return(db);
}
static ReadOneLine(FILE *infile, currencyDB db)
{
currencyT cur;
char termch, currency;
double rate;
int nscan, nCurrency;
nCurrency = 0;
while(1) {
nscan = fscanf(infile, "%20s %f%c", db->cur[nCurrency].currency,
&db->cur[nCurrency].rate, &termch);
if(nscan = EOF) break;
if(nscan != 3 || termch != '\n') {
Error("Improper file format");
}
nCurrency++;
}
db->nCurrency = nCurrency;
}
static void ProcessExchange(currencyDB db)
{
}
main()
{
currencyDB currencies;
currencies = ReadDataBase();
ProcessExchange(currencies);
}
See 8 & 9 first.
MaxCurrencyTypes is undeclared, let's assume
#define MaxCurrencyTypes (5)
string is undeclared, let's assume
typedef char * string;
currencyDB is a pointer type, recommend instead declaring as a structure type
typedef struct {
currencyT cur[MaxCurrencyTypes];
int nCurrency;
} currencyDB; // Drop *
static ReadOneLine() should use explicit return type.
static int ReadOneLine()
int nCurrency; not used in ReadDataBase().
New() in db = New(currencyDB) is not declared nor defined. Assume to allocate uninitialized memory for *db.
ExchangeFile not declared.
if (nscan = EOF) -> if (nscan == EOF)
ReadOneLine() needs to return a value.
main() should explicitly state return type and parameters.
int main(void)

Copying unformatted file into structure

#define MAX 20
typedef char string20[21];
struct flight_list{
char fcode[21];
string20 srccity;
string20 descity;
int deptime[2];/** deptime[0] hours, deptime[1] minutes **/
int duration;
int eta[2];/**eta[0] hours , eta[1] minutes**/
int nctr;
};
void load_flight(struct flight_list flight[]){
int num,i;
char* ptr;
FILE* fp;
fp = fopen("flightFILES.txt","r");
fscanf(fp,"%d",&num);
while(!feof(fp)){
for(i=0;i<num;i++){
fgets(flight[i].fcode,100,fp);
fgets(flight[i].srccity,100,fp);
fgets(flight[i].descity,100,fp);
fscanf(fp,"%d %d",flight[i].deptime[0],flight[i].deptime[1]);
fscanf(fp,"%d",flight[i].duration);
fscanf(fp,"%d %d",flight[i].eta[0],flight[i].eta[1]);
ptr=strchr(flight[i].fcode,'=');
strcpy(flight[i].fcode,ptr+1);
ptr=strchr(flight[i].srccity,'=');
strcpy(flight[i].srccity,ptr+1);
ptr=strchr(flight[i].descity,'=');
strcpy(flight[i].descity,ptr+1);
}
}
fclose(fp);
}
every time I run this function It crashes I just followed what he advice me to do please help me I'm suppose to copy the contents inside of this file to my array of structures
the file format is this:
4
FCODE=CHIX
SRCCITY=MAN
DESTCITY=KAN
DEPARTURE=12 10
DURATION=30
FCODE=PAUL
SRCCITY=KAN
DESTCITY=CHG
DEPARTURE=13 10
DURATIOn=60
File input/output in C unformatted

Structure pointer declared in function

Here is the part of the code that isnt working for me.I am declaring a pointer to a structure and I try to use it on a function,although c says that it cant convert main person to person.
void display (char *s2,FILE *f1,int max);
void insert (FILE *f1, struct person *p1);
void deletestring (FILE *f1,FILE *f2,char *s2,char *s1,char *file1,char *file2,int max);
void edit (FILE *f1,FILE *f2,char *s2,char *s1,char *file1,char *file2,struct person *p1,int max);
int main ()
{
char s1[MAX],s2[MAX];
FILE *f2,*f1;
struct person
{
char id[MIN];
char emer[MIN];
char mbiemer[MIN];
};
struct person p1;
struct person *pp1;
pp1 = &p1;
char *file1 = "f1.txt";
char *file2 = "f2.txt";
int zgjedhja=1;
printf("Programi funksionon sipas shpjegimit \n :");
printf("Shtypni 1 per te shtuar nje person \n Shtypni 2 per te ndryshuar informacionin e nje personi \n Shtypni 3 per te shfaqur te dhenat \n Shtypni 4 per te fshire nje person \n Shtypni -1 per te dale nga programi \n ");
while (zgjedhja != -1 )
{
printf("Jepni zgjedhjen tuaj \n ");
scanf(" %d " , & zgjedhja );
switch (zgjedhja)
{
case 1:
f1=fopen(file1,"a");
insert (f1,pp1);
The type struct person has main scope, so it won't have the same meaning in insert. In fact, a structure type whose members have not been specified is known as an incomplete type. To remove this error, declare your structure outside of your function.
struct person
{
/* ... */
};
/* Function declarations. */
int main (void)
{
/* ... */
}

Resources