C 之文字檔案的讀取和寫入

2021-10-23 04:33:01 字數 1381 閱讀 9580

部落格2:c++建立txt檔案並讀寫

部落格3:c++檔案流在ios類中定義

部落格4:c++檔案操作詳解(ifstream、ofstream、fstream)

使用檔案流物件開啟檔案後,檔案就成為乙個輸入流或輸出流。對於文字檔案,可以使用 cin、cout 讀寫。

在《c++檔案類(檔案流類)》一節中提到,流的成員函式和流操縱運算元同樣適用於檔案流,因為 ifstream 是 istream 的派生類,ofstream 是 ostream 的派生類,fstream 是 iostream 的派生類,而 iostream 又是從 istream 和 ostream 共同派生而來的。

例題:編寫乙個程式,將檔案 in.txt 中的整數排序後輸出到 out.txt。例如,若 in.txt 的內容為:

1 234 9 45

6 879

則執行本程式後,生成的 out.txt 的內容為:

1 6 9 45 234 879

假設 in.txt 中的整數不超過 1000 個。

#include

#include

#include

//qsort在此標頭檔案中宣告

using

namespace std;

const

int max_num =

1000

;int a[max_num]

;//存放檔案中讀入的整數

intmycompare

(const

void

* e1,

const

void

* e2)

intmain()

ofstream destfile

("out.txt"

,ios::out)

;//以文字模式開啟out.txt備寫if(

!destfile)

int x;

while

(srcfile >> x)

//可以像用cin那樣用ifstream物件

a[total++

]= x;

qsort

(a,total,

sizeof

(int

),mycompare)

;//排序

for(

int i =

0;i < total;

++i)

destfile << a[i]

<<

" ";

//可以像用cout那樣用ofstream物件

destfile.

close()

; srcfile.

close()

;return0;

}

c 讀取 寫入 文字檔案

include include 讀寫檔案的標頭檔案 include using namespace std 1 文字檔案 寫檔案 1 包含標頭檔案 include 2 建立流物件 ofstream ofs 3 指定路徑和開啟方式 ofs.open 路徑,開啟方式 開啟方式 ios in 讀檔案開啟 ...

讀取和寫入文字檔案

read a text file 的這篇文章部分描述如何使用streamreader類來讀取文字的檔案。write a text file example 1 和 write a text file example 2 在各節說明了如何使用streamwriter類來向檔案寫入文字。讀取文字檔案 若...

C 文字檔案的讀取和寫入

使用檔案流物件開啟檔案後,檔案就成為乙個輸入流或輸出流。對於文字檔案,可以使用 cin cout 讀寫。流的成員函式和流操縱運算元同樣適用於檔案流,因為 ifstream 是 istream 的派生類,ofstream 是 ostream 的派生類,fstream 是 iostream 的派生類,而...