I am working on a project where I am creating structures inside of a separate function than main()
. After being created and added member (variable) information into the structure variable, I need to be able to return
a pointer to the structure in which I can access it for reference and printing.
I am including my code and please be as simple as possible as I am new to structures.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct _car
{
char color[20];
char model[20];
char brand[20];
int year;
struct _car *eptr;
} Car;
Car* readCars(char* filename);
/*
*
*/
int main(int argc, char** argv) {
Car *Cars;
Car *eptr;
Cars = readCars(argv[1]);
printf("%s%s%s%s", Cars->color, Cars->brand, Cars->model, Cars->color);
return (EXIT_SUCCESS);
}
Car* readCars(char* filename)
{
FILE *file = fopen(filename, "r");
int year;
char color [20], model [20], brandx[20];
Car car1;
Car car2;
Car *carptr;
Car *car2ptr;
if (file == NULL)
{
printf("File cannot be opened
");
}
while(file != EOF)
{
fscanf(file, "%s%s%s%d", color, model, brandx, &year);
strcpy(car1.color, color);
strcpy(car1.model, model);
strcpy(car1.brand, brandx);
car1.year = year;
carptr = &car1;
fscanf(file, "%s%s%s%d", color, model, brandx, &year);
strcpy(car2.color, color);
strcpy(car2.model, model);
strcpy(car2.brand, brandx);
car2.year = year;
car2ptr = &car2;
if (fscanf(file, "%s%s%s%d", color, model, brandx, &year) == EOF)
{
break;
}
}
return carptr;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…