Reputation: 619
I'm working on a homework project and i'm trying to store inventory data into a file.
The inventory data size shouldn't be too large cause technically no one is going to really use it.
I need to write these contents to a file:
• Item Description • Quantity on Hand • Wholesale Cost • Retail Cost • Date Added to Inventory
I am going to need to make an interface that allows me to do this:
• Add new records to the file • Display any record in the file • Change any record in the file
Struct would be the easiest way to go about this imo. If I can just figure out how to read / write structs to a file this should be really easy.
If you could provide a small example on how to do this I would really appreciate it.
Thanks!
Upvotes: 0
Views: 543
Reputation: 78683
If you don't mind really low level, you can just bit copy the structs in and out by casting a pointer to the struct to void*
and using sizeof()
to get the struct length. (IIRC their is a way to dump/read a void buffer to/from a file)
Note this ONLY works if the data has no pointers/references/etc.
I like C's IO better than C++'s so:
typedef struct { int hi; int mon; char[35] dat; } S;
S s;
S arr[22];
int f;
// write
f = open(/* I forget the args*/);
// one
if(sizeof(s) != write(f, &s, sizeof(s))) Error();
// many
if(sizeof(arr) != write(f, arr, sizeof(arr))) Error();
close(f);
// read
f = open(/* I forget the args*/);
// one
if(sizeof(s) != read(f, &s, sizeof(s))) Error();
// many
if(sizeof(arr) != read(f, arr, sizeof(arr))) Error();
close(f);
Upvotes: 2
Reputation: 30384
IOStream library does it
The ofstream class provides the interface to write data to files as output streams.
The ifstream class provides the interface to read data from files as input streams
Edit- Example
Upvotes: 1
Reputation: 13581
Ask your teacher, could you use boost library.
If yes, read boost serilization tutorial, it contains a simple examples: http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/tutorial.html
But if you want understand how to work with files, you should do this works without any help or boost.
If you want works with std::[io]fstreams you should decide what format you will support:
- text - for this case best way define operator<< and operator>> and use them for writing structure to file or reading;
- binary - your structure should be POD ( plain old data ) and doesn't should contain pointers - and you will use read and write streams methods.
example for binary file:
http://www.codeguru.com/forum/showthread.php?t=269648
Upvotes: 2
Reputation: 3190
I would go with XML; it's structured, it's text based so you can look at it with any text editor.
Upvotes: 0