Ivan  Tarabykin
Ivan Tarabykin

Reputation: 11

Reading from file into an array in C

guys. I have a trouble reading from file in C and putting in into array, assigning each part of an array to an variable.

The file looks like this:

A0005:Burger:2.39:Extra Cheese
A0006:Soda:1.35:Coke
....

The thing is, I don't quite get how do you split string in C when it reaches colon.

So far i tried to make a structure, tried using strtok and getchar but so far unsuccessfully.

here's what i got so far

#include <stdio.h>

struct menuItems{
 char itemCode[5];
 char itemName[50];
 float itemPrice;
 char itemDetails[50];
 };


int main(void){
    FILE *menuFile;
    char line[255];
    char c;

    struct menuItems allMenu = {"","",0.0,""};


    if ((menuFile = fopen("addon.txt", "r")) == NULL){
        puts("File could not be opened.");

    }
    else{
        printf("%-6s%-16s%-11s%10s\n", "Code", "Name", "Price", "Details");
        while( fgets(line, sizeof(line), menuFile) != NULL ){
            c = getchar();
            while(c !='\n' && c != EOF){
                fscanf(menuFile, "%5s[^:]%10s[^:]%f[^:]%s[^:]", allMenu.itemCode, allMenu.itemName, &allMenu.itemPrice, allMenu.itemDetails);
            }

            }


    }
}

Upvotes: 1

Views: 129

Answers (1)

Sameer Mahajan
Sameer Mahajan

Reputation: 598

For every line you need to do something like:

   /* your code till fgets followed by following */
   /* get the first token */
   token = strtok(line, ":");

   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token ); /* you would rather store these in array or whatever you want to do with it. */

      token = strtok(NULL, ":");
   }

The following code allocates memory for an array of 100 menuItems and reads the given file entries into it. You can actually count the number of lines in your input file and allocate as many entries (instead of hard coded 100):

#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<stdlib.h>

struct menuItem
{
    char itemCode[5];
    char itemName[50];
    float itemPrice;
    char itemDetails[50];
};

int main()
{
    char line[255];
    FILE *menuFile = fopen("addon.txt", "r");
    struct menuItem * items =
        (struct menuItem *) malloc (100 * sizeof (struct menuItem));
    struct menuItem * mem = items;

    while( fgets(line, sizeof(line), menuFile) != NULL )
    {
        char *token = strtok(line, ":");
        assert(token != NULL);
        strcpy(items->itemCode, token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        strcpy(items->itemName, token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        items->itemPrice = atof(token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        strcpy(items->itemDetails, token);
        items++;
   }

   free(mem);
   fclose(menuFile);
}

Upvotes: 1

Related Questions