在C++中讀讀寫文件一般指的就是磁盤中的文本文件和二進制文件:
文本文件:以字符序列組成的文件
二進制文件:由二進制組成的文件
讀寫文件采用ofstream和ifstream文件流,兩者可用頭文件<fstream>包含,具體代碼如下:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
ofstream out;//輸出文件
out.open("D:\\PPC\\test.txt");
if (out.is_open())
{
out << "This is a line.\n";
out << "This is another line.\n";
out.close();
}
char buffer[256];
ifstream in("D:\\PPC\\test.txt");//讀文件
if (!in.is_open())
{
cout << "error!";
getchar();//讓dos停留觀測結果用,可刪除
exit(1);
}
while (!in.eof())
{
in.getline(buffer, 100);
cout << buffer << endl;
}
getchar();
return 0;
}
