文本文件操作:
代码如下:
#include <iostream>
#include <fstream>
using namespace std;void test01()
{const char *fileName = "C:\\Users\\Tom\\Desktop\\hhh.txt";//ifstream ism(fileName, ios::in);//只读方式打开文件ifstream ism;ism.open(fileName, ios::in);const char *TagetName = "C:\\Users\\Tom\\Desktop\\jjj.txt";ofstream osm(TagetName, ios::out);if (!ism){cout << "打开文件失败" << endl;return;}//读文件char ch;while (ism.get(ch)){/*cout << ch;*/osm.put(ch);}ism.close();osm.close();}int main()
{test01();return 0;
}
追加写文件操作核心代码:
ofstream osm(TagetName, ios::out | ios::app);
代码如下:
#include <iostream>
#include <fstream>
using namespace std;void test01()
{const char *fileName = "C:\\Users\\Tom\\Desktop\\hhh.txt";//ifstream ism(fileName, ios::in);//只读方式打开文件ifstream ism;ism.open(fileName, ios::in);const char *TagetName = "C:\\Users\\Tom\\Desktop\\jjj.txt";ofstream osm(TagetName, ios::out | ios::app);if (!ism){cout << "打开文件失败" << endl;return;}//读文件char ch;while (ism.get(ch)){/*cout << ch;*/osm.put(ch);}ism.close();osm.close();}int main()
{test01();return 0;
}
二进制文件读写:
对象的序列化: 把对象写入文件
代码如下:
#include <iostream>
#include <fstream>
using namespace std;class Person
{
public:Person(){}Person(int age,int id):age(age),id(id){}void show(){cout << "age = " << age << "id = " << id << endl;}public:int age;int id;
};void test01()
{const char * fileName = "C:\\Users\\Tom\\Desktop.jjj.txt";Person p1(10, 20), p2(30, 40);//二进制存储//把p1,p2写进文件里ofstream osm(fileName, ios::out | ios::binary);osm.write((char*)&p1, sizeof(Person));osm.write((char*)&p2, sizeof(Person));osm.close();ifstream ism(fileName, ios::in | ios::binary);Person p3,p4;ism.read((char *)&p3, sizeof(Person));//从文件读取数据ism.read((char *)&p4, sizeof(Person));//从文件读取数据p3.show();p4.show();}int main()
{test01();return 0;
}