-
头文件 #inlcude < fstream>
- 写文件
- ofstream ofs (文件路径,打开方式 ios::out )
- 判断文件是否打开成功 ofs.is_open
- ofs << “…”
- 关闭文件 ofs.close();
- 读文件
- ifstream ifs(文件路径,打开方式 ios::in)
- 判断文件是否打开成功 ofs.is_open
- 利用4种方式 对文件进行读取
- 关闭文件 ifs.close();
文件读写、
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void write_data() {
//ofstream ofs("./text.txt",ios::out | ios::trunc);
ofstream ofs;
ofs.open("./text.txt", ios::out | ios::trunc);
if (!ofs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
ofs << "abcdefg" << endl;
ofs << "abcdefg" << endl;
ofs << "abcdefg" << endl;
ofs << "abcdefg" << endl;
ofs.close();
}
void read_data() {
//ifstream ifs;
//ifs.open("./text.txt", ios::in);
ifstream ifs("./text.txt", ios::in);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
//第一种方式
//char buf[1024] = { 0 };
//while (ifs >> buf)
//{
// cout << buf << endl;
//}
//第二种方式
//char buf[1024] = { 0 };
//while (ifs.getline(buf,sizeof(buf)))
//{
// cout << buf << endl;
//}
//第三种方式
//string buf;
//while ( getline(ifs,buf) )
//{
// cout << buf << endl;
//}
//第四种方式
char c;
while ((c = ifs.get()) != EOF)
{
cout << c;
}
ifs.close();
}
int main() {
write_data();
read_data();
system("pause");
return EXIT_SUCCESS;
}
二进制文件读写实例、
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Maker
{
public:
string name;
int age;
public:
Maker() {}
Maker(string name, int age)
{
this->name = name;
this->age = age;
}
};
//写文件
void test01()
{
Maker *m1=new Maker("悟空", 18);
Maker *m2 = new Maker("贝吉塔", 22);
ofstream ofs;
ofs.open("test.txt", ios::out | ios::trunc | ios::binary);
if (!ofs.is_open())
{
cout << "打开失败" << endl;
}
//写
ofs.write((const char*)&m1, sizeof(Maker));
ofs.write((const char*)&m2, sizeof(Maker));
ofs.close();
}
//读文件
void test02()
{
ifstream ifs;
ifs.open("test.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "打开失败" << endl;
}
//读
Maker *m1;
Maker *m2;
ifs.read((char*)&m1, sizeof(Maker));
ifs.read((char*)&m2, sizeof(Maker));
cout << "Name:" << m1->name << " Age:" << m1->age << endl;
cout << "Name:" << m2->name << " Age:" << m2->age << endl;
delete m1;
delete m2;
ifs.close();
}
int main()
{
test01();
test02();
system("pause");
return EXIT_SUCCESS;
}