废话没有,直接上正文
目录
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 分割线 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C++标准库
iostream 是我们常用的标准库,使用 cin 和 cout 作为标准输入流和标准输出流
那文件输入输出怎么实现呢?
fstream 他来了!
作为一个可以实现文件操作的标准库,fstream 提供了3个流:
ofstream 是输出文件流,用于创建文件并向文件写入信息。
ifstream 是输入文件流,用于从文件读取信息。
fstream 是输入输出文件流,即具有 ofstream 和 ifstream 两种功能,用于创建文件,向文件写入信息,从文件读取信息。
使用 fstream 首先要包含头文件:
#include <iostream>
#include <fstream>
定义流的方法:
ofstream outfile;
ifstream infile;
fstream iofile;
打开文件
打开文件使用 open 函数,open 函数原型:
void open(const char *filename, ios::openmode mode);
// filename : 打开的文件名及其位置
// mode : 文件打开的模式(见下表)
打开模式 | 描述 |
---|---|
ios::app | 所有写入追加到文件末尾。 |
ios::ate | 文件打开后定位到文件末尾。 |
ios::in | 打开文件用于读取。 |
ios::out | 打开文件用于写入。 |
ios::trunc | 如果该文件已经存在,则删除文件内容 |
mode 参数可以有多个模式结合,使用 '|' 将多个模式结合起来,如:
// 样例1
ofstream outfile;
outfile.open("file1.dat", ios::trunc | ios::out);
// 样例2
fstream iofile;
iofile.open("file2.dat", ios::out | ios::in | ios::trunc);
关闭文件
关闭文件使用 close 函数,close 函数原型:
void close();
如:
outfile.close();
读写文件
读写文件使用 >> 和 << 运算符,只要把 iostream 中的 cin 和 cout 换成 ifstream 和 ofstream 对象就可以了(即上面代码中的 outfile,infile 和 iofile),如:
// 读取
char d[20];
infile >> d;
// 写入
outfile << "Hello World!" << endl;
定位文件位置(选读)
如何重新定位文件指针(即读写文件的位置)的位置呢?
可以使用 ifstream 中的 seekg 函数和 ofstream 中的 seekp 函数
第一个参数为长整型数据(long),第二个参数用于确定查找方向(见下表):
ios::beg | 从开头开始定位(默认) |
ios::cur | 从当前位置开始定位 |
ios::end | 从末尾开始定位 |
文件位置指针是一个整数值,指定从文件的起始位置到指针所在位置的字节数。
如:
// 定位到 infile 第 n 个字节 (即 ios::beg)
infile.seekg(n);
// 把读指针从 infile 当前位置向后移 n 个字节
infile.seekg(n, ios::cur);
// 把读指针从 infile 末尾往回移 n 个字节
infile.seekg(n, ios::end);
// 定位到 infile 末尾
infile.seekg(0, ios::end);
文件读写实例
这里给出一个文件读写实例:(看不懂的可以看注释)
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// 以只写模式打开文件
ofstream outfile;
outfile.open("info.dat");
// 从终端读入一行
cout << "What's your name? ";
cin.getline(data, 100);
// 向文件写入用户的姓名
outfile << data << endl;
cout << "How old are you? ";
cin >> data;
// 向文件写入用户的年龄
outfile << data << endl;
// 关闭打开的文件
outfile.close();
// 以只读模式打开文件
ifstream infile;
infile.open("info.dat");
// 读取文件内容(一行)
infile >> data;
// 在终端上写入数据
cout << "The data: " << data << endl;
// 再读取文件内容(一行)
infile >> data;
// 在终端上写入数据
cout << data << endl;
// 关闭打开的文件
infile.close();
// 暂停程序看运行结果
system("pause");
return 0;
}
输入输出:
文件内容:
Chocolate~
100
可以看到程序成功编译和运行
更多
C++文件操作还有其他方法,更多方法有待更新:
freopen 和 fopen:更新中
希望以上内容对各位有些帮助 (~ ̄▽ ̄)~