Re: Help with file writing please
* james@jgoode.co.uk:
Hi,
I'm new to C++, and coming from a dynamically-typed language, I'm
finding the data types difficult. My goal at the moment is to append
a string that is typed as a command line argument into the end of a
file, and I'm wondering if somebody could point me in the right
direction. At the moment, I can open the file and write a hard-coded
string using:
#include <fstream.h>
#include <iostream.h>
The above are pre-standard headers. Some modern compilers don't provide
them. Instead, use
#include <fstream>
#include <iostream>
#include <cstdlib>
int main()
Here you can declare arguments:
int main( int nArgs, char* args[] )
The argument strings are non-const because 'main' was inherited from C,
but that doesn't mean you can modify them.
The best thing you can do, as a newbie, is to immediately convert the
'main' arguments to a std::vector of std::string, and call a
C++-oriented main function (I usually call it 'cppMain'):
#include <cstddef> // std::size_t
#include <string> // std::string
#include <vector> // std::vector
// Your additional headers, e.g.
#include <fstream>
#include <iostream>
typedef std::vector<std::string> StringVector;
void cppMain( StringVector const& arguments )
{
using namespace std;
// Your code goes here, e.g.
for( size_t i = 0; i < arguments.size(); ++i )
{
cout << arguments.at( i ) << endl;
}
}
int main( int nArgs, char* args[] )
{
// This can be elaborated on, but as a minimum:
cppMain( StringVector( args, args + nArgs );
}
{
fstream fout("./output.txt",ios::out);
This code would go in 'cppMain' above.
Since you're trying to append text, it would make sense to use the
append mode.
Also, since you're only writing to the stream, it would probably be
better to use std::ofstream instead of the more general std::fstream.
fout<<"String";
fout.close();
}
I am using the g++ compiler under Debian to compile.
All help is appreciated,
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?