02 C++ 文件操作
头文件<fstream>
提供三个文件流类
| 类名 | 作用 |
|---|---|
ifstream |
只读文件流(输入) |
ofstream |
只写文件流(输出) |
fstream |
读写文件流(输入输出) |
成员函数
| 成员函数 | 作用 |
|---|---|
close() |
关闭文件 |
write() |
写入二进制数据 |
read() |
读取二进制数据 |
seekg() |
设置读取位置 |
seekp() |
设置写入位置 |
tellg() |
获取当前读取位置 |
tellp() |
获取当前写入位置 |
eof() |
检测是否到达文件结尾 |
fail() |
检测是否发生失败 |
bad() |
检测是否发生严重错误 |
clear() |
清除错误标志 |
文件模式
| 标志 | 作用 |
|---|---|
std::ios::in |
读取模式打开 |
std::ios::out |
写入模式打开 |
std::ios::app |
追加模式,不覆盖原有内容 |
std::ios::trunc |
清空模式,覆盖原有内容 |
std::ios::binary |
二进制模式 |
std::ios::ate |
如果已存在则转到文件尾部 |
文件操作
打开文件
/*
// C 风格
FILE* fp;
fp = fopen("a.txt","wb");
*/
ifstream f;
f.open( "d:\\customer.dat ");
char name[20];
cin>>name;
f.open(fileName);
//先定义流对象 再打开文件
ifstream inFile;
inFile.open("a.txt",ios::out | ios::in | ios::binary);
//定义流对象时打开文件
fstream file("example.txt",std::ios::in | std::ios::out | std::ios::app);
//检测是否打开成功
if(!file) cout<<"failed"<<endl;
if(file.fail())
{
cout<<"failed"<<endl;
exit(0);
}
关闭文件
dataFile.close();
读写文件
写文件
使用 << 写入信息
#include <iostream>
using namespace std;
#include <fstream>
#include <cstdlib>
int main( )
{
fstream dataFile ;
dataFile.open("demofile.txt", ios::out );
if ( ! dataFile )
{
cout << "Error opening file.\n";
exit(0);
}
dataFile << "Confucius\n" ;
dataFile << "Mo-tse\n" ;
dataFile.close( );
dataFile.open("demofile.txt", ios::out | ios::app);
dataFile << "Einstein\n" ;
dataFile << "Shakespeare\n" ;
dataFile.close( );
return 0;
}
读文件
使用 >> 读出数据
>> 会忽略换行和空格,读入换行和空格可用 inFile.get(ch) 代替,读入整行可用 getline(inFile,line) 代替(不会读入换行符)
#include <iostream>
using namespace std;
#include <fstream>
#include <cstdlib>
void main()
{
fstream dataFile;
char name [81];
dataFile.open("demofile.txt", ios::in);
if ( !dataFile)
{
cout << "File open error!" << endl;
exit(0);
}
for(int count = 0; count < 4; count++)
{
dataFile >> name;
cout << name << endl;
}
dataFile.close( );
}
流对象做参数
必须通过引用的方式传递,保证实参和形参是同一个流对象
#include <iostream>
using namespace std;
#include <fstream>
#include <cstdlib> // C++ 中 stdlib.h 的写法
#include <cstring>
bool openFileIn(fstream &, char[ ]);
void showContents(fstream &);
void main( )
{
fstream dataFile;
if (!openFileIn(dataFile,"demofile.txt"))
{
cout << "File open error!" << endl;
exit(0);
}
showContents(dataFile);
dataFile.close( );
}
bool openFileIn(fstream &file, char name[ ]) // 必须有引用
{
file.open(name, ios::in);
return file.fail( ) ? false : true;
}
void showContents(fstream &file)
{
char name [81];
while( !file.eof( ))
{
file >> name;
if(file.fail( )) break;
cout << name << " ";
}
}
函数成员读写文件
getline 成员函数:C风格dataFile.getline(str,81,'\n');
C++风格getline(dataFile,str);
get 成员函数:inFile.get(ch);
put 成员函数:outFile.put(ch);
检测文件结束
while(!inFile.eof())
inFile>>var;
if (inFile.eof())
inFile.close();
while(!dataFile.eof())
{
dataFile >> name ;
if(dataFile.fail())
break;
cout << name << "\n";
}
dataFile.close();
出错检测
| 流对象的标志位 | 当前状态 |
|---|---|
ios::eofbit |
遇到输入流尾部 |
ios::failbit |
操作失败 |
ios::hardfail |
出现不可恢复错误 |
ios::badbit |
出现无效操作 |
ios::goodbit |
以上所有标记都未设置 |
| 函数成员 | 检测(设置返回 true ,未设置返回 false) |
|---|---|
eof() |
返回 eofbit 状态 |
fail() |
返回 failbit |
bad() |
返回 badbit 状态 |
good() |
返回 goodbit 状态 |
clear() |
清除所有状态位 |
多文件操作
#include <iostream>
using namespace std;
#include <fstream>
#include <cstdlib>
#include <cctype>
int main( )
{
ifstream inFile;
ofstream outFile("out.txt");
char fileName[81], ch, ch2;
cout << "请输入文件名: ";
cin >> fileName;
inFile.open(fileName);
if (!inFile)
{
cout << "打开失败" << fileName << endl;
exit(0);
}
while(!inFile.eof())
{
inFile.get(ch);
if (inFile.fail())
break;
ch2 = toupper(ch);
outFile.put(ch2);
}
inFile.close();
outFile.close();
}
二进制文件
//打开文件
file.open("stuff.dat",ios::out|ios::binary);
//读写函数
file.write((char*)buffer,sizeof(buffer));
file.read((char*)buffer,sizeof(buffer));
// 二进制 转 ASCLL
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
fstream f;
int x[10]={1,2,3,4,5,6,7,8,9,0};
int y[10];
f.open("a.txt",ios::out | ios::binary);
f.write((char*)x,sizeof x);
f.close();
f.open("a.txt",ios::in | ios::binary);
f.read((char*)y,sizeof y);
f.close();
f.open("b.txt", ios::out);
for(int i=0;i<10;i++) f << y[i];
f.close();
return 0;
}
结构体记录文件
必须以二进制方式打开
#include <iostream>
using namespace std;
#include <fstream>
#include <cstdlib>
#include <cctype>
struct Info
{
char name[21] ;
int age ;
char address[51] ;
char phone[14] ;
char email[51] ;
};
int main( )
{
fstream people("people.dat", ios::out | ios::binary);
Info person ;
char again ;
if(people.fail( ))
{
cout << "打开文件people.dat出错! \n" ;
exit( 0 );
}
do {
cout << "请输入下面的数据: \n" ;
cout << "姓名:" ; cin.getline(person.name, 21);
cout << "年龄:" ; cin >> person.age ; cin.ignore( );
cout << "联系地址:" ; cin.getline(person.address, 51);
cout << "联系电话:" ; cin.getline(person.phone, 14);
cout << "邮箱地址" ; cin.getline(person.email, 51);
people .write(( char *)&person, sizeof(person));
cout << "还要再输入一个同学的数据吗 ? " ;
cin >> again ; cin.ignore( );
} while( toupper( again ) == 'Y' );
people.close( );
cout << "\n\n*** 下面显示所有人的数据 ***\n" ;
people.open("people.dat", ios::in | ios::binary);
if(people.fail( ))
{
cout << "打开文件people.dat出错! \n" ;
exit( 0 );
}
while( !people.eof( ))
{
people.read(( char *)&person, sizeof(person));
if(people.fail( )) break;
cout << "姓名: " << person.name << endl ;
cout << "年龄: " << person.age << endl ;
cout << "地址: " << person.address << endl ;
cout << "电话: " << person.phone << endl ;
cout << "邮箱: " << person.email << endl ;
cout << "\n按任意键,显示下一个记录!\n" ;
cin.get(again);
}
cout << "显示完毕 ! \n" ;
people.close( );
return 0;
}
随机访问文件
seekp 和 seekg 函数
seekp用于输出(写文件),seekg用于输入(读文件)
| 访问模式 | |
|---|---|
ios::beg |
从文件头计算偏移量 |
ios::end |
从文件尾计算偏移量 |
ios::cur |
从当前位置计算偏移量 |
file.seekp(20L,ios::beg); // 从文件开头移动 20 字节
file.seekg(0L,ios::end); // 移动到文件结尾
tellp 和 tellg 函数
tellp 用于返回写位置,tellg 返回读位置
pos1=outFile.tellp();
pos2=inFile.tellg();

浙公网安备 33010602011771号