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

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

实现效果为:

C++文件批量生成与读写_第1张图片

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

实现代码如下:

<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>


你可能感兴趣的:(C++,文件操作,文件批量生成)