1. 文件操作
程序运行时产生的数据都属于临时数据,程序一旦运行结束就会被释放掉,可以通过文件将数据保存下来,持久化。
C++中对文件进行操作需要包含头文件
文件类型:
- 文本文件:文件以文本的ASCII码形式存储在计算机中;
- 二进制文件:文件以文本的二进制形式存储在计算机中;
文件操作的类型:(三个类)
- ofstream 读操作
- ifstream 写操作
- fstream 读写操作
1.1 文本文件
1.1.1 写文件步骤
- 包含头文件;
#include - 创建流对象;
ofstream ofs; - 打开文件;
ofs.open(“文件路径”,打开方式); - 写入数据;
ofs<<“写入的数据”; - 关闭文件;
ofs.close;
文件打开方式:
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件(文件尾追加)
ios::trunc 如果文件存在,先删除再创建
ios::binary 二进制方式操作
注意:文件操作方式可以配合使用,利用“|”操作符;
#include <fstream>
void test54()
{
ofstream ofs; //或者 fstream ofs;
ofs.open("test.txt", ios::out | ios::trunc); //不加绝对路径,会在项目文件目录下创建文件
ofs << "Hello China !" << endl;
ofs.close();
}
void main54()
{
test54();
}
1.1.2 读文件步骤
-
包含头文件;
#include -
创建流对象;
ifstream ifs; -
打开文件并判断文件是否打开成功;
ifs.open(“文件路径”,打开方式);
if (!ifs.is_open()){} -
读数据;
四种方式读取: 1)利用字符数组 while (ifs >> buf) 2)利用字符数组 while (ifs.getline(buf, sizeof(buf))) 3)利用字符串 while (getline(ifs, buf)) 4)利用单个字符 while ((c = ifs.get()) != EOF)
-
关闭文件;
ifs.close();
#include <fstream>
void test55()
{
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 c;
while ((c = ifs.get()) != EOF)//逐个字符读入,判断是否读到文件尾 EOF(end of file)
{
cout << c ;
}
ifs.close();
}
int main55()
{
test55();
system("pause");
return 0;
}
1.2 二进制文件
以二进制的方式对文件进行读写操作,打开方式要指定为 ios::binary
1.2.1 写文件
二进制方式写文件主要利用流对象调用成员函数write
函数原型:*ostream& write(const char* buffer,int len);*
参数解释:字符指针buffer指向内存中一段存储空间,len是读写的字节数。
class Dog
{
public :
char m_Dog[640];
int m_Age;
};
void test56()
{
ofstream ofs;
ofs.open("test2.txt", ios::out | ios::binary | ios::trunc);
//等价于 ofstream ofs("test2.txt", ios::out | ios::binary);
Dog d1 = { "哈士奇",5 };//隐式转换法
ofs.write((const char*)&d1, sizeof(d1));//取地址、强制转换
ofs.close();
}
int main56()
{
test56();
system("pause");
return 0;
}
1.2.2 读文件
二进制方式读文件主要利用流对象调用成员函数read
函数原型:*istream& read(char *buffer, int len);*
参数解释:字符指针buffer指向内存中一段存储空间,len是读写的字节数。
class Dog2
{
public :
char m_Dog[64];
int m_Age;
};
void test57()
{
ifstream ifs("test2.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
Dog2 d2;
ifs.read((char*)&d2, sizeof(d2));
cout << "名字:" << d2.m_Dog << "年龄:" << d2.m_Age << endl;
ifs.close();
}
int main57()
{
test57();
system("pause");
return 0;
}
问题:写入和读出的年龄不一样
原因:当class Dog的 char m_Dog[64]; 与class Dog2的 char m_Dog[64]; 字符数组的位数不相同时,会造成读和写不一致。
(哔哩哔哩黑马程序员 C++教程 学习笔记,如有侵权请联系删除)