關於c 檔案流與二進位制的讀入寫出 二

2021-06-26 19:19:05 字數 2149 閱讀 7410

一、使用streamwriter類寫入檔案

應用filestream類需要許多額外的資料型別轉換操作,十分影響效率。本節將介紹另外一種更為簡單實用的類寫入方法,即streamwriter類。streamwriter類允許直接將字元和字串寫入檔案。streamwriter類的構造方法一共有7種,此處只介紹常用的三種,如下所示,以及streamwriter類的常用方法:

建構函式:

streamwriter(stream)  (用utf-8編碼及預設緩衝區大小,為指定的流初始化streamwriter類的乙個新例項)

streamwriter(string)  (使用預設編碼和緩衝區大小,為指定路徑上的指定檔案初始化streamwriter類的新例項)

streamwriter(string,boolean)  (使用預設編碼和緩衝區大小,為指定路徑上的指定檔案初始化streamwriter類的新例項。如果該檔案存在,則可以將其改寫或向其追加。如果該檔案不存在,則此建構函式將建立乙個新檔案

streamwriter的方法介紹:

close  (關閉當前的streamwriter物件和基礎流)

write  (寫入流)

writeline  (寫入過載引數指定的某些資料,後跟行結束符)

例項介紹:

public class streamwritertest

public static void main()

try//保留檔案現有資料,以追加寫入的方式開啟c:\file.txt檔案

streamwriter m_sw = new streamwriter(@ "c:\file.txt ",true);

//向檔案寫入新字串,並關閉streamwriter

m_sw.writerline("another file operation method");

m_sw.close();

catch(ioexecption ex)

console.writeline("there is an io exception!");

console.writeline(ex.message);

console.readline();

return;

console.writeline("write to file succeed!");

console.readline();

return;

二、使用streamreader類讀取檔案

相對於streamwriter類,streamreader類提供了另一種從檔案中讀取資料的方法。streamreader類的應用方式非常類似於streamwriter類,其常見建構函式與常用方法如下:

streamreader(stream)  (為指定的流初始化streamreader類的新例項)

streamreader(string)  (為指定的檔名初始化streamreader類的新例項)

方法:close  (關閉streamreader物件和基礎流,並釋放與讀取器關聯的所有系統資源)

read  (讀取輸入流中的下乙個字元或下一組字元)

readline  (從當前流中讀取一行字元並將資料作為字串返回)

readtoend  (從流的當前位置到末尾讀取流)

例項:public class streamreadertest

public static void main()

try//以絕對路徑方式構造新的streamreader物件

streamreader  m_sw =new streamreader(@ "c:\file.txt");

//用readtoend方法將c:\file.txt中的資料全部讀入字串m_data中,並關閉streamreader

string m_data = m_sw.readtoend();

console.writeline(m_data);

m_sw.close();

catch(ioexception ex)

console.writeline("there is an io exception!");

console.writeline(ex.message);

console.readline();

return;

console.readline();

return;

檔案操作 二進位制檔案讀入

time limit 1 sec memory limit 128 mb submit 88 solved 24 submit status web board 現有100名學生的姓名 name 學號 num 英語 english 數學 math 語文 chinese 成績儲存在乙個二進位制檔案st...

std ofstream由二進位製流寫檔案的問題

從mpq包中讀取二進位製流出來然後檔案寫到硬碟。dword size sfilegetsize hfile char buffer new char size std ofstream ofs ofs.open name assert ofs.good ofs.write buffer,size a...

檔案流 ASCII 與 二進位制

乙個字元就使乙個位元組,所以即使是二進位制檔案你仍然能看的懂,不要以為寫進去的就是文字了。include include include include using namespace std struct student int main 注意 這種方式能把檔案放入指定的地方 ofstream o...