#include <fstream> //头文件
//以输出模式打开 hello.txt
ofstream outfile("hello.txt");
//以追加模式 ( append mode ) 开启hello.txt
//要提供第二个参数 ios_base::app 传给ostream对象
//新数据会被加到文件尾端
ofstream outfile("hello.txt", ios_base::app);
//如果 outfile 的计算结果为 false, 表示此文件未开启成功
if (!outfile){
//因为某种原因,文件无法开启
cerr << "Oops! Unable to save session data!\n";
}
else{
//ok: outfile 开启成功,接下来将数据写入
outfile << name << " " << id << " " << sex << " " << addr << endl;
}
//以读取模式 ( input mode ) 开启 infile
ifstream infile("hello.txt");
if (!infile) {
//由于某种原因,文件无法开启……
}
else {
while (infile >> name) {
infile >> id >> sex >> addr;
if (name == find_name) {
//找到他了
cout << name << " " << id << " " << sex << " " << addr << endl;
}
}
}
//如果想要同时读写同一个文件,得定义一个fstream对象
//为了以追加模式(append mode)开启,我们得传入第二参数值ios_base::in | ios_base::app
fstream iofile("hello.txt", ios_base::in | ios_base::app);
if (!iofile)
//由于某种原因,文件无法开启
else{
//开始读取之前,将文件重新定位至起始处
//以附加模式开启文件时,文件位置会位于尾端,没有重新定位则会遇到eof
iofile.seekg(0);
}
通过 fstream 的 close 函数来关闭文件, inflie.close() outfile.close() iofile.close()
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Person{
string name;
long long id;
char sex;
string addr;
};
int main()
{
Person per;
char ch = 'y';
//outfile
ofstream outfile("fuck.txt");
while (ch != 'n'){
cout << "输入姓名 学号 性别 地址: ";
cin >> per.name >> per.id >> per.sex >> per.addr;
outfile << per.name << " " << per.id << " " << per.sex << " " << per.addr << endl;
cout << "继续输入?(y or n): ";
cin >> ch;
}
outfile.close();
//infile
ifstream infile("fuck.txt");
while (!infile.eof()){
infile >> per.name >> per.id >> per.sex >> per.addr;
cout << per.name << " " << per.id << " " << per.sex << " " << per.addr << endl;
}
infile.close();
system("pause");
return 0;
}