C++中的文件流


ifstream用來從磁盤文件的輸入

ofstream用來向磁盤文件的輸出

fstream既可以用來輸入也可以用來輸出

1.向文件中寫入

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ifstream ifs/*("hello.txt")*/;//可以在常見這個變量時就初始化
    char buf[100];
    ifs.open("hello.txt",ios::in/*表明是寫入的狀態,不寫的化默認也是寫入的狀態*/);//也可以後來對他進行初始化
    if(!ifs)
    {
        cout<<"open feiled"<<endl;
    }
    ifs>>buf;//將ifs文件中的內容寫入到buf中去
    //ifs.getline(buf,100);
    cout<<buf<<endl;
}

2.將文件中的內容如初到屏幕上

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ofstream ofs;
    ofs.open("hello.txt"/*不寫默認是讀出的狀態*/);
    if(!ofs)
    {
        cout<<"失敗阿"<<endl;
    }
    char buffer[100]="asdfasdfasdfa";
    ofs<<buffer;//將buffer中的內容如初到ofs當中去
    ofs.close();//有open必須要有close();
    return 0;
}



發佈了50 篇原創文章 · 獲贊 76 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章