Hello everyone. I am trying to convert a string to a character so that I can use the output file stream (fwrite) to write the characters from the string to a new file. In essence, I would like to write out the string object "g" in the code below to a new file. I am not sure how to accomplish this. Any help would be greatly appreciated. Thank you.
// print the content of a text file.Below is the code.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
FILE * pFile;
pFile = fopen ( "myfile2.bin" , "wb" );
// This is where we'll put the stuff we read from file
char buffer[ 800 ];
// Fill the buffer with zeros (char strings must be null-terminated)
fill_n( buffer, 800, '\0' );
ifstream infile;
ofstream outfile;
outfile.open("myfile2.txt");
infile.open ("myfile.txt", ifstream::in);
while (infile.good())
{
// Read as many as 100 bytes (chars) from the file and stick them in our array
infile.read( buffer, 800 );
// Convert that char array into a STL string, and show the user what we got.
string g( buffer );
string str2="trail";
string str="no";
g.replace(g.find(str2), str2.length(), str);
cout << g << " successfully read from file.\n";
fwrite (buffer, 1 , sizeof(buffer) , pFile );
fclose (pFile);
infile.close();
}
return 0;
}
How would I use file<<string: since I have "g" as the string that I want to write out to....In other words how would I code that for this specific code?
Also, If I use fwrite(string.c_str(), 1, string.length(), pFile); , how will it it know to write out the contents of "g"?