/*
C++的ifstream和ofstream
读文件写文件操作
*/
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
//文件名
string filename = "map_file.txt";
//如果文件名是string类型的调用c_str成员获取C风格字符串
//因为IO标准库是使用C风格字符串来作为文件名的
//此处打开文件也可以用ifstream的成员函数open来执行
ifstream infile(filename.c_str());
//检查文件是否打开成功
if(!infile)
{//如果没成功
throw runtime_error("file cannot open");
return -1;
}
else
{//文件打开成功,开始进行读文件操作
string s;
//fstream类中也有getline成员函数,不要弄错
//getline(infile,s);
while(!infile.eof())
{
//infile >> s;
getline(infile,s);
cout << s << endl;
}
}
infile.close();
//打开文件的时候可以用初始化
//ofstream outfile(filename.c_str(),ofstream::out | ofstream::app);
//也可以用ofstream的成员函数outfile.open(filename.c_str(),ofstream::out | ofstream::app)来进行打开文件
//如果写文件的模式直接是out,则会清除原来文件的内容,app模式是让文件指针定位到文件尾再开始写入
ofstream outfile;
outfile.open(filename.c_str(),ofstream::out | ofstream::app);
if(!outfile)
{//未成功打开文件
throw runtime_error("file cannot open");
return -1;
}
else
{
//在文件map_file.txt文件尾部进行写入
//有时,此处测试已经换行,文件尾部没有换行,在此需要换行写入
//outfile << endl;
//在文件中写入 111 222数据
outfile << "111 222" << endl;
//文件流一定要记着关闭
outfile.close();
}
return 0;
}