How do I save a file to disk in C ++?
I am making an application that simulates an ATM machine (its completely trivial). I had a little problem saving my transactions to the hard drive. Two main questions: A) Should I save it as DB or text file, B) How can I save to disk using DB or txt format in STL C ++ (I really don't want to use third line, batch library, but I if necessary).
Thanks in advance: -)
a source to share
something like that:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
However, you might want to link SQLite to your application as it is the most widely used database in the world: http://www.sqlite.org/capi3.html
It is durable and is used by many mobile devices, Thunderbird and Firefox.
a source to share
The database seems more deadly for this, just write one line to the file per transaction. A useful link for C ++ streaming classes can be found here http://www.cppreference.com/wiki/io/start - which also only provides a good general reference for C ++
a source to share
A) Should I save it as DB or text file,
It will depend on the use / application - you are the best judge.
B) How to save to disk using DB or txt format in STL C ++ (I don't want to use a third party library, but if needed).
STL doesn't provide you with a database driver. This allows you to create output streams and save data as files on disk. If you plan on writing out a DB file, you need to know about the internal DB format and write a binary file.
a source to share
If you are fairly new to C ++, I would suggest just logging your transactions to a text file. The easiest way to do it in C ++ is to use the tactic:
#include <fstream>
void write_transaction(ofstream& file, transaction t)
{
file << t.somedata;
}
int main(int argc, char** argv)
{
ofstream file;
file.open("transactions.txt");
transaction t;
t.data = "Something";
write_transaction(file, t);
file.close();
return 0;
}
Of course, a transaction is defined as something that contains all of your transaction data and is likely to be stored in an array. write_transaction then writes out all the important data.
a source to share
For C ++, you can have a look at fstream .
If you can use an external (but very standard) library, boost serialization can help you a lot - especially if you want to dump the contents of STL containers (not obvious if that's what you want to do from your question).
Even if you can't afford an external library, I highly recommend looking at how api serialization is designed.
a source to share