Hi, I´ve had some problems completing a program that I´ve worked with for a while now. Basically, i need to read data from a textfile with 30 beers each containing 10 elements(each element is seperated by a comma). This data is supposed to be stored in a struct with maximum capacity of 100 items(beers). Can someone explain how you´re supposed to solve it?
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>
void start(void)
{
char *oneline, *tok;
char envara[256];
char delim[] = ",";
FILE *fp;
int i;
struct vara
{
int nummer;
char namn[100];
float pris;
float volym;
char typ[100];
char stil[100];
char forpackning[20];
char land[20];
char producent[50];
float alkoholhalt;
} items[100];
items[i].nummer = atoi(tok);
items[i].pris = atof(tok);
items[i].volym = atof(tok);
items[i].alkoholhalt = atof(tok);
strncpy(&items[i].namn, tok, strlen(tok));
strncpy(&items[i].typ, tok, strlen(tok));
strncpy(&items[i].stil, tok, strlen(tok));
strncpy(&items[i].forpackning, tok, strlen(tok));
strncpy(&items[i].land, tok, strlen(tok));
strncpy(&items[i].producent, tok, strlen(tok));
if ((fp = fopen("varor.csv", "r")) == NULL)
{
fprintf(stderr, "Filen varor.csv gick inte att öppna\n");
exit(-1);
}
for (i = 0; i < 100 && fgets(envara, 256, fp); i++)
{
envara[strlen(envara) - 1] = '0'; // Ta bort radslutstecknet
printf("%s\n\n", envara);
oneline = strdup(envara);
tok = strtok(oneline, delim);
while (tok != NULL)
{
printf("%s\n", tok);
tok = strtok(NULL, delim);
}
}
free(oneline); free(tok);
fclose(fp);
}