除了可以使用(<<)與(>>)運算子外
還可以使用類別內的函數
- get(),put():讀取或寫入特定單元
- getline():一次讀取特定數目字元數
- 檔案物件.get(ch); 從檔案讀取一個字元,並把它寫入ch字元變數
- 檔案物件.getline(str,N,’n’); 從檔案內最多讀取N-1個字元,或是讀取到’n’,並把他們存放到字串str中
- 檔案物件.put(ch); 將ch字元變數寫入檔案內
[code language=”cpp”]
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;fstream&amp;gt; //要載入&amp;lt;fstream&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;lt;&amp;lt; "字串已寫入" &amp;lt;&amp;lt; endl;
ofile.close();
}
[/code]

拷貝文字檔
會將先前建立的讀入
在寫入到另一個檔案
相當於文字檔的拷貝
接著再開啟拷貝的檔案
印在螢幕上面
Ex:
[code language=”cpp”]
#include <iostream>
#include <fstream> //要載入<fstream>標頭檔
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()&&ofile.is_open()){
cout << "檔案已開啟" << endl;
while(ifile1.get(ch))
ofile.put(ch);
cout << "拷貝完成" << endl;
}
else
cout << "檔案未開啟" << endl;
ofile.close();
ifile1.close();
ifstream ifile2("C:\\test2.txt",ios::in);
if(ifile2.is_open()){
cout << "檔案已開啟" << endl;
while(!ifile2.eof())
{
ifile2.getline(txt,80,’\n’);
cout << txt;
}
}
else
cout << "檔案未開啟" << endl;
ifile2.close();
}
[/code]