所謂的文字檔就是由ASCII碼或是純文字組成的檔案
在C++中
可以利用(<<)運算子將資料寫進檔案中
可以利用(>>)運算子將資料從檔案讀出
將資料寫入文字檔
檔案目錄應利用雙斜線隔開
因為在字串中
會有使用跳脫字元的嫌疑
可避免很多錯誤
Ex:
#include &amp;lt;iostream&amp;gt; #include &amp;lt;fstream&amp;gt; //要載入&amp;lt;fstream&amp;gt;標頭檔 using namespace std; int main(){ ofstream onf("C:\\test.txt",ios::out); if(onf.is_open()){ cout &amp;lt;&amp;lt; "檔案已開啟" &amp;lt;&amp;lt; endl; onf &amp;lt;&amp;lt; "錦江春色來天地" &amp;lt;&amp;lt; endl; onf &amp;lt;&amp;lt; "玉壘浮雲變古今" &amp;lt;&amp;lt; endl; cout &amp;lt;&amp;lt; "已寫入檔案" &amp;lt;&amp;lt; endl; } else{ cout &amp;lt;&amp;lt; "檔案未開啟" &amp;lt;&amp;lt; endl; } onf.close(); }
打開該純文字檔可以發現剛剛的資料已經寫在裡面
將資料附加到已存在的檔案
Ex:
#include <iostream> #include <fstream> //要載入<fstream>標頭檔 using namespace std; int main(){ ofstream afile("C:\\test.txt",ios::app); //建立可以附加檔案的物件 if(afile.is_open()){ cout << "檔案已開啟" << endl; afile << "北極朝近終不改" << endl; afile << "西山寇盜莫相侵" << endl; cout << "已寫入檔案" << endl; } else{ cout << "檔案未開啟" << endl; } afile.close(); }