Vulkan

C++文件读取与写入

经常用到文件读写,图省事,记下来以后直接COPY

先写入文件

/***以下代码为将va的内容写入到4.txt文件
*	格式为:
*		1,2
*		2,4
*		3,6
***/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct mpoint
{
	int x;
	int y;
	mpoint(int _i,int _j)
	{
		x=_i;
		y=_j;
	}

};
int main()
{
	/***初始化va***/
	vector<mpoint>va;
	for (int i=0;i<20;i++)
	{
		va.push_back(mpoint(i,2*i));
	}
	
	ofstream outfile;
	outfile.open("e:\\4.txt",ios::app);
	if(!outfile)
	{
		cout<<"Can not open file"<<endl;
	}
	/***写入数据***/
	for (int i=0;i<va.size();i++)
	{
		outfile<<va[i].x<<" "<<va[i].y<<'\n';
	}

	outfile.close();
	return 0;
}

读取文件
/***以下代码为将文件4.txt的内容读取到vb
*	文件中数据存储格式为:
*		1,2
*		2,4
*		3,6
***/


#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

struct mpoint
{
	int x;
	int y;
	mpoint(int _i,int _j)
	{
		x=_i;
		y=_j;
	}
};

int main(int args, char **argv)
{
	vector<mpoint>vb;
	std::ifstream  fin("e:\\4.txt", std::ios::in);
	char  line[1024]={0};
	std::string  x = "";
	std::string  y = "";
	int ix;
	int iy;

	while(fin.getline(line, sizeof(line)))/***按行读取***/
	{
		std::stringstream  word(line);
		word >> x;
		word >> y;
		ix=atoi(x.c_str());/***string转换为int***/
		iy=atoi(y.c_str());
		vb.push_back(mpoint(ix,iy));
	}

	/***打印到控制台***/
	for (int i=0;i<vb.size();i++)
	{
		cout<<vb[i].x<<","<<vb[i].y<<endl;
	}
	
	fin.clear();
	fin.close();
	return 0;
}


posted on 2012-12-06 16:10  Vulkan  阅读(328)  评论(0编辑  收藏  举报

导航