操作文件的三大类
- ofstream:写操作
- ifstream:读操作
- fstream:读写操作
文件打开方式
写文本文件
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream ofs;
ofs.open("demo.txt", ios::out);//打开文件,并指定打开方式为写文件,如果文件不存在,会自动创建
ofs << "Hello" << endl;//写入内容
ofs << "World" << endl;//写入内容
ofs.close();
return 0;
}
读文本文件
对于文件读取,还是比较推荐方案一二
int main() { ifstream ifs; ifs.open(“demo.txt”, ios::in);//打开文件,并指定打开方式为写文件
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
return -1;
}
char buf[1024] = {0};
while (ifs.getline(buf,sizeof(buf)))
{
cout << buf << endl;//打印读取到的内容
}
ifs.close();
return 0;
}
- 方案二
```cpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream ifs;
ifs.open("demo.txt", ios::in);//打开文件,并指定打开方式为写文件
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
return -1;
}
string buf;
while (getline(ifs,buf))
{
cout << buf << endl;//打印读取到的内容
}
ifs.close();
return 0;
}
int main() { ifstream ifs; ifs.open(“demo.txt”, ios::in);//打开文件,并指定打开方式为写文件
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
return -1;
}
char buf[1024] = {0};
while (ifs>>buf)
{
cout << buf << endl;//打印读取到的内容
}
ifs.close();
return 0;
}
- 方案四
```cpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream ifs;
ifs.open("demo.txt", ios::in);//打开文件,并指定打开方式为写文件
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
return -1;
}
char c;
while ((c = ifs.get())!=EOF)//判断是否读到文件尾c
{
cout << c;//打印读取到的内容
}
ifs.close();
return 0;
}
写二进制文件
#include <fstream>
#include <iostream>
using namespace std;
class People{
public:
char mName[128];
int mAge;
};
int main()
{
ofstream ofs("person.txt", ios::out|ios::binary);//打开文件,并指定打开方式为写文件,如果文件不存在,会自动创建
People p = {"小明", 12};
ofs.write((const char *)&p,sizeof(p));
ofs.close();
return 0;
}
读二进制文件
#include <fstream>
#include <iostream>
using namespace std;
class People{
public:
char mName[128];
int mAge;
};
int main()
{
ifstream ifs("person.txt", ios::in|ios::binary);//打开文件,并指定打开方式为写文件,如果文件不存在,会自动创建
if (!ifs.is_open())
{
cout << "文件打开失败!" << endl;
return -1;
}
People p;
ifs.read((char *)&p,sizeof(People));
cout << "姓名:" << p.mName << ",年龄" << p.mAge << endl;
return 0;
}