打开文件的方法

方法1:freopen

例:freopen("demo.txt","r",stdin);然后直接cin即可读取内容,且不需要关闭。

方法2:fstream

例:

读取:ifstream

写入:ofstream

打开:fstream

以字符形式输出文件中所以内容:

 1 #include <iostream>
 2 #include <string>
 3 #include <fstream>
 4 using namespace std;
 5 int main()
 6 {
 7     string str;
 8     ifstream myfile("C://Users//Linuas//Desktop//demo.txt");
 9     if (!myfile.is_open()) cout << "error!" << endl;
10     while (getline(myfile, str))
11         cout << str << endl;
12     myfile.close();
13     return 0;
14 }

猜你喜欢

转载自www.cnblogs.com/ljy1227476113/p/9908957.html