C++文件批量生成与读写

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/walkandthink/article/details/41847961

利用C++的fstream流,批量生成文件,并对文件写入数据。

实现效果为:


注意输入扩展名是,前面需要加上".",比如".txt"

实现代码如下(基于VS2013编译器实现):

<span style="font-size:18px;">#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

void WriteFile(ofstream &file)
{
	int LineNum,LineLength;
	int i,j;
	LineNum=1+rand()%50;
	for (i=1;i<=LineNum;i++)
	{
		LineLength=1+rand()%20;
		for (j=1;j<=LineLength;j++)
		{
			file<<rand()%1000<<" ";
		}
		file<<endl;
	}
	file.close();
}

void CreateFile(int n)
{
	ofstream *file;
	file=new ofstream[n];
	string *filename;
	string sname,tname,str;
	cout<<"请输入文件的前缀名:";
	cin>>sname;
	cout<<"请输入文件的扩展名:";
	cin>>tname;
	filename=new string[n];
	int i,j;
	char a[10];
	for (i=1;i<=n;i++)
	{
		sprintf_s(a,"%d",i);
		str=a;
		filename[i-1]=sname+str+tname;
	}
	for (i=1;i<=n;i++)
	{
		file[i-1].open(filename[i-1],ios::out);
		WriteFile(file[i-1]);
	}
}

int main()
{
	int FileNum;
	cout<<"请输入要创建的文件数目:";
	cin>>FileNum;
	CreateFile(FileNum);
	return 0;
}</span>


有部分人反应上面的代码有问题,我又重新编译了下,发现是VS的编译器与GCC编译器支持标准不一样导致的问题。下面补充一个用CodeBlocks写的,基于GCC4.9编译器的版本,我自己编译能通过。另外,C++11标准里面有更简单的函数实现int到string的转换。


下面是基于GCC4.9的代码:


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

void WriteFile(ofstream &file)
{
	int LineNum, LineLength;
	int i, j;
	LineNum = 1 + rand() % 500;
	for (i = 1; i <= LineNum; i++)
	{
		LineLength = 1 + rand() % 200;
		for (j = 1; j <= LineLength; j++)
		{
			file << rand() % 10000 << " ";
		}
		file << endl;
	}
	file.close();
}

void CreateFile(int n)
{
	ofstream *file;
	file = new ofstream[n];
	string *filename;
	string sname, tname, str;
	cout << "请输入文件的前缀名:";
	cin >> sname;
	cout << "请输入文件的扩展名:";
	cin >> tname;
	filename = new string[n];
	int i;
	for (i = 1; i <= n; i++)
	{
	    ostringstream convert;
		convert<<i;
		str = convert.str();
		filename[i - 1] = sname + str + tname;
	}
	for (i = 1; i <= n; i++)
	{
		file[i - 1].open(filename[i - 1].c_str(), ios::out);
		WriteFile(file[i - 1]);
	}
}

int main()
{
	int FileNum;
	cout << "请输入要创建的文件数目:";
	cin >> FileNum;
	CreateFile(FileNum);
	return 0;
}


猜你喜欢

转载自blog.csdn.net/walkandthink/article/details/41847961
今日推荐