STL檔案操作簡介

來源:互聯網
上載者:User

我們經常整些命令台程式,啥cout<<, cin>>之類的.而實際項目中基本上不會要你用cout啥的在螢幕上輸出.而在硬碟上讀寫檔案操作倒很多.

假如沒用到MFC或者win API咋去讀寫檔案呢.STL中提供了一些類可以讓你很方便的讀寫檔案.比較常見有有三個:

fstream :可以寫也可以讀檔案

ofstream: 只能寫檔案

ifstream:只能讀檔案

 

寫檔案

#include <iostream>

#include <string>

#include <fstream>  //記得引用該標頭檔

using namespace std;

 

int main()

{

 //用fstream來寫檔案

  string filePath = "D:\\arwen.txt";

  fstream writeFile;

  writeFile.open( filePath, ios::out);  //開啟檔案,如果檔案不存在則建立該檔案.

  writeFile<<"hello arwen."<<endl;  //往檔案中寫入內容,如果開啟的檔案中之前有內容會被覆蓋.如果只想在原有內容上新增內容則要這樣開啟檔案

                                                  //writeFile.open(filePath, ios::out | ios::app);

  fstream.close();

 

//用ofstream來寫檔案

 string filePath = "D:\\tmp.txt";

 ofstream fileWriteOnly;

 fileWriteOnly.open( filePath, ios::out);

 fileWriteOnly << "i am temp file"<<endl;

fileWriteOnly.close();

 

讀檔案

//用fstream讀檔案

string filePath = "D:\\arwen.txt";

fstream readFile;

readFile.open( filePath, ios::in);

char ch;

while( readFile.get(ch) )

       cout<<ch;

readFile.close();

 

//用ifstream讀檔案

string filePath = "D:\\tmp.txt";

ofstream fileReadOnly;

fileReadOnly.open( filePath, ios::in);

while( fileReadOnly.get(ch) )

cout<<ch;

 

fileReadOnly.close();

 

return 0;

}

 

上面讀檔案是一次讀一個char,也可以一次讀一行.

例如

string filePath = "D:\\tmp.txt";

ofstream fileReadOnly;

fileReadOnly.open( filePath, ios::in);

char myString[100] = {'0'};

 

while( fileReadOnly.getline(myString , 1000) ) //第二個參數是緩衝區大小

    cout<<myString;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.