#include <fstream>
using namespace std;
class WriteReadTxt
{
public:
void ReadTxt(char* file,vector<int>& vec);
void WriteTxt(char* file,int maxSize);
};
void WriteReadTxt::ReadTxt(char* file,vector<int>& vec)
{
ifstream fin(file);
if(!fin){
cout<<"can not open file!"<<endl;
}
int i;
while ( fin >> i )
{
vec.push_back(i);
}
fin.close();
}
void WriteReadTxt::WriteTxt(char* file,int maxSize)
{
ofstream fout(file);
if(!fout){
cout<<"file not found!"<<endl;
}
int n = 0,a;
srand( time(NULL) );
while(n++ < maxSize){
a = rand()% maxSize;
fout<<a<<" ";
if(n%20 == 0){
fout<<endl;
}
}
fout.close();
}
主函数调用:
vector<int> nums;
WriteReadTxt * txt = new WriteReadTxt();
int maxsize = 1000;
char* str = (char*)malloc(100);//必须要分配空间,否则str会成为野指针,每次函数传递都得要分配空间
sprintf(str, "%d", maxsize);
txt -> WriteTxt(str,maxsize);
txt -> ReadTxt(str,nums);
注意:指针作为函数参数传递时,一定要分配空间,否则会出现野指针。