C++文件读写
#include<iostream>
#include<fstream>
using namespace std;
#include<string>
void test01()
{
ofstream ofs;
ofs.open("E:\\VC++ Project\\test01.txt", ios::out);
/*ofs << "name:lucy" << endl;
ofs << "age:23 " << endl;*/
ofs << "名字:张三" << endl;
ofs << "年龄:23 " << endl;
ofs.close();
}
void test02()
{
ifstream ifs;
ifs.open("E:\\VC++ Project\\test01.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
exit(1);
}
//第一种读的方式
/*char buf01[1024] = { 0 };
while (ifs >> buf01)
{
cout << buf01 << endl;
}*/
第二种读的方式
//char buf02[1024] = { 0 };
//while (ifs.getline(buf02, sizeof(buf02)))
//{
// cout << buf02 << endl;
//}
//第三种读的方式
/*string buf03;
while (getline(ifs, buf03)) //此处注意如果引用的是<cstring>头文件,则会报错,如若导入的是<string>的头文件,则错误消失
{
cout << buf03 << endl;
}*/
//第四种读的方式,一个一个字符读,效率低,不推荐
char c;
while ((c = ifs.get()) != EOF)
{
cout << c ;
//cout << endl;
}
}
class Person
{
public:
Person(string name, int age)
{
this->name = name;
this->age = age;
}
Person()
{
}
string name;
int age;
};
//用二进制来写文件
void test03()
{
ofstream ofs("E:\\VC++ Project\\test02.txt", ios::out | ios::binary);
//ofs.open("E:\\VC++ Project\\test012.txt", ios::out | ios::binary);
Person p = { "wangwu",28 };
ofs.write((const char *)&p, sizeof(Person)); //sizeof是编译期间确定的,是实际分配的内存空间,而strlen是字符串长度,不含结束符‘\0’
ofs.close();
}
//用二进制来读文件
void test04()
{
ifstream ifs;
ifs.open("E:\\VC++ Project\\test02.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "文件打开失败!!" << endl;
return;
}
Person p;
ifs.read((char*)&p, sizeof(Person));
cout << p.name << endl;
cout << p.age << endl;
ifs.close();
}
int main()
{
test01();
test02();
test03();
test04();
return 0;
}
总结步骤:
- 1. 引入头文件
- 2. 创建流对象
- 3. 打开文件(构造函数或者调用open函数)
- 4. 进行读写操作
- 5. 关闭文件