1 ofstream:写操作
2 ifstream:读操作
3 fstream:读写操作
文本文件
写文件
1包含头文件
#include
2 创建流对象
osrteam ofs
3 打开文件
ofs.open(“文件打开方式”)
4 写数据
ofs<“写入的数据”;
5 关闭文件
ofs.close()
文件操作(写文件)
1 包含头文件
2 创建流
3 打开(选用合适的打开模式)
4 开始进行读或者写操作
5 关闭文件(操作完毕)
如果不指定路径的话,默认的情况就在源文件所在目录下生成一个所创建的文件
例如:一个简单的例子,代码如下所示:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
//文本文件 写文件
void test01()
{
//1 包含头文件 fstream
//2 创建流对象
ofstream ofs;
//3 打开的方式
ofs.open("test.txt", ios::out); //注意模式
//4 写内容
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:18" << endl;
for (int i = 0; i < 100000; i++)
{
ofs << "第 " << i << " 次打印!" << endl;
}
//5 关闭文件
ofs.close();
}
int main(void)
{
test01();
system("pause");
return 0;
}
文件操作(读文件)
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
//文本文件 写文件
void test01()
{
//1 包含头文件 fstream
//2 创建流对象
ifstream ifs;
//3 打开的方式
ifs.open("test.txt", ios::in); //注意模式(读取)
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
return;
}
//4.1 第一种读取方式
//char buf[100] = { 0 };
//while (ifs >> buf)
//{
// cout << buf << endl;
//}
//4.2 第二种读取方式
/*char buf[1024] = { 0 };
while (ifs.getline(buf, 1))
{
cout << buf<<endl;
}*/
//4.3 string
//string buf;
//while (getline(ifs, buf))
//{
// cout << buf << endl;
//}
//4.4
//这种方法是一个一个读取的,因此效率比较低
char c;
while ((c = ifs.get()) != EOF)
{
cout << c ;
}
//4 读取
//5 关闭文件
ifs.close();
}
int main(void)
{
test01();
system("pause");
return 0;
}
二进制文件
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
//二进制文件 写文件
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test01()
{
//1 包含头文件
//2 创建流对象
ofstream ofs("Person.txt",ios::out|ios::binary); //用二进制方式
//3 打开文件
Person p = { "张三",18 };
//4 写文件
ofs.write((const char*)&p,sizeof(p));//(const char*)&p强制转换
//5 关闭文件
ofs.close();
}
int main(void)
{
test01();
system("pause");
return 0;
}
用二进制去读取文件
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
//二进制文件 写文件
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test01()
{
//1 包含头文件
//2 创建流对象
//ifstream ifs("Person.txt",ios::out|ios::binary); //用二进制方式
ifstream ifs;
//3 打开文件
ifs.open("Person.txt", ios::out | ios::binary);
//Person p = { "张三",18 };
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
//4 写文件
Person p;
ifs.read((char *)&p, sizeof(Person));
cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
//5 关闭文件
ifs.close();
}
int main(void)
{
test01();
system("pause");
return 0;
}