Rdbuf() function help!

First I output data to a the file "f1.txt" with output file stream f1out. Then I want to copy the data from file "f1.txt" to the file "f2.txt". Then I want to output the content of both files through standard output to the monitor.
My problem is that it does not output anything from the files at all. I think that the rdbuf() is causing this but I do not know why. How can I fix this but still use the rdbuf() function?

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
#include <iostream>
#include <fstream>

using namespace std;

int main () {
	ofstream f1out("f1.txt");
	ifstream f1in("f1.txt");
	ofstream f2out("f2.txt");
	ifstream f2in("f2.txt");

	char fname[101];
	char ename[101];
	int age;
	char c;

	cout << "Enter your first name: "; 
	cin >> fname;
	cout << "Enter your last name: ";
	cin >> ename;
	cout << "Enter your age: ";
	cin >> age;

	f1out << "First name: " << fname << endl
		<< "Last name: " << ename << endl
		<< "Age: " << age << endl;

	f2out << f1in.rdbuf();

	cout << "Content of file 1---------------------: " << endl;
	cout << f1in.rdbuf();
	cout << "Content of copied file 2-------------------:" << endl;
	cout << f2in.rdbuf();

	system("pause");
	exit(EXIT_SUCCESS);
	return 0;
}
Last edited on
i just searched rdbuf in the reference of this site and they give an example in which they backup cout's streambuf and reset it again after the operations. so i believe that you should do that too to get output.
here is the link:
http://www.cplusplus.com/reference/iostream/ios/rdbuf/
I tried and did what the reference shows, but this does not solve the problem that it does not print out the content of the two files. The problem is still there. Do any others know why?
Last edited on
rdbuf() returns the private internal buffer of the stream class instance. You actually have to fill that buffer with read() readsome() operator>> etc. If you simply create a filestream object and then call rdbuf() it will not have any contents.

Edit: in the example from the link above the buffer is filled with the line:
 
 cout << "This is written to the file";


As the internal buffer for the file stream object was swapped with the internal buffer for cin the string is sent to file instead of stdout.
Last edited on
I tried to do the same thing today and somehow I made it work. I will check your answers the next time as I encounter this problem. Thanks for your help guys.
Last edited on
Topic archived. No new replies allowed.