C++文本文件操作和二进制文件读写
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++文本文件操作和二进制文件读写相关的知识,希望对你有一定的参考价值。
文本文件操作:
代码如下:
#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;
}
以上是关于C++文本文件操作和二进制文件读写的主要内容,如果未能解决你的问题,请参考以下文章