C Plus Plus 實現文件讀寫
Scarborough_Coral
前面介紹了C語言的文件讀寫,下面我們將介紹C++的文件操作。
在C++的文件操作中,需要文件流對象,有了對象才能對文件進行操作。
- 文件寫操作
#include <iostream>
#include <fstream>//包含文件操作頭文件
using namespace std;
int main()
{
ofstream out("test.txt");//實例化文件輸出流對象並打開文件
if (out.is_open())
{
out << "這是第一行。\n";
out << "這是第二行。\n";//輸出兩句話到文件
out.close();
}
else
{
cout << "Open error!" << endl;//若打開失敗提示錯誤
}
return 0;
}
- 結果查看
- 文件讀操作
#include <iostream>
#include <fstream>//包含文件操作頭文件
using namespace std;
int main()
{
char buffer[256];//緩存,用於短暫存儲從文件讀入的內容
ifstream in("test.txt");//實例化文件輸出流對象並打開文件
if (in.is_open())
{
while (!in.eof())//判斷是否讀到文件結尾
{
in.getline(buffer, 100);//將文本讀入到buffer中
cout << buffer << endl;//輸出buffer
}
in.close();
}
else
{
cout << "Open error!" << endl;//若打開失敗提示錯誤
}
return 0;
}
- 結果顯示