使用fstream类处理流文件
关键词: fstream()、open()、close()
使用 ofstream() 新建一个文本文件并向其中写入文本
/*************
writing
**************/
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main()
{
ofstream myfile;
myfile.open("test.txt",ios_base::out);//ios_base::out open
if(myfile.is_open())//is_open() check if open succeed
{
cout << "File open Succeed! " << endl;
myfile << "my first text file" << endl;
myfile << "I am PIG three." << endl;;
cout << "Finished writing into file,will close now" << endl;
myfile.close();//关闭流文件,以保存修改内容
}
else cout << "File open failed:: check if your file is in right" << endl;
return 0;
}
使用open()及 >> 运算reading 写入的文本文件
/*************
reading test.txt
***************/
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("test.txt",ios_base::in);//只读
if(myfile.is_open())
{
cout << "File open Succeed! As follow: " << endl;
string temp;
while(myfile.good())//good()判断文件是否读完,读完退出循环
{
getline(myfile, temp);//一行一行读
cout << temp << endl;
}
cout << "Finished reading file,will close now" << endl;
myfile.close();//关闭流文件,以保存修改内容
}
else cout << "File open failed:: check if your file is in right" << endl;
return 0;
}
test.txt
//my first text file
//I am PIG three.
输出
技巧
在线OJ时,常在本地调试代码,可以通过文件的形式读入测试用例,降低人工输入数据的时间复杂度。
#ifdef ONLINE_JUDGE
#else
#include <fstream>
#endif
#ifdef ONLINE_JUDGE
#else
ifstream cin("test.txt")
#endif
(全文完)