wiso said:
ok, but how I can use a fstream with io operation? I need to write to a file
(I don't know if it exists, without rewrite it) and alse to read it. Is
there a way to do all automatically? or I have to check if the file exists,
if not, create, ...
Anything "automatic" is by implication more complicated, not simpler.
If you prefer hacking a fragile program, go ahead, i'm not getting
involved.
In your case since you might not be use to coding with pos types and
seekg-ing within a file, i strongly discourage going that route. Keep
the system simple. As simple as humanly possible.
Then there is the issue of requirements. I got the append part, but
read what and store it where?
Note that the std::ios:

ut | std::ios::app mode combination will
create the file if non-existant and does append as expected.
I'ld suggest trying this:
a) write a class to store the filename and a vector container of
std::strings for storage
b) add a public append() function that opens the file with a
std:

fstream for output
c) add a public read() function that opens the file with a
std::ifstream for input (load vector)
d) add a public method that displays the contents of the vector
Thats a simple design. The file streams don't even need to be manually
closed.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
class Filer
{
std::string m_sfile;
std::vector< std::string > vs; // a)
public:
Filer(std::string s) : m_sfile(s), vs() { }
bool append(std::string& s) const // b)
{
// open file with std:

fstream and append s to it
// any error returns true
}
bool read() // c)
{
// open file with std::ifstream and load vector with
std::getline(...)
// any error returns true
}
void show() const // d)
{
// to std::cout, iterate through vector
}
};
int main(int argc, char* argv[])
{
Filer filer(file.txt);
if ( filer.append("whatever") ) // "whatever" could be taken from
argv[1]
{
std::cout << "error while writing to file.\n";
return -1;
}
if ( filer.read() )
{
std::cout << "error while reading file.\n";
return -1;
}
filer.show();
return 0;
}
Personally, i'ld prefer exceptions rather than passing errors, but lets
not get carried away.