文件的读写

为了读而打开文件,要创建一个ifstream对象,他的用发与cin相同,为了写而打开文件,要创建一个ofstream对象,用法与cout相同。一旦打开一个文件,就可以像处理其他iostream对象那样对它进行读写。

在iosream库中,一个十分有用的函数是getline(),用它可以读入到string对象中(以换行符结束)。getline()的第一个参数是ifstream对象,从中读取内容,第二个参数是stream对象。函数调用完成后,string对象就装载了一行内容。

//FirstMain.cpp and FirstMain.cpp is the name of sourse file

#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream in("FirstMain.cpp");
ofstream out("FirstMain2.cpp");
string s;
while(getline(in,s))
cout<<s<<"\n";
}


#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream in("FirstMain.cpp");
ofstream out("FirstMain2.cpp");
string s,line;
while(getline(in,line))
s+=line+"\n";
cout<<s;
}

这两个例子会在控制台输出源代码。

你可能感兴趣的:(文件的读写)