Actually this is not an assignment or anything... School days are done... Still there's lot of things that i don't know...

I just need some ideas on how to make an inventory using files...
Basically, the file contains the name of the "Items" "Prices" and the "Amount"...

I want to access them using file reading...I actually know how to write to text file and read from it... But i don't know how edit them... Example...

[B]myFile [/B] contains --> Item    Price     Pieces
                      Pencil   $1        50 
                      Eraser  $2        50
[1] Pencil [2] Eraser  [3] Edit Price
 Enter item: 1
 Enter #pcs: 2
 //then in [B]myFile[/B] the pieces of pencil will reduce to 48...
// if the user choose 3 then he can access [B]myFile [/B]and edit the price...

Can anyone enlighten me please? I really wanted to learn...

(1) use fopen() to read all items from the file into a structure in memory, then fclose() the file immediately

(2) do whatever manipulations you want on the memory structure.

(3) when the user is ready to commit a change (either singly or in a batch) reopen the file using fopen() to write all items from the data structure back into the file, then fclose().

(4) repeat 2 - 3 as often as desired until exiting the program.


another method you may see or be told, is to open the file for simultaneous read and write access, and perform reads and writes on the fly. this is more complicated, requires the use of other commands like "rewind" and/or "fseek" and opens up many opportunities for you to permanently corrupt your data file. I don't recommend this method at all.

.

You will find it easiest using fixed lengths for each field, and thus a fixed length for each record. Every item then fits nicely into this struct (where each struct member is a field, and each record is a struct. A simple example:

struct item {
  long  prod_num;
  char name[32];      //char *name - not a fixed width
  char supplier[32];  //not char *supplier
  int in_stock;
  float price;
}

You can now read and write from the file in binary mode, with any record you want, one record at a time. While this is a relatively safe way to work this, recognize that the first disk error you have, may make the entire inventory file, no good.

So, you always have two things: 1) a back up file that is not being written to daily, and 2) a list of all the transactions that have occurred during the day. Using these two things, you can recreate the inventory system, should the main file be damaged.

Always best if your struct is a multiple of 2, and preferably a multiple of 32 or 64.bytes in total.

If you can load all your inventory into memory, do so. That still requires safeguards from things like power outages, etc. Backups are essential!! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.