initial import
[staff/goc4/2018bti7061.git] / c-6-additional / examples / c-variousexamples / exercise2writecars.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "cars.h"
5
6 #define DEBUG 0
7
8 #define MAXCARS 255
9
10 int main(){
11
12 car** list_of_cars;
13
14 list_of_cars = (car**) malloc(MAXCARS * sizeof(car*));
15 int nb_cars=0;
16
17 printf("*********************************\n");
18 printf("******* CAR LIST*****************\n");
19 printf("**********************************\n");
20 printf("**Type Control D to end the list**\n");
21 printf("**********************************\n");
22
23 while(1){
24 car* p_car = (car*) malloc(sizeof(car));
25 printf("*** Car number : %d ***\n",nb_cars+1);
26 printf("Enter the identification number: ");
27 scanf(" %s",p_car->id_number);
28 if(strlen(p_car->id_number) ==0){
29 goto endloop;
30 }
31 printf("Enter the brand:");
32 scanf(" %s",p_car->brand);
33 if(strlen(p_car->brand) ==0){
34 goto endloop;
35 }
36 printf("Enter the type:");
37 scanf(" %s",p_car->type);
38 if(strlen(p_car->type) == 0){
39 goto endloop;
40 }
41 printf("Enter the price:");
42 int matches;
43 matches=scanf(" %lf",&(p_car->price));
44 if(matches==0){
45 goto endloop;
46 }
47
48 #if DEBUG
49 printf("new car\n");
50 printf("Address in memory %lX",p_car);
51 printf("Size in memory %lu\n",sizeof(*p_car));
52 #endif
53
54 list_of_cars[nb_cars++]=p_car;
55
56 continue;
57 endloop:
58 puts("*********************");
59 free(p_car);
60 break;
61
62 }
63 int i;
64 printf("*****\nList of cars\n");
65 FILE *fp;
66 fp = fopen("cars.txt","a");
67
68 for(i=0;i<nb_cars;++i){
69 car* p_car2 = list_of_cars[i];
70
71 fprintf(fp,"%s %s %s %lf\n",p_car2->type,p_car2->brand,p_car2->id_number, p_car2->price);
72 }
73
74
75 }