我們經常整些命令台程式,啥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;