C++讀檔案
阿新 • • 發佈:2021-02-05
讀檔案與寫檔案步驟相似,但是讀取方式相對於比較多
讀檔案步驟如下:
1.包含標頭檔案
#include
2.建立流物件
ifstream ofs;
3.開啟檔案
ifs.open(“檔案路徑”,開啟方式);
4.寫資料
四種方式讀取
5.關閉檔案
ifs.close();
程式碼示例:
#include <iostream>
#include <fstream> //標頭檔案包含
#include <string>
using namespace std;
//文字檔案 寫檔案
void test01()
{
//1.包含標頭檔案 fstream
// 2.建立流物件
ifstream ifs;
//3.指定開啟方式
ifs.open("test.txt", ios::in);
if (!ifs.is_open())
{
cout << "檔案開啟失敗" << endl;
return;
}
//4.讀內容
//第一種
//char buf[1024] = { 0 };
//while (ifs>>buf)
//{
// cout << buf << endl;
//}
//第二種
//char buf[1024] = { 0 };
//while (ifs.getline(buf,sizeof(buf)))
//{
// cout << buf << endl;
//}
//第三種
//string buf;
//while (getline(ifs,buf))
//{
// cout << buf << endl;
//}
//第四種(不推薦使用,因為要一個一個遍歷字元)
char c;
while ((c=ifs.get())!=EOF) //EOF end of file
{
cout << c;
}
//5.關閉檔案
ifs.close();
}
int main()
{
test01();
return 0;
}
總結:
1.讀檔案可以利用ifstream,或者fstream類
2.利用is_open函式可以判斷檔案是否開啟成功
3.close關閉檔案