954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Need help! how to store file data in a structure?

Need help guys! my problem is i cannot store file data into an array of structures. I can already read the file data and also tokenized it so as to separate data. here is content of the file that i am reading:

200001, hamburger, 30.50
100000, cheeseburger, 21.00

the name of the file is inventory.ini

i can already read the file with this output:

200001
hamburger
30.50

100000
cheeseburger
21.00

i used the strtok() function.

the problem is i cannot store these data in a structure! here is my code:

header file is saved separately but IN THE SAME PATH as to where my code is saved:

typedef struct productDescriptionType
{
char inventory_code[7];
char item_description[20];
float unit_price;
} INVENTORY;
this is the inventoryStruct.h

this is the main program
#include
#include
#include
#include "inventoryStruct.h"

struct productDescriptionType* product; // inventory array

void printInfo(INVENTORY product) //just to check if i successfully transferred the file data to the structure. apparently i still cant reach this part. :(
{
printf("%s",product.inventory_code);
printf("%s",product.item_description);
printf("%f",product.unit_price);
}

int main()
{
INVENTORY prodDesc; //declare struct

int ctr_file; //sample number of lines in the file

FILE *ptr; //pointer to open inventory.ini

ctr_file = 4; //sample line number
int i; //index for the inventory array

char tempStorage[30]; //temporary storage of the tokenized data
char * tokenized; //tokenized data value is stored in this pointer

product = (struct productDescriptionType*) malloc(ctr_file * sizeof(struct productDescriptionType)); // allocate memory for the structure

ptr = fopen("inventory.ini","r"); //read .ini file

if ( ptr==NULL )
{
perror("Error...");
system("pause");
exit(1);
}

for(i = 0;i

nagarayan
Newbie Poster
4 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

Need help guys! my problem is i cannot store file data into an array of structures. I can already read the file data and also tokenized it so as to separate data. here is content of the file that i am reading:

200001, hamburger, 30.50 100000, cheeseburger, 21.00

the name of the file is inventory.ini

i can already read the file with this output:

200001 hamburger 30.50

100000 cheeseburger 21.00

i used the strtok() function.

the problem is i cannot store these data in a structure! here is my code:

header file is saved separately but IN THE SAME PATH as to where my code is saved:

typedef struct productDescriptionType { char inventory_code[7]; char item_description[20]; float unit_price; } INVENTORY; this is the inventoryStruct.h

this is the main program #include #include #include #include "inventoryStruct.h"

struct productDescriptionType* product; // inventory array

void printInfo(INVENTORY product) //just to check if i successfully transferred the file data to the structure. apparently i still cant reach this part. :( { printf("%s",product.inventory_code); printf("%s",product.item_description); printf("%f",product.unit_price); }

int main() { INVENTORY prodDesc; //declare struct int ctr_file; //sample number of lines in the file FILE *ptr; //pointer to open inventory.ini ctr_file = 4; //sample line number int i; //index for the inventory array char tempStorage[30]; //temporary storage of the tokenized data char * tokenized; //tokenized data value is stored in this pointer product = (struct productDescriptionType*) malloc(ctr_file * sizeof(struct productDescriptionType)); // allocate memory for the structure ptr = fopen("inventory.ini","r"); //read .ini file if ( ptr==NULL ) { perror("Error..."); system("pause"); exit(1); } for(i = 0;i

Your first issue (why the program won't compile) is you're treating the variable "prodDesc" as an array and it has not been declared as such.

I can't see anywhere in your code (unless I'm going blind) where you are actually reading the file. You use the scanf() function which takes it's input from stdin.

You're using tempStorage in your strtok call, but how is this field being set in the first place?

You have many other errors, but I think it's best that you sort out exactly what you want to do with this program first and learn how to do things like declare an array of structures, read a file, tokenise a string and assign data to structure members.

You need to:

- read a record from the input file (perhaps using the fgets function) - tokenise the string obtained via the fgets call - iterate through the tokens and assign each token to a member in your structure. - repeat until EOF

Whilst developing the program, take small bites. Don't try and write the whole program in one hit. Make sure you are opening/reading the file correctly first. Then learn how to use strtok correctly (a Google will help out). Then learn how to assign data to the member of structure. In each iteration, make sure you have a working program before moving on to writing the next "feature" of the program.

One final thing - when posting code, use code tags.

Cheers JD

yellowSnow
Posting Whiz in Training
203 posts since Jul 2009
Reputation Points: 651
Solved Threads: 35
 

Your first issue (why the program won't compile) is you're treating the variable "prodDesc" as an array and it has not been declared as such.

I can't see anywhere in your code (unless I'm going blind) where you are actually reading the file. You use the scanf() function which takes it's input from stdin.

You're using tempStorage in your strtok call, but how is this field being set in the first place?

You have many other errors, but I think it's best that you sort out exactly what you want to do with this program first and learn how to do things like declare an array of structures, read a file, tokenise a string and assign data to structure members.

You need to:

- read a record from the input file (perhaps using the fgets function) - tokenise the string obtained via the fgets call - iterate through the tokens and assign each token to a member in your structure. - repeat until EOF

Whilst developing the program, take small bites. Don't try and write the whole program in one hit. Make sure you are opening/reading the file correctly first. Then learn how to use strtok correctly (a Google will help out). Then learn how to assign data to the member of structure. In each iteration, make sure you have a working program before moving on to writing the next "feature" of the program.

One final thing - when posting code, use code tags.

Cheers JD

thanks so much JD! anyway i was successful in storing the file in my structure. though the weird thing is the second unit_price amount can't be read by the program! and the program still reads the delimiter (,) in the description part.here is the output:

code: 000001<<<<<.and here is my new code:

#include "inventoryStruct.h" //header file of struct
#include
#include

void printInfo( INVENTORY product ) //function to print the structure data
{
printf("\ncode: %s\n", product.inventory_code);
printf("description : %s\n", product.item_description);
printf("price: %.2f\n",product.unit_price);
}
int main()
{
INVENTORY prodDesc[5]; //text file has 4 sets of data.i just assumed that i know the size of the file
int i=0;

FILE * ptr; //pointer to open inventory.ini
char array[50];
char * tokenized;

char price[6];

ptr = fopen("inventory.ini","r");

if(ptr == NULL)
{
perror("Error..");
system("pause");
exit(1);
}

while(!feof(ptr))
{
prodDesc[i].inventory_code[strlen(prodDesc[i].inventory_code)-1] = '\0'; //missing link!.haha transferring inventory.ini data to structure
fscanf(ptr,"%s",prodDesc[i].inventory_code);
prodDesc[i].item_description[strlen(prodDesc[i].item_description)-1] = '\0'; // tried to remove delimiter for the desciption but the comma can still be seen in the output
fscanf(ptr,"%s",prodDesc[i].item_description);
fscanf(ptr,"%s",price); // i just treated the unit price as a string
prodDesc[i].unit_price = atof(price); // used atof to treat the string unit price as a float

i++; //increment index array of struct
}
for ( i = 0; i < 4; i++ )
{
printInfo(prodDesc[i]);
}
system("pause");
return 0;
}

i used the same header file for the struct. i didnt used the strtok() anymore.please help :(

nagarayan
Newbie Poster
4 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

nagarayan> please help
If you want to get help, don't ignore the rules. Learn how to post code

Aia
Nearly a Posting Maven
2,392 posts since Dec 2006
Reputation Points: 2,224
Solved Threads: 218
 

nagarayan, I ran your code and for the life of me I don't understand how you think that this program actually works. Generally speaking, the fscanf() function is not a good choice for reading text files.

Please read the suggestions from my previous post again!

Here is some code for you to try. It reads four records (comma delimited), tokenises each record and loads each field into the members of the INVENTORY structure and then prints them to the screen. It doesn't do exactly what you're trying to do but it's close. Make changes to the code to suit your requirements.

Here is the input file (inventory.ini) that I used:

000001,hamburger,30.50
000002,cheeseburger,21.00
100001,frenchfries,21.00
200001,icedtea,17.00

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

typedef struct productDescriptionType {
    char inventory_code[7];
    char item_description[20];
    float unit_price;
} INVENTORY;


int main(void) {

    INVENTORY product;
    FILE *fp;
    char *rec;
    char *token;
    char *flds[3];
    int i;

    if ((fp = fopen("inventory.ini", "r")) == NULL) {
        printf("Error opening file!");
        return EXIT_FAILURE;
    }

    rec = malloc(BUFSIZ);
    while (fgets(rec, BUFSIZ, fp) != NULL) {
        rec[strlen(rec) - 1] = '\0';
        i = 0;
        token = strtok(rec, ",");
        while (token != NULL) {
            flds[i] = token;
            i++;
            token = strtok(NULL, ",");
        }

        strcpy(product.inventory_code, flds[0]);
        strcpy(product.item_description, flds[1]);
        product.unit_price = atof(flds[2]);

        printf("Inventory code = %s\n", product.inventory_code);
        printf("Item description = %s\n", product.item_description);
        printf("Unit price = %.2f\n\n", product.unit_price);
    }

    free(rec);
    fclose(fp);
    return 0;
}
yellowSnow
Posting Whiz in Training
203 posts since Jul 2009
Reputation Points: 651
Solved Threads: 35
 
nagarayan> please help If you want to get help, don't ignore the rules. Learn how to post code


im so sorry.lesson learned

nagarayan
Newbie Poster
4 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

nagarayan, I ran your code and for the life of me I don't understand how you think that this program actually works. Generally speaking, the fscanf() function is not a good choice for reading text files.

Please read the suggestions from my previous post again!

Here is some code for you to try. It reads four records (comma delimited), tokenises each record and loads each field into the members of the INVENTORY structure and then prints them to the screen. It doesn't do exactly what you're trying to do but it's close. Make changes to the code to suit your requirements.

Here is the input file (inventory.ini) that I used:

000001,hamburger,30.50 000002,cheeseburger,21.00 100001,frenchfries,21.00 200001,icedtea,17.00

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

typedef struct productDescriptionType {
    char inventory_code[7];
    char item_description[20];
    float unit_price;
} INVENTORY;


int main(void) {

    INVENTORY product;
    FILE *fp;
    char *rec;
    char *token;
    char *flds[3];
    int i;

    if ((fp = fopen("inventory.ini", "r")) == NULL) {
        printf("Error opening file!");
        return EXIT_FAILURE;
    }

    rec = malloc(BUFSIZ);
    while (fgets(rec, BUFSIZ, fp) != NULL) {
        rec[strlen(rec) - 1] = '\0';
        i = 0;
        token = strtok(rec, ",");
        while (token != NULL) {
            flds[i] = token;
            i++;
            token = strtok(NULL, ",");
        }

        strcpy(product.inventory_code, flds[0]);
        strcpy(product.item_description, flds[1]);
        product.unit_price = atof(flds[2]);

        printf("Inventory code = %s\n", product.inventory_code);
        printf("Item description = %s\n", product.item_description);
        printf("Unit price = %.2f\n\n", product.unit_price);
    }

    free(rec);
    fclose(fp);
    return 0;
}


your amazing! thanks a lot! my program actually works, though my code is very confusing and i am the only one who understands it :sad: . i declared my structure on a different file as a header. and i just declared #include "" which includes the struct declaration. the problems on my code are: the 2nd unit price can't be read and i can't eliminate the comma on the item description. anyway, you solved my problem. thanks a lot! :)

nagarayan
Newbie Poster
4 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You