C++ 文件流操作
概要
在C++中,文件被看作是字符的序列,即文件是由一个个的字符数据顺序组成的。正因为C++文件是一个字符流,而不考虑记录的界限,因此这种文件称为流式文件。
按数据的存储形式分类
- 文本文件 :每个字节存放一个ASCII代码表示一个字符。(好处:可直接按字符形式输出)
- 二进制文件:把数据的内部存储形式原样存放到文件中。(好处:无需存储形式转换,存储效率高)
按数据的存取方式分类 - 顺序文件
- 随机读写文件
在C++ 中文件被定义为文件流类的一个对象。
1、文件流
C++ 中有三种文件流,
- 输入文件流 :对应
ifstream
类 - 输出文件流:对应
ofstream
类 - 输入输出文件流: 对应
fstream
类
这三种类都在头文件fstream
中定义。
2、文件的打开与关闭
文件的打开方式
标识常量 | 值 | 含义 |
---|---|---|
ios::in | 0x0001 | 以输入方式打开文件 |
ios::out | 0x0002 | 以输出方式打开文件 |
ios::ate | 0x0004 | 打开一个已有文件,将文件指针定位于文件尾部 |
ios::app | 0x0008 | 追加方式打开文件 |
ios::trunc | 0x0010 | 如果文件存在,清除原有内容,否则创建新文件 |
ios::nocreate | 0x0020 | 不建立新文件,如果文件不存在则打开失败 |
ios::noreplace | 0x0040 | 通常用来建立新文件,如果文件存在,需与app或ate同时用,否则打开失败 |
ios::binary | 0x0080 | 以二进制方式打开。默认方式 |
文件的关闭使用close()成员函数。
举个例子:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file1;
file1.open("test.txt",ios::out|ios::in|ios::app);
if(!file1)
{
cout<<"open failed"<<endl;
}
//...
file1.close();
return 0;
}
3、文件的读写
(1)、文本文件读写
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file1;
char ch;
file1.open("test.txt",ios::out|ios::in|ios::app);
if(!file1)
{
cout<<"open failed"<<endl;
}
while(cin>>ch)
{
file1<<ch<<endl; //一个字符一行
cout<<"write:"<<ch<<endl;
}
cout<<"over"<<endl;
file1.close();
return 0;
}
/****************read********************/
char str[10];
while(!file1.eof())
{
file1.getline(str,sizeof(str));
cout<<"input:"<<str[0]<<endl;
}
cout<<"over"<<endl;
file1.close();
(2)、二进制文件读写
写入:
举个例子:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream file1;
int num_array[3][3]={{1,2,3},{4,5,6},{7,8,9}};
file1.open("num.dat",ios::trunc|ios::binary);
if(!file1)
{
cout<<"open failed"<<endl;
}
for(int i = 0;i<3;i++)
{
file1.write((char*)&num_array[i],3*sizeof(int));
}
file1.close();
return 0;
}
先看下输出结果,这是个二进制文件,得用一些工具查看,如下图,01,02,03,…都已经写了进去。显然一个int 型数据占4个字节。
在file1.write((char*)&num_array[i],3*sizeof(int));
这句中,首先num_array
是一个二维数组名,num_array[i]
就是二维数组的第一行,然后对其取地址,并强制指针转换,然后把连续的3个数据写入。为社么是(char*),这是因为函数原型是这样的。
__ostream_type&
write(const char_type* __s, streamsize __n);
读取:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file2;
int num_array1[3][3]={0};
file2.open("num.dat",ios::binary);
if(!file2)
{
cout<<"open failed"<<endl;
}
for(int i = 0;i<3;i++)
{
file2.read((char*)&num_array1[i],3*sizeof(int));
}
for(int i = 0;i<3;i++)
{
for(int j = 0;j<3;j++)
{
cout<<num_array1[i][j]<<endl;
}
}
file2.close();
return 0;
}