Converting a String to A Character

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.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// print the content of a text file.Below is the code. 

#include <iostream>
#include <fstream>
#include <string>
using namespace 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;






}
Last edited on
fwrite(string.c_str(), 1, string.length(), pFile);

That should work. If not, use snprintf() or sprintf()

Typically, I'd just use the << operator.
file << string;
Last edited on
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"?
Your code is very strange. You've used a combination of C (FILE*) and C++ (FStream etc) file I/O methods. You should pick one and stick to it.

Simple writing out to a file of a string.
1
2
3
4
5
6
7
ofstream                   fFile;
fFile.open(sFullFileName.c_str(), mode);

string myData = "blah";
fFile << myData << endl;

fFile.close();
Topic archived. No new replies allowed.