From 8b49a62f9eb149f9e1ab3ef87bdb503ccdcdc395 Mon Sep 17 00:00:00 2001 From: Cestmir Houska Date: Fri, 22 Apr 2011 03:09:31 +0200 Subject: [PATCH] Itemio: Items can be loaded from the data file Signed-off-by: Cestmir Houska --- itemio.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++--- itemio.h | 2 ++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/itemio.c b/itemio.c index f6eb696..d698cf6 100644 --- a/itemio.c +++ b/itemio.c @@ -1,14 +1,61 @@ #include +#include #include "itemio.h" struct item items[ITEM_MAXNUM]; +int items_count; void fill_items() { - char buf[128]; + //Add 32 characters for a safe margin + #define BUFSIZE EAN_MAXLEN + NAME_MAXLEN + 32 + char buf[BUFSIZE]; FILE *f = fopen("items.txt", "r"); - while (fgets(buf, 128, f)) { - printf("%s\n", buf); + char c; + + items_count = 0; + + while (fgets(buf, BUFSIZE, f)) { + int i = 0; + int begin = 0; + + //Initialize the item + items[items_count].ean[0] = 0; + items[items_count].name[0] = 0; + items[items_count].price = 0; + + //Read the item EAN + while (i < BUFSIZE) { + if (buf[i] == '\t') { + buf[i] = 0; + strcpy(items[items_count].ean, &buf[begin]); + buf[i] = '\t'; + begin = i+1; + break; + } + i++; + } + + //Read the item name + i = begin; + while (i < BUFSIZE) { + if (buf[i] == '\t') { + buf[i] = 0; + strcpy(items[items_count].name, &buf[begin]); + buf[i] = '\t'; + begin = i+1; + break; + } + i++; + } + + //Use scanf to read the item price + i = begin; + if (i < BUFSIZE) { + sscanf(&buf[i], "%d", &items[items_count].price); + } + + items_count++; } fclose(f); } diff --git a/itemio.h b/itemio.h index 6f304b9..940ee94 100644 --- a/itemio.h +++ b/itemio.h @@ -9,6 +9,8 @@ struct item { int price; }; +extern int items_count; + extern struct item items[ITEM_MAXNUM]; extern void fill_items();