opening file in c++ and acessing to the contents

i want to read a text file(notepad) file in c++(open it) and then print the content of it.what should i do?i mean where should i place the text file and which syntaxes should i use for that
You can place a file where you want. Use ifstream/ofstream/fstream (http://www.cplusplus.com/reference/iostream/ifstream/
http://www.cplusplus.com/reference/iostream/ofstream/
http://www.cplusplus.com/reference/iostream/fstream/) for that.

Code opening a file and printing it on the screen:
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
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;


int main()
{
	string fname;
	cout << "Input the file name:" << endl;
	getline(cin, fname);

	cout << "---" << endl;
	ifstream fin(fname.c_str());
	if(!fin)
	{
		cout << "Can't open the file \"" << fname << "\"." << endl;
		return 1;
	}

	copy(istreambuf_iterator<char>(fin), istreambuf_iterator<char>(), ostreambuf_iterator<char>(cout));
	cout << endl << "---" << endl;

	if(!fin)
	{
		cout << "Error while writing to the file." << endl;
		fin.clear();
	}

	fin.close();
	if(!fin)
	{
		cout << "Can't close the file \"" << fname << "\"." << endl;
		return 1;
	}

	return 0;
}
i used the codes that syuf wrote like below(my text file name that i want to open is "test2")
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
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;


int main()
{
	string fname;
	cout << "test2" << endl;
	getline(cin, fname);

	cout << "---" << endl;
	ifstream fin(fname.c_str());
	if(!fin)
	{
		cout << "Can't open the file \"" << fname << "\"." << endl;
		return 1;
	}

	copy(istreambuf_iterator<char>(fin), istreambuf_iterator<char>(), ostreambuf_iterator<char>(cout));
	cout << endl << "---" << endl;

	if(!fin)
	{
		cout << "Error while writing to the file." << endl;
		fin.clear();
	}

	fin.close();
	if(!fin)
	{
		cout << "Can't close the file \"" << fname << "\"." << endl;
		return 1;
	}

	return 0;
}


but it shows me the errors below:

Error: noname01.cpp(14,21):Could not find a match for 'std::getline(istream_withassign,std::basic_string<char,std::string_char_traits<char>,std::allocator<char>>)'
Error: noname01.cpp(24,26):Undefined symbol 'istreambuf_iterator'
Error: noname01.cpp(24,32):Expression syntax


what should i do know?
Topic archived. No new replies allowed.