[檔案處理] get(),getline(),put()

除了可以使用(<<)與(>>)運算子外
還可以使用類別內的函數

  • get(),put():讀取或寫入特定單元
  • getline():一次讀取特定數目字元數
  • 檔案物件.get(ch);                    從檔案讀取一個字元,並把它寫入ch字元變數
  • 檔案物件.getline(str,N,’n’);    從檔案內最多讀取N-1個字元,或是讀取到’n’,並把他們存放到字串str中
  • 檔案物件.put(ch);                   將ch字元變數寫入檔案內
Ex:

[code language=”cpp”]
#include &amp;amp;lt;iostream&amp;amp;gt;
#include &amp;amp;lt;fstream&amp;amp;gt; //要載入&amp;amp;lt;fstream&amp;amp;gt;標頭檔
using namespace std;

int main(){

char txt[]={"錦江春色來天地,玉壘浮雲變古今。北極朝近終不改,西山寇盜莫相侵。"};
ofstream ofile("C:\\test.txt",ios::out);

int i=0;

while(txt[i]!=’\0’)
{
ofile.put(txt[i]);
i++;

}

cout &amp;amp;lt;&amp;amp;lt; "字串已寫入" &amp;amp;lt;&amp;amp;lt; endl;

ofile.close();

}
[/code]

打開該純文字檔 可以發現剛剛的資料已經寫在裡面

拷貝文字檔

會將先前建立的讀入

在寫入到另一個檔案

相當於文字檔的拷貝

接著再開啟拷貝的檔案

印在螢幕上面

Ex:

[code language=”cpp”]
#include &lt;iostream&gt;
#include &lt;fstream&gt; //要載入&lt;fstream&gt;標頭檔
using namespace std;

int main(){

char txt[80],ch;

ifstream ifile1("C:\\test.txt",ios::in);
ofstream ofile("C:\\test2.txt",ios::out);

if(ifile1.is_open()&amp;&amp;ofile.is_open()){

cout &lt;&lt; "檔案已開啟" &lt;&lt; endl;

while(ifile1.get(ch))
ofile.put(ch);

cout &lt;&lt; "拷貝完成" &lt;&lt; endl;

}

else
cout &lt;&lt; "檔案未開啟" &lt;&lt; endl;

ofile.close();
ifile1.close();

ifstream ifile2("C:\\test2.txt",ios::in);

if(ifile2.is_open()){

cout &lt;&lt; "檔案已開啟" &lt;&lt; endl;
while(!ifile2.eof())
{

ifile2.getline(txt,80,’\n’);
cout &lt;&lt; txt;

}

}

else
cout &lt;&lt; "檔案未開啟" &lt;&lt; endl;

ifile2.close();

}

[/code]

有疑問? 留個言吧!

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

%d 位部落客按了讚: