0. 头文件与命名空间
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
1. 写入文件(覆盖模式与追加模式)
// ofstream 写入文件, out 覆盖掉原文件内容
ofstream fout("test.txt", ios::out);
// app 末尾追加模式
ofstream fout("test.txt", ios::app);
fout << "this is an insert sentence1" << endl;
fout << "this is an insert sentence2" << endl;
fout << "this is an insert sentence3" << endl;
fout.close();
2. 读文件
char* ch1 = new char[100];
string ch2;
2.1 char*逐行读取
//打开文件
ifstream fin1("test.txt", ios::in);
while (fin1.getline(ch1, 100)) {
cout << ch1 << endl;
}
fin1.close();
delete []ch1;
2.2 只想读取前n行