how to save to a text file

M

mov

I am a newbie, please someone tell me how to create a text file and save it
using c++.
thanks
 
V

Victor Bazarov

mov said:
I am a newbie, please someone tell me how to create a text file and save it
using c++.

Create an std::eek:fstream object. Write to it using <<.

#include <fstream>
int main()
{
std::eek:fstream os("text_file.txt");
os << "Hello world!";
}

V
 
A

Aggro

Victor said:
#include <fstream>
int main()
{
std::eek:fstream os("text_file.txt");

// Check could we open file for writing or not
if( os )
{
os << "Hello world!";
}
else
{
// This could happen for example if file already exists
// and it is read-only or user doesn't have permission to write
// into it.
std::cout << "Failed to open file";
}
 
V

Victor Bazarov

Aggro said:
// Check could we open file for writing or not
if( os )
{
os << "Hello world!";
}
else
{
// This could happen for example if file already exists
// and it is read-only or user doesn't have permission to write
// into it.
std::cout << "Failed to open file";

I'd actually output that to std::cerr ...

V
 
K

Karthik Kumar

Victor said:
Create an std::eek:fstream object. Write to it using <<.

#include <fstream>
int main()
{
std::eek:fstream os("text_file.txt");
os << "Hello world!";
}

V

Isn't it important to close the file after writing it ?

os.close(); ?
 
J

John Harrison

Isn't it important to close the file after writing it ?

os.close(); ?

NO!!

This is C++, the ofstream destructor does that for you. This does seem to be
a very common misunderstanding however. I guess programmers get it drilled
into them from an early age that you must always close files that no-one
imagines that it could be any different in C++.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,968
Members
47,518
Latest member
TobiasAxf

Latest Threads

Top