file access

檔案存取

FILE物件

宣告一個字元:char ch;

宣告一個FILE物件:FILE *fp; //檔案指標

開啟檔案:fp=fopen(檔案名稱,"r");

檔案結束:fgetc(fp) == EOF

讀取字元:ch=fgetc(fp);

輸出字元:fputc(ch,stdout); //從螢幕輸出

fstream物件

標頭檔:include <fstream>

命名空間:using namespace std;

宣告一個字元:char ch;

宣告一個ifstream物件:ifstream fin; //輸入檔案物件

檔案結束:fin.eof()

讀取字元:fin.get(ch);

輸出字元:printf("%c",ch);

寫入

fstream物件檔案操作物件

標頭檔:#include<fstream.h>

命名空間:using namespace std;

fstream:可讀、可寫。

ifstream:可讀、不可寫。

ofstream:可寫、不可讀。

唯讀

ifstream fin;

fin.open("檔案名稱");

開檔失敗:!fin

檔案結束:fin.eof()

讀取字元:fin.get(ch);

寫入

ofstream fout;

fout.open("檔案名稱");

檔案不存在:!fout

檔案結束:fout.eof()

寫入字元:fout.put(ch);

寫入字串:fout << "字串";


參考網址:https://www.itread01.com/content/1543733046.html

http://www2.lssh.tp.edu.tw/~hlf/class-1/lang-c/c++file.htm