1. 程式人生 > >檔案輸入輸出 c++ 比較兩個文字內容

檔案輸入輸出 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; }