编程语言
首页 > 编程语言> > c++文件读写

c++文件读写

作者:互联网

// 输入输出流1.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iomanip>
#include<iostream>
#include<fstream>
using namespace std;
//文本文件读写
void test1()
{

	
	const char * path = "C:\\Users\\lfzh\\Desktop\\source.txt";
	const char* target = "C:\\Users\\lfzh\\Desktop\\target.txt";
	//法一
	ifstream ism(path, ios::in);//只读方式打开文件,调用构造函数打开文件
	//ofstream osm(target, ios::out);//每次都会删掉之前写入的
	ofstream osm(target, ios::out|ios::app);//实现写入的内容追加
 //法二
	/*
	ifstream ism;
	ism.open(path, ios::in);//调用成员方法打开文件
	*/
	if (!ism)//判断是否成功打开文件
	{
		cout << "打开文件失败" << endl;
		return;
	}

	//读文件
	char ch;
	while (ism.get(ch))
	{
		cout << ch;
		osm.put(ch);
	}
	//关闭文件
	ism.close();
	osm.close();
}
int main()
{
	test1();

    return 0;
}


// 输入输出流1.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iomanip>
#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 id;
	int age;
 };
void test()
{
	//文本模式读的是文本文件吗
	//二进制文件读的是二进制文件吗
	Person p1(10, 20), p2(30, 40);//以二进制放入内存的
	//把p1 p2写入文件
     const char * targetname = "C:\\Users\\lfzh\\Desktop\\target.txt";
	 ofstream osm(targetname, ios::out | ios::binary);
	 osm.write((char*)&p1,sizeof(Person));
	 osm.write((char*)&p2, sizeof(Person));
	 osm.close();

	 ifstream ism(targetname, ios::in | ios::binary);
	 Person p;
	 ism.read((char*)&p1,sizeof(Person));
	 ism.read((char*)&p2, sizeof(Person));
	 p1.show();
	 p2.show();
}
int main()
{
	test();

    return 0;
}


标签:文件,target,读写,ios,c++,Person,ism,include,id
来源: https://blog.csdn.net/weixin_41375103/article/details/104671740