概述
文件流: 对文件进行读写操作头文件: <fstream>
类库:
①ifstream 对文件输入(读文件)
②ofstream 对文件输出(写文件)
③fstream 对文件输入或输出
文本文件和二进制文件的区别:
文本文件: 写数字1, 实际写入的是 ‘1’
二进制文件:写数字1, 实际写入的是 整数1(4个字节,最低字节是1, 高3个字节都是0) 写字符‘R’实际输入的还是‘R’
既对于数字来说文本文件和二进制文件会有大的不同其他的都基本没什么区别。
文件的打开操作时也有很多的模式:
这些模式标记都是可以通过位操作符|来进行组合。
一、文本文件读写操作
1、文本文件写操作
对文本文件进行写操作有几个步骤:①打开文件②输入数据
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main1() {
string name;
int age;
ofstream outfile;//定义一个输出流对象
//fstream outfile;
//打开文件
outfile.open("user.txt");//利用fstream默认写文件不截段,用ofstream默认写文件截段
while (1) {
cout << "请输入姓名:【ctrl+z退出】";
cin >> name;
if (cin.eof()) {//是否结束ctrl+z
break;
}
outfile << name << '\t';
cout << "请输入年龄:【ctrl+z退出】";
cin >> age;
outfile << age << endl;
}
//关闭打开的文件流
outfile.close();
return 0;
}
总结:就像在代码中的注释一样,利用fstream默认写文件不截断,用ofstream默认写文件截断为0(不截断的意思是从第文件第一个字节开始对原先的数据进行覆盖,截断的意思是直接把原来的的数据全部删除,再写文件)
2、文本文件读操作
对文本文件进行读操作有几个步骤:①打开文件②读取数据
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
string name;
int age;
fstream inFile;
inFile.open("user.txt", ios::in);
while (1) {
inFile >> name;//遇到空格,‘\t','\n'都会自动跳过
if (inFile.eof()) {
break;
}
cout << name<<'\t';
inFile >> age;
cout << age << endl;
}
//关闭文件流
inFile.close();
return 0;
}
总结:对于文本文件的读操作来说在读取数据的时候遇到制表符(‘\t’,’\n’…)都会自动跳过。
二、二进制文件
1、二进制文件写操作
对二进制文件进行读操作有几个步骤:①打开文件②写入数据
和文本文件不同的是在打开文件时要指定为二进制,使用文件流对象的write方法写入二进制数据.
outfile.write((char*)&age, sizeof(age));//对于数字的写入就得这样
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
ofstream outfile;
outfile.open("user.dat", ios::out | ios::trunc | ios::binary);//指定二进制文件打开,记住不能用txt类型
while (1) {
cout << "请输入姓名: [ctrl+z退出] ";
cin >> name;
if (cin.eof()) { //判断文件是否结束
break;
}
outfile << name << "\t";
cout << "请输入年龄: ";
cin >> age;
//outfile << age << endl; //如果这样的话会自动转成文本方式写入
outfile.write((char*)&age, sizeof(age));
}
// 关闭打开的文件
outfile.close();
system("pause");
return 0;
}
总结:与写文本文件不同的是①打开文件方式②把数字写入文件的操作
2、二进制文件读操作
对二进制文件进行读操作有几个步骤:①打开文件②读取数据
与文本文件读操作不同的是要指定文件打开方式,在读取二进制文件数据时不会跳过制表符,在读取制表符和数字时要利用文件流的read方法。
infile.read((char*)&age, sizeof(age));
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
ifstream infile;
infile.open("user.dat", ios::in | ios::binary);
while (1) {
infile >> name;
if (infile.eof()) { //判断文件是否结束
break;
}
cout << name << "\t";
// 跳过中间的制表符
char tmp;
infile.read(&tmp, sizeof(tmp));
//infile >> age; //从文本文件中读取整数, 使用这个方式
infile.read((char*)&age, sizeof(age));
cout << age << endl; //文本文件写入
}
// 关闭打开的文件
infile.close();
system("pause");
return 0;
}
总结:与文本文件读操作不同的是①要指定文件打开方式②在读取二进制文件数据时不会跳过制表符③read方法的使用。