先看一个小程序:
#include <fstream>
#include <iostream>
using namespace std;
int main(){
ofstream op("text1.txt");
op<<"hello world!";
op.close();
return 0;
}
这个程序将在当前运行目录下生成一个text1.txt文件,其内容为”hello world!”。
ofstream,即 output file stream(输出文件流),是fstream头文件中的类,op是该类的对象。
既然打开了一个流文件,就应有关闭它的语句,op.close()实现了这一功能。
当然,也可以用下面的语句,将变量的值写进文件:
ofstream op("text1.txt");
string s="hello world!";
op<<s;
op.close();
ofstream用于写入文件,那么,如何读取文件呢?
不难猜到,ifstream,即 input file stream ,可以实现这一功能:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
ifstream op("text1.txt");
string s;
while(!op.eof())
s+=op.get();
cout<<s<<endl;
op.close();
return 0;
}
我们可以用读取文件实现某些功能,例如,比较两个txt文件内容是否相同:
#include <iostream>
#include <fstream>
#include <string>
int main(){
ifstream op;
string str1,str2;
op.open("text1.txt");
while(!op.eof())
str1+=op.get();
op.close();
op.open("text2.txt");
while(!op.eof())
str2+=op.get();
op.close();
if(str1==str2)
puts("YES");
else
puts("NO");
return 0;
}