文本文件
写文件
文件打开方式:
打开方式 | 解释 |
---|---|
ios::in | 为读文件而打开文件 |
ios::out | 为写文件而打开文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 追加方式写文件 |
ios::trunc | 如果文件存在先删除,再创建 |
ios::binary | 二进制方式 |
int main()
{
// 1.包含头文件 <fstream>
// 2.创建流对象
// 1. ofstream:写操作
// 2. ifstream: 读操作
// 3. fstream : 读写操作
ofstream ofs;
// 3.打开文件 ofs.open("文件路径",打开方式);
ofs.open("test.txt", ios::out);
// 4.写数据
ofs << "zhangsan 18 " << endl;
// 5.关闭文件
ofs.close();
system("pause");
return 0;
}
读文件
// 读文件操作
void test()
{
// 1.包含头文件
// 2.创建流对象
ifstream ifs;
// 3.打开文件并判断打开是否成功
ifs.open("test.txt", ios::in);
if (!ifs.is_open()) // ifs.is_open 判断文件是否打开,打开返回true
{
cout << "打开失败" << endl;
return; // 结束运行
}
// 4.读数据,四种方式
// 1.
string buf;
while (getline(ifs, buf))
{
cout << buf << endl;
}
// 2.
/*char buf[1024] = { 0 };
while (ifs >> buf)
{
cout << buf << endl;
}*/
// 3.
/*char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf)))
{
cout << buf << endl;
}*/
// 4.
//char c;
//while ((c = ifs.get()) != EOF) // EOF是 end of file 文件结尾
//{
// cout << c;
//}
// 5.关闭文件
ifs.close();
}
二进制文件
写文件
// 二进制写文件
class Person
{
public:
char name[50];
int age;
};
void test()
{
// 1.创建流对象
ofstream ofs;
// 2.打开文件
ofs.open("person.txt", ios::out | ios::binary); // 二进制文件
// 3.写文件
Person p = { "zhangsan" , 18 };
ofs.write((const char*)&p, sizeof(Person)); // 把对象p强制转换成const char*类型
ofs.close();
}
读文件
// 二进制读文件
class Person
{
public:
char name[50];
int age;
};
void test()
{
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "打开失败" << endl;
return;
}
Person p2;
ifs.read((char*)&p2, sizeof(Person));
cout << p2.name << "\t" << p2.age << endl;
ifs.close();
}