文件输入输出 c++ 比较两个文本内容

先看一个小程序:

#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;
}
  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值