-3

I'm reading products from a binary file. When I'm reading these products, I'm also counting the repetition of same products. At the end,I'm listing products and their numbers.

void product_counting_listing(FILE *fileptr)
{

Product p;

while(!feof(fileptr))
{
    fread(&p.p_code,sizeof(Product),1,fileptr);
    ??
}

rewind(fileptr);
while(!feof(fileptr)){
    printf("Product Code  Number of Product\n");
    printf("-------- --------");
    fread(&p.p_code,sizeof(Product),1,fileptr);
    printf("%d %d",p.p_code,?)

}

Any ideas for counting the same Products and listing them?

Arun A S
  • 6,421
  • 4
  • 29
  • 43
hisiti
  • 5
  • 5
  • 2
    First of all, don't do `while (!feof(...))` as it will seldom work as expected. Instead do e.g. `while (fread(...) == 1)`. Secondly, don't you mean to read the hole structure into `p`? Like `fread(&p, sizeof(p), 1, fileptr)`? Thirdly, if the file contains only the structure `Product`, the the size is a multiple of `sizeof(Product)` so you can get the number of structures by dividing the size of the file by `sizeof(Product)`. – Some programmer dude Mar 28 '15 at 15:50
  • typedef struct product_structure Product; Product p; Yes Joachim Pileborg.I just want to know how to count the same products.Any idea ? – hisiti Mar 28 '15 at 15:56

1 Answers1

0

while(!feof(fileptr)) is not a good approach as pointed by @Joachim Pileborg. You can find very fruitful information to why is it so at Why is “while ( !feof (file) )” always wrong?

Now assuming that the file contains multiple Product structure information, the simple approach to read all the structures would be

int bytesRead = 0;
while((bytesRead = fread(&p.p_code,sizeof(Product),1,fileptr)) > 0){
    //Print product information
    //Check for duplicate products
    memset(&p, '\0', sizeof(Product));
}

In the last line, you are resetting the Product structure to reuse for the next read.

Now in order to identify duplicate products, you need to maintain a list of all products that you read previously. And after reading each product you must iterate over all the previous products to find the duplicate ones. To maintain list of previous products, you can use link-lists. Or its up to you how you want to do that

Community
  • 1
  • 1
Yasir Majeed
  • 739
  • 3
  • 12