C 程式例 文字檔案的讀寫 二進位制檔案讀寫

2021-10-08 12:16:17 字數 1377 閱讀 9975

文字檔案的讀寫

#include

#include

#include

using

namespace std;

void

test_a()

//建立乙個.txt檔案並寫入內容

void

test_b()

//讀取檔案中的內容

//4、讀內容,4種方式如下。推薦第三種,其他的作了注釋處理

第一種,初始化乙個字元陣列,注意初始化的時候有大括號

//char buf[1024] = ;

//while (ifs >> buf)

//第二種,與前一種類似

//char buf[1024] = ;

//while (ifs.getline(buf, sizeof(buf)))

////第三種,利用全域性函式getline(),注意在vs2019仍需要標頭檔案 #include

string buf;

while

(getline

(ifs, buf)

)第四種,乙個個讀,不推薦

//char c;

//while ((c = ifs.get()) != eof)//eof:end of file

////5、關閉

ifs.

close()

;}intmain()

二進位制檔案的讀寫

#include

#include

using

namespace std;

class

person

;void

test_c()

//寫入自定義資料person類物件

; ofs.

write((

const

char*)

&p,sizeof

(person));

//強轉指標為char型

ofs.

close()

;}void

test_d()

//讀出二進位制檔案

person p;

//用相應的資料型別去接收即將讀到的資料

ifs.

read((

char*)

&p,sizeof

(person));

cout <<

"從檔案中讀得:姓名:"

<< p.m_name

<<

" 年齡:"

<< p.m_age << endl;

ifs.

close()

;}intmain()

C C 讀寫文字檔案 二進位制檔案

掌握c語言文字檔案讀寫方式 掌握c語言二進位制檔案讀寫方式 掌握cpp文字檔案讀寫方式 掌握cpp二進位制檔案讀寫方式 1.文字檔案寫入 採用c模式對txt進行寫出 void txtwrite cmode 寫出txt file fid fopen txt out.txt w if fid null ...

C C 讀寫文字檔案 二進位制檔案

掌握c語言文字檔案讀寫方式 掌握c語言二進位制檔案讀寫方式 掌握cpp文字檔案讀寫方式 掌握cpp二進位制檔案讀寫方式 1.文字檔案寫入 採用c模式對txt進行寫出 void txtwrite cmode 寫出txt file fid fopen txt out.txt w if fid null ...

讀寫文字檔案和二進位制檔案 二進位制模式

fstream binary開啟 新行採用 lf 作為乙個位元組 關閉 新行採用 cr lf 組合,作為乙個位元組。關於 cr lf 參見 以下是 c primer 第四版中的一段 1 intmain 29 10 ifstream pos type ptendmark finout.tellg 11...