Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

Grabbing each line from CSV to Struct

Hey guys,

I recently started to work with C in school and I am trying to make a program which can read each line from a CSV file and store it in a struct named "Products". The struct must be able to handle up to 100 products in total (The product.csv file contains 50 lines of products). So far this class that I have can read one line from the CSV file, and it only grabs the first line. If I use fgets again, it will overwrite the first line and give me the second line which is not what I need.

This is what the assignment says:
The input file products.csv contains about 50 items. Each single row corresponds to a product. A loaded line must be saved in one
struct, with the name being, with content as above (The struct at the bottom of the thread). Create a field with these commodities with space for 100 pieces of goods.


So far this is the code I have:

Code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "header.h"

int getfile(void)
{
 char *oneline, *tok;
 char oneproduct[256];
 char delim[] = ",";
 
 FILE *fp;
 
 if ((fp = fopen("products.csv", "r")) == NULL) {
   fprintf(stderr, "The file products.csv was unable to open. \n");
 }

 fgets(oneproduct, 256, fp);
 oneproduct[strlen(oneproduct) - 1] = '\0';
 printf("One line: %s\n", oneproduct);

 oneline = strdup(oneproduct);

 tok = strtok(oneline, delim);
 while (tok != NULL) {
   printf("%s\n", tok);
   tok = strtok(NULL, delim);
 }

 free(oneline); free(tok);
 fclose(fp);
 return 0;
}

The struct must contain the following items:
Code
struct product
{
   int productID;
   char name[100];
   float price;
   float volym;
   char type[100];
   char stil[100];
   char containment[50];
   char country[50];
   char producer[100];
   float alcoholpercentage;
};

Any ideas on how I can proceed to grab each line using a loop or something and store them in a struct?

I am willing to pay in bitcoin if someone could help me out with this :)

Thanks!
struct product products[100]
loop the lines count and sign the products array properties with your data
[Image: bitcoin.png] Be Nice For Once 15hVUVz7xA4kazHdk2BuErENGCskVwjYXP


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C#] by GuillyianJul 11, 2022 05:19 AM 5 230 Jul 11, 2022 05:19 AM
Last Post: MavenGradle
[Python] by MomentumAug 24, 2021 03:54 PM 3 202 Aug 24, 2021 03:54 PM
Last Post: Momentum
[Java] by theloharryDec 4, 2020 06:15 AM 7 230 Dec 4, 2020 06:15 AM
Last Post: Rmdy