在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; }