目录
一.文件的读写
#include<fstream> //包含 ofstream/ifstream/fstream类
#include<iostream>
#include<string>
using namespace std;
int main()
{
string user_name;
int num_tries;
int num_right;
//使用ofstream和ifstream分别负责打开、写入文件和读取文件
ofstream outfile("GodFishhh.txt", ios_base::app); //第二个参数ios_base::app使得可以以追加模式打开这个文件(如果文件已经存在,将会丢弃原有内容),追加模式下不会丢弃原有内容。
if (!outfile) //如果文件没有打开成功,则ofstream对象的求值结果为false
{
cout << "文件无法打开" << endl;
}
else
{
cout << "文件打开成功,向文件中写入数据" << endl;
cout << "分别输入用户姓名,尝试的次数和猜对的次数" << endl;
cin >> user_name >> num_tries >> num_right;
//将数据写入文件
outfile << user_name << " "
<< num_tries << " "
<< num_right << endl;
}
ifstream infile("GodFishhh.txt");
if (!infile)
{
cout << "文件无法打开" << endl;
}
else
{
string name;
int nt;
int nr;
// infile>>name 即从infile读取数据并储存在infile中,同时通过一个while语句依次读取直到文件中不再有此类数据类型的数据
while (infile >> name)
{
infile >> nt >> nr; //从文件中读取数据并依次储存在nt和nr中
if (name == user_name)
{
cout << "找到了" << user_name << endl;
cout << "你的成绩为: " << nr << " out of " << nt << endl;
}
}
}
//利用fstream同时完成文件的打开、写入数据、读取数据
fstream iofile("GodFishhh.txt", ios_base::app);
if (!iofile)
{
cout << "无法打开文件" << endl;
}
else
{
iofile.seekg(0); // 开始读取之前,将文件重新定位到起始处
}
system("pause");
return 0;
}
知识点:
1.可以利用ofstream和ifstream分别创建对象负责文件的打开、写入和文件的读取,也可以直接利用fstream创建对象同时负责这些功能。(ofstream负责的是从内存到硬盘--输出到文件,ifstream负责的是从硬盘到内存--从文件输出)(ofstream和ifstream是fstream的两个子类,ofstream默认以输出方式打开文件--ios::out,ifstream默认以输入方式打开文件--ios::in)
ofstream outfile("GodFishhh.txt",ios_base::app)
ifstream infile("GodFishhh.txt")
fstream iofile("GodFishhh",ios_base::app)
2.以追加模式打开文件,需要加上第二个参数ios_base::app。(如果不以追加模式打开文件,则若打开的文件存在,其中的原有内容就会丢失)
3.ofstream对象outfile负责向文件中写入数据:outfile<<name 即为向文件中写入数据name;ifstream对象infile对象负责从文件中读取数据:infile>>name 即为从文件中读取数据并赋值给name这个变量。
4.利用类函数seekg(0)使得在开始读写之前,将文件重新定位至起始处。
fstream iofile("GodFishhh",ios_base::app);
//将文件重新定位至起始处
iofile.seekg(0)
5.成员函数 void open(const char*filename ,int mode,int access)
参数:
filename: 要打开的文件名
mode: 要打开文件的方式
access: 打开文件的属性
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:
ios::app: 以追加的方式打开文件
ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性
ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
ios::in: 文件以输入方式打开(文件数据输入到内存)
ios::out: 文件以输出方式打开(内存数据输出到文件)
ios::nocreate: 不建立文件,所以文件不存在时打开失败
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc: 如果文件存在,把文件长度设为0
可以用“或”把以上属性连接起来,如ios::out|ios::binary
打开文件的属性取值是:
0:普通文件,打开访问
1:只读文件
2:隐含文件
4:系统文件
fstream iofile;
iofile.open("GodFishhh.txt",ios::in|ios::app,0);
参考文章:(53条消息) C++ - ofstream和ifstream函数详细用法_AIHGF的博客-优快云博客_ifstream用法
二.函数指针
知识点:
1.函数指针的定义:通过小括号改变优先级(*fucname)。
const vector<int>* (*seq_prt)(int);
2. 存放函数指针的数组
const vector<int>* (*seq_array[]) (int);
3.利用enum常量来给存在函数指针的数组赋值(便于识别),同时enum中的枚举量在默认情形下第一个值为0,接下来的每个枚举量都比前一个的值多1。
enum ns_type
{
ns_fibon, ns_lucas, ns_pell
ns_triang, ns_square, ns_pent
};
//ns_fibon的值为0,ns_lucas的值为1,ns_pell,ns_triang,ns_square,ns_pent依次递增
seq_ptr = seq_array[ns_fibon];
//相当于seq_prt = seq_array[0];