Writing to a text file

Hi,

I have a string I'd like to write to a non-existent textfile, and would like to create the file in the process.

Anybody have a few lines of source they can post which will show me how to do this?


Thanks,
Bob
ba272Asked:
Who is Participating?
 
AxterConnect With a Mentor Commented:
Hi ba272,
You can use fstream to open the file.

#include <fstream>
using namespace std;

fstream file("c:\\Myfile.txt", std::ios::out);

char data[] = "Hello World";
file.write(data, strlen(data));

std::string strData = "Hello World";
file.write(datstrData.c_str(), datstrData.size());


David Maisonave :-)
Cheers!
0
 
AxterCommented:
FYI:
If you only plan on writing to the file, you can use ofstream instead of fstream
0
 
ba272Author Commented:
If you could include the few lines needed to read in that text file, it would be appreciated.


Thanks,
Bob
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
ba272Author Commented:
Thanks David.  Would you mind giving me the file read piece as well?
0
 
AxterCommented:
#include <string>
#include <fstream>
using namespace std;

ifstream file("c:\\Myfile.txt");

std::string strData;

std::getline(file, strData); //Read a line in your text file
0
 
jkrConnect With a Mentor Commented:
#include <fstream>
#include <string>
using namespace std;

string read_file(char* filename) {

string strLine;

ifstream is(filename);

if ( is.is_open()) {

getline(is,strLine);
}

return strLine;
}

and call that like

string strContent = read_file("c:\\myfile.txt");
0
 
ba272Author Commented:
Thanks.  You both tied for the second piece, with different approaches.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.