(12.1) 文本文件的写入
文本文件以ASCII码的形式存储在计算机中。
#include<iostream>
#include<fstream> //(1)文件操作需要包含文件流头文件
using namespace std;
int main()
{
ofstream ofs; //(2)创建文件流对象
//ofstream ofs; //创建写入文件的流对象
//ifstream ifs; //创建读取文件的流对象
//fstream fs; //创建读写文件的流对象
ofs.open("data.txt",ios::out); //(3)指定打开方式(文件默认路径是项目所在路径)
//ios::in 只读
//ios::out 只写
//ios::ate 将读写位置移到文件尾
//ios::app 以追加方式写入
//ios::trunk 如果文件存在就先删除再创建
//ios::binary 以二进制方式读写
ofs << "姓名:张三" << endl; //(4)写入文件
ofs << "性别:男" << endl;
ofs << "年龄:18" << endl;
ofs.close(); //(4)关闭文件
system("pause");
return 0;
}
(12.2) 文本文件的读取
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
ifstream ifs;
ifs.open("data.txt",ios::in);
if(!ifs.is_open()) //判断是否打开成功
{
cout << "文件打开失败!" << endl;
return 0;
}
//第一种读取方法
char buffer1[1024] = {0}; //初始化全为0
while(ifs >> buffer1) //将ifs中的数据放到(>>)buffer数组中
{
cout << buffer1 << endl;
}
//第二种读取方法
char buffer2[1024] = {0};
while(ifs.getline(buffer2,sizeof(buffer2)))
{
cout << buffer2 << endl;
}
//第三种读取方法
string str;
while(getline(ifs,str))
{
cout << str << endl;
}
//第四种读取方法
char c;
while( (c = ifs.get()) !=EOF ) //EOF:end of file
{
cout << c;
}
ifs.close();
system("pause");
return 0;
}
(12.3) 二进制文件的写入
二进制文件以二进制的形式存储在计算机中。
#include<iostream>
#include<fstream>
using namespace std;
class Person
{
public:
char m_Name[64]; //在写入字符串的时候最好不要用C++的string,用C语言的字符数组
int m_Age;
};
int main()
{
Person p = {"张三",18};
ofstream ofs;
ofs.open("person.txt",ios::out | ios::binary);
ofs.write((const char*)&p , sizeof(Person)); //参数形式是规定好了的,记住就好
ofs.close();
system("pause");
return 0;
}
虽然二进制文件点开后显示出来有乱码,但是只要文件读出来是我们想要的就可以了。
(12.4) 二进制文件的读取
#include<iostream>
#include<fstream>
using namespace std;
class Person
{
public:
char m_Name[64];
int m_Age;
};
int main()
{
ifstream ifs;
ifs.open("person.txt",ios::in | ios::binary);
if(!ifs.is_open())
{
cout << "文件打开失败" << endl;
return 0;
}
Person p;
ifs.read((char *)&p , sizeof(Person));
cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
ifs.close();
system("pause");
return 0;
}
《 C + + S Y N T A X 》 系 列 博 客 创 作 参 考 资 料 来 源 《C++\ SYNTAX》系列博客创作参考资料来源 《C++ SYNTAX》系列博客创作参考资料来源
- 《黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难》@黑马程序员.https://www.bilibili.com.
博 客 创 作 : A i d e n L e e 博客创作:Aiden\ Lee 博客创作:Aiden Lee
特别声明:文章仅供学习参考,转载请注明出处,严禁盗用!