C++ 核心编程 ——4.9 文件操作
4.9.0 概述
程序运行时产生的数据都属于临时数据,一旦运行结束都被释放,通过文件可以将数据持久化
C++中对文件操作需要包含文件流的头文件 ==< fstream >==
文件类型 | 文本文件 | 文件以文本的ASCII码(每个字符都有对应的编码)形式存储在计算机中 | |
二进制文件 | 文件以文本的二进制(一般不能直接读懂它们)形式存储在计算机中 | ||
操作类型 | 写操作 | ofstream | output-file-stream |
读操作 | ifstream | input-file-stream | |
读写操作 | fstream |
打开方式 | 解释 |
iios::in | 为读文件而打开文件 |
ios::out | 为写文件而打开文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 追加方式写文件 |
ios::trunc | 如果文件存在先删除,再创建 |
ios::binary | 二进制方式 |
可以配合使用:利用 | 操作符 | ios::binary | ios:: out (二进制方式写文件) |
4.9.1 文本文件
4.9.1.1 写文件
步骤 | 1.包含头文件 | #include <fstream> |
2.创建流对象 (通过ofstream这个类来创建对象) | ofstream ofs; | |
3.打开文件 | ofs.open("文件路径",打开方式); | |
4.写数据(文件的输出流对象) | ofs << "写入的数据"; | |
5.关闭文件 | ofs.close(); |
#include<iostream>
#include"string"
#include<fstream>
using namespace std;
void test()
{
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "姓名:张三" << endl;
//endl在文件中可以用于换行
ofs << "电话:13712345678" << endl;
ofs.close();
};
int main()
{
test();
system("pause");
return 0;
}
4.9.1.2 读文件
步骤 | 1.包含头文件 | #include <fstream> |
2.创建流对象 (通过ifstream这个类来创建对象) | ofstream ifs; | |
3.打开文件并判断文件是否打开成功 | ifs.open("文件路径",打开方式); | |
4.读数据 | ||
5.关闭文件 | ofs.close(); |
读取方式 | 语法 | 原理 | ||
数组 char buf[1024] = { 0 }; | ifs >> buf | 左移运算,读完返回假 | ||
ifs.getline(buf,sizeof(buf)) | isf子类函数(位置,参数量) | |||
字符 | 字符串 | string buf | getline(ifs, buf) | 全局函数(输入流,接受字符串) |
单个字符 | char buf | ((buf = ifs.get()) != EOF | 一个个读(慢)不推荐 | |
EoF:end of file | ||||
没有读到文件尾就一直读 |
#include<iostream>
#include"string"
#include<fstream>
using namespace std;
void test()
{
ifstream ifs;
ifs.open("test.txt",ios::in);
if( !ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
};
第一种方式
//char buf[1024] = { 0 };
//while(ifs >> buf )
//{
// cout << buf << endl;
//};
/*char buf[1024] = { 0 };
while(ifs.getline(buf,sizeof(buf)))
{
cout << buf << endl;
}*/
/*string buf;
while(getline(ifs,buf))
{
cout << buf << endl;
}*/
char buf;
while( (buf = ifs.get())!=EOF)
{
cout << buf ;
}
};
int main()
{
test();
system("pause");
return 0;
}
4.9.2 二进制文件
以二进制的方式对文件进行读写操作
打开方式要指定为 ==ios::binary==
4.9.2.1 写文件
二进制方式写文件主要利用流对象调用成员函数write
ostream& write(const char * buffer,int len);
先创建输出流对象ostream,后调用write函数,最后传入数据地址(const char *buffer),数据长度(int len)
参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
4.9.2.2 读文件
二进制方式读文件主要利用流对象调用成员函数read
istream& read(char *buffer,int len);
参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
#include<iostream>;
#include"string";
using namespace std;
#include <fstream>;
class Person
{
public:
char name[64];
int age;
};
void write()
{
ofstream ofs("person.txt", ios::out | ios::binary);
Person p = { "张三" ,18};
ofs.write((const char*)&p , sizeof(p));
ofs.close();
return;
}
void read()
{
ifstream ifs("person.txt",ios::in | ios::binary);
if(! ifs.is_open())
{
cout<<"打开文件失败"<< endl;
};
Person p;
ifs.read( (char*)&p, sizeof(p));
cout<< p.name << p.age << endl;
ifs.close();
};
int main()
{
//write();
read();
system("pause");
return 0;
}