C 流和檔案操作

2021-10-05 09:22:32 字數 1899 閱讀 1224

c++中輸入輸出操作使用流來完成,將輸出輸入的操作稱為流類,實現流類的庫為流類庫
流類庫標頭檔案
#include
c++常用流類派生關係:

標頭檔案

#include
檔案開啟方式

開啟方式

說明ios::in

讀檔案方式開啟檔案,檔案不存在開啟失敗

ios::out

寫檔案方式開啟檔案,檔案不存在久建立了再開啟

ios::ate

開啟檔案後,指標指向檔案尾

以追加方式開啟寫檔案

ios::trunc

檔案存在先刪除再建立

ios::binary

二進位制方式

寫檔案

void write_file(void)

int main(void)

函式名

引數1引數2

open檔案路徑,如d:\test\person.txt,不寫路徑預設當前目錄

檔案開啟方式

讀檔案四種方式:

//方式1,使用運演算法》讀出資料到buf

void read_file1(void)

char buf[1024];

while(ifs >> buf) //4、使用運算子》讀出資料到buf

ifs.close();

}void read_file2(void)

char buf[1024];

while(ifs.getline(buf, sizeof(buf))) //4、使用流物件中的讀出函式從檔案中讀出資料放到buf中

ifs.close(); //5、關閉檔案

}void read_file3(void)

string buf;

while(getline(ifs, buf)) //4、從檔案中讀出資料放到buf中

ifs.close(); //5、關閉檔案

}void read_file4(void)

char c;

while((c = ifs.get()) != eof) //4、使用流物件ifs.get()函式從檔案one by one byte方式放到c中

ifs.close(); //5、關閉檔案

}int main(void)

二進位制方式讀寫檔案
#include #include #include using namespace std;

class person

};//二進位制方式讀寫檔案

void binary_write_read(void)

ifs.read((char *)&person1, sizeof(person1)); //2、讀出檔案資料

cout << "person name : " << person1.name << endl;

cout << "person age : " << person1.age << endl;

ifs.close(); //3、關閉檔案

}int main(void)

檔案和檔案流

12.1 c 檔案流的基本概念 12.1.1檔案及及分類 1.程式檔案 包括源程式檔案 字尾名.cpp 目標檔案 字尾為.obj 可執行檔案 字尾名.exe 這類檔案包含的是文字和二進位制程式 2.資料檔案 檔案的內容不是程式,而是供程式讀寫的資料。12.1.2 c 檔案流基礎 1.ifstream...

C 學習摘要之九 C 流和檔案流

在程式設計 中,資料輸入 輸出 i o 操作是必不可少的,c 語言的資料輸入 輸出操作是通過i o流庫來實現的。c 中把資料之間的傳輸操作稱為流,流既可 以表示資料從記憶體傳送到某個載體或裝置中,即輸出流,也可以表示資料從某個載體或裝置傳送到記憶體緩衝區變數中,即輸入流。在進行i o操作時,首先是開...

C 操作目錄和檔案

1 通過path類的combine方法可以合併路徑。string activedir c mydir string newpath system.io.path.combine activedir,mysubdirone 2 目錄的建立。建立目錄時如果目錄已存在,則不會重新建立目錄,且不會報錯。建立...