头文件
#include <fstream>
读写文件三个类,对应不同的操作方式或者组合:
ofstream //文件写操作 内存写入存储设备
ifstream //文件读操作,存储设备读区到内存中
fstream //读写操作,对打开的文件可进行读写操作
操作对象初始化
void open(const wchar_t *_Filename,
ios_base::openmode mode,
int prot);
参数:
filename 操作文件名
mode 打开文件的方式
ios::in | 为输入(读)而打开文件 |
ios::out | 为输出(写)而打开文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 所有输出附加在文件末尾 |
ios::trunc | 如果文件已存在则先删除该文件 |
ios::binary | 二进制方式 |
prot 打开文件的属性
0 | 普通文件,打开操作 |
1 | 只读文件 |
2 | 隐含文件 |
4 | 系统文件 |
举例:
#include <fstream>
void main(){
ofstream fout("d:\\fstream_test.txt");
//或者
ofstream out;
out.open("d:\\fstream_test.txt", ios::in|ios::out|ios::binary)
//判断是否成功创建对象
if (!fout) {
cout << "文件不能打开" << endl;
}
}
以文本方式读写文件
- 使用重载的插入操作符 << 或者 >>
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream fout("d:\\fstream_test.txt");
if (!fout) {
cout << "文件不能打开" << endl;
}
else {
fout << "Learning C++ is very useful." << endl;
fout << "This is another line." << endl;
}
fout.close();
ifstream fin("d:\\fstream_test.txt");
if (!fin) {
cout << "文件不能打开" << endl;
}
else {
char buffer[80];
while (!fin.eof()) {
fin >> buffer;//每次读取一个单词,即遇到空格或者换行符
cout << buffer << endl;
}
fin.close();
}
return 0;
}
fstream_test.txt
Learning C++ is very useful.
This is another line.
cmd output
Learning
C++
is
very
useful.
This
is
another
line.
- 使用函数getline()
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin("d:\\fstream_test.txt");
if (!fin) {
cout << "文件不能打开" << endl;
}
else {
char buffer[80];
while (!fin.eof()) {
fin.getline(buffer, 80);
cout << buffer << endl;
}
fin.close();
}
return 0;
}
cmd output
Learning C++ is very useful.
This is another line.
以二进制方式读写文件
文件流包括两个为顺序读写数据特殊设计的成员函数:write 和 read。第一个函数 (write) 是ostream 的一个成员函数,都是被ofstream所继承。而read 是istream 的一个成员函数,被ifstream 所继承。类 fstream 的对象同时拥有这两个函数。它们的原型是:
write ( char * buffer, streamsize size );
read ( char * buffer, streamsize size );
这里 buffer 是一块内存的地址,用来存储或读出数据。参数size 是一个整数值,表示要从缓存(buffer)中读出或写入的字符数。
#include <iostream>
#include <fstream>
using namespace std;
void main() {
float array[5][5];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
array[i][j] = i + j;
}
}
ofstream fout("d:\\fstream_binary_test.txt");
if (!fout) { cout << "文件不能打开" << endl;}
else {
fout.write((char*)array, 5 * 5 * sizeof(float));
}
fout.close();
ifstream fin("d:\\fstream_binary_test.txt");
if (!fin) { cout << "文件不能打开" << endl;}
else {
char buffer[200];
fin.read(buffer, 5 * 5 * sizeof(float));
float* data = (float*)buffer;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
int posi = i * 5 + j;
cout << data[posi] << ' ';
}
cout << endl;
}
}
fin.close();
}
fstream_binary_test.txt
€? @ @@ €@ €? @ @@ €@ 燖 @ @@ €@ 燖 繞 @@ €@ 燖 繞 郂 €@ 燖 繞 郂 A
cmd output
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8