#include <iostream>
using namespace std;
#include <string>
//文件操作
//写文件 ofs out把数据放到文件
//读文件 ifs in把文件数据放到自己准备好的地方
#include <fstream>//头文件
//写文件
void test()
{
//添加头文件
//创建流对象
ofstream ofs;//out file 写文件
//指定打开方式
ofs.open("test.txt", ios::out);
//写
ofs << "123456789" << endl;
ofs << "123456789" << endl;
ofs << "123456789" << endl;
ofs << "123456789" << endl;
//关闭文件
ofs.close();
}
int main()
{
test();
}
#include <iostream>
using namespace std;
#include <string>
//文件操作
#include <fstream>//头文件
//读文件
void test1()
{
//创建流对象
ifstream ifs;
//指定打开方式
ifs.open("test.txt", ios::in);
//判断打开是否成功
if (!ifs.is_open())
{
cout << "defest" << endl;
return;//程序到此结束
}
//读取
//方式1
/* char buf[1024] = {0};
while (ifs >> buf) //碰到空格会直接换行
{
cout << buf << endl;
} */
//方式2
/* char buf[1024] = {0};
while (ifs.getline(buf, sizeof(buf)))
{
cout << buf << endl;
} */
//方式3
string buf;//推荐
while (getline(ifs, buf))//ifs:流对象 buf:准备好的字符串
{
cout << buf << endl;
}
ifs.close();
}
int main()
{
test1();
}
#include <iostream>
using namespace std;
#include <string>
//文件操作
#include <fstream>//头文件
//二进制
//写二进制
class person
{
public:
int m_age;
char m_name[64];
};
void test()
{
ofstream ofs("person.txt", ios::out | ios::binary);
//ofs.open("person.txt",ios::out|ios::binary);
person p = {18,"abc"};
ofs.write((const char*)&p,sizeof(person));
ofs.close();
}
int main()
{
test();
}
#include <iostream>
using namespace std;
#include <string>
//文件操作
#include <fstream>//头文件
//读二进制
class person
{
public:
int age;
char m_name[64];
};
void test()
{
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "defeat" << endl;
return;
}
person p;
ifs.read((char*)&p, sizeof(person));
cout << p.age << p.m_name << endl;
ifs.close();
}
int main()
{
test();
}
C++22/03/17
最新推荐文章于 2024-10-08 06:04:53 发布
本文详细介绍了C++中如何进行文件操作,包括文本文件的写入和读取,以及二进制文件的写入和读取。通过示例代码展示了使用ofstream和ifstream对象进行文件操作的方法,包括不同方式读取文件内容的技巧。同时,还展示了如何进行二进制数据的序列化和反序列化操作。
摘要由CSDN通过智能技术生成