/* * ===================================================================================== * * Filename: auta.c * * Description: auticka * * Version: 1.0 * Created: 11/30/2011 04:04:02 PM * Revision: none * Compiler: gcc * * Author: Milan Kabat (), kabat@ics.muni.cz * Company: FI MUNI * * ===================================================================================== */ #include #include #include #include #define YEAR_SPAN 61 #define NUM_COLORS 6 #define NUM_BRANDS 7 #define FILENAME_BINARY "car_list.dat" #define FILENAME "car_list.txt" char *brands[] = { "Opel", "Mazda", "Toyota", "Skoda", "Audi", "Buick", "Ford" }; enum colors { red, yellow, blue, green, white, black }; struct car { char brand[20]; enum colors color; int year; }; void printCar(struct car *c) { char color[10]; switch(c->color) { case red: { strcpy(color, "Red"); break;} case yellow: { strcpy(color, "Yellow"); break;} case blue: { strcpy(color, "Blue"); break;} case green: { strcpy(color, "Green"); break;} case white: { strcpy(color, "White"); break;} case black: { strcpy(color, "Black"); break;} } printf("| %-10s | %-10s | %d\n", color, c->brand, c->year); } void createCarsAsText(int howMany, FILE *f) { struct car c; for(int i = 0; i < howMany; i++) { c.year = rand()%YEAR_SPAN + 1950; c.color = rand()%NUM_COLORS; sprintf(c.brand, "%s", brands[rand()%NUM_BRANDS]); //printCar(&c); fprintf(f, "%s %d %d\n", c.brand, c.color, c.year); } } void readCarsAsText(FILE *f) { int a; while((a = fgetc(f)) && !feof(f)) { printf("%c", a); } } void createCarsBinary(int howMany, FILE *f) { struct car c; for(int i = 0; i < howMany; i++) { c.year = rand()%YEAR_SPAN + 1950; c.color = rand()%NUM_COLORS; sprintf(c.brand, "%s", brands[rand()%NUM_BRANDS]); fwrite(&c, sizeof(struct car), 1, f); } } void readCarsBinary(FILE *f) { struct car c; while(!feof(f)) { if(fread(&c, sizeof(struct car), 1, f)) { printCar(&c); } } } /* * === FUNCTION ====================================================================== * Name: main * Description: * ===================================================================================== */ int main ( int argc, char *argv[] ) { srand(time(NULL)); FILE *f; /*f = fopen(FILENAME, "w"); createCarsAsText(100, f); fclose(f); f = fopen(FILENAME, "r"); readCarsAsText(f); fclose(f); */ f = fopen(FILENAME_BINARY, "wb"); createCarsBinary(10, f); fclose(f); f = fopen(FILENAME_BINARY, "rb"); readCarsBinary(f); fclose(f); printf("\n\n"); return EXIT_SUCCESS; } /* ---------- end of function main ---------- */