0

I am trying to update my quantity in stock which is a struct attribute saved in a file, i wish to add the order quantity which is also a struct attribute saved in a filed, I tried this line of code, but is not giving any change, could anyone give me any ideas?

fread(arrayBatch, sizeof(struct product), numberOfStructsProd, prodFile);
int k;
for(k=0; k< numberOfStructsProd; k++)
{
    update = arrayBatch[k].quantityInStock + arrayBatch[k].orderQuantity;
    arrayBatch[k].quantityInStock = update;
    printf("Batch file updated...\n");
}
fwrite(arrayBatch, sizeof(struct product), numberOfStructsProd, prodFile);
user1928374
  • 71
  • 2
  • 9
  • You need to write the change back into the file... The objects you update are in memory. – StoryTeller - Unslander Monica Jan 10 '13 at 19:55
  • I have done that, sorry forgot to paste the last line of code it is this one, I guess it's correct? fwrite(arrayBatch, sizeof(struct product), numberOfStructsProd, prodFile); – user1928374 Jan 10 '13 at 19:57
  • You need to close the file after you read it, and reopen it in "w" mode. – StoryTeller - Unslander Monica Jan 10 '13 at 19:59
  • I did close it didn't paste it sorry, so I should reopen the file in write mode in the same function then ? and thanks a lot :) – user1928374 Jan 10 '13 at 20:00
  • That should do it. But only after you read what you need from it, "w" mode truncates the file. – StoryTeller - Unslander Monica Jan 10 '13 at 20:01
  • speaking of which, the more idiomatic way would have been to open the file in "r+" mode, and do a seek to the begining before writing. You should prefer that solution for performance sake. – StoryTeller - Unslander Monica Jan 10 '13 at 20:09
  • If you're using Windows, [this SO question](http://stackoverflow.com/questions/14279658/mixing-read-and-write-on-python-files-in-windows/14280029#14280029) might be relevant to you. It regards Python, but the root cause is an issue in the Windows file libraries. Essentially if you mix reads and writes on the same filehandle it's good practice to put a seek or flush between them. This only applies if you open in `r+` mode, if you reopen the file you need not worry about it (although that is, as StoryTeller points out, less efficient). – Cartroo Jan 12 '13 at 09:55

0 Answers0