您的位置:首页 > 其它

随机文件生成器

2014-11-29 22:38 204 查看
// WriteBigFile.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#include <string.h>

#include <windows.h>

#define WORDSINLINE 150 //每行字节数

#define NUMOFLINES 1000000 //行数

#define BIGFILENAME1 "..\\BigFile1.dat"

#define BIGFILENAME2 "..\\BigFile2.dat"

#ifdef _DEBUG

#define MOSHI "Debug模式下"

#else

#define MOSHI "Release模式下"

#endif

#define Conn(x,y) x ## y

#define ToChar(x) #@ x

#define ToStr(x) # x

int main(int argc, char* argv[])

{

/*

这个工程的主要用途是产生一个很大的文件:

一行150个字节 --- 前六位代表行号 + "--" +随机字母

1,000,000行

1000*1000*150/1024*1024 = 大约143兆

*/

srand( (unsigned)time( NULL ) );//与时间相关的随机种子

//创建文件

if (GetFileAttributes(BIGFILENAME1) != -1)

{

if (!DeleteFile(BIGFILENAME1))

{

printf("文件1已存在,删除失败\n");

return 1;

}

}

if (GetFileAttributes(BIGFILENAME2) != -1)

{

if (!DeleteFile(BIGFILENAME2))

{

printf("文件2已存在,删除失败\n");

return 1;

}

}

FILE * pBigFile1 = fopen(BIGFILENAME1,"ab+");

if (pBigFile1 == NULL)

{

return 1;

}

FILE * pBigFile2 = fopen(BIGFILENAME2,"ab+");

if (pBigFile2 == NULL)

{

return 1;

}

//写文件

int randNum;

char basicChar = 'a';

char randChar;

char string[WORDSINLINE+2];

memset(string,0,WORDSINLINE+2);

clock_t time1 = clock();//测量时间

for (int i=0; i<NUMOFLINES; i++)

{

for (int j=10; j<WORDSINLINE-2; j++)//从第11个字节开始随机赋值

{

randNum = rand()%25;//随机产生0-25之间的数字

randChar = (char)(basicChar+randNum);

string[j]=randChar;

}

string[0]= ToChar(1);

string[1]=(char)('0'+(i/100000)%10 );

string[2]=(char)('0'+(i/10000)%10 );

string[3]=(char)('0'+(i/1000)%10 );

string[4]=(char)('0'+(i/100)%10 );

string[5]=(char)('0'+(i/10)%10 );

string[6]=(char)('0'+(i/1)%10 );

string[7]='-';

string[8]='-';

string[9]='-';

string[WORDSINLINE-2]='\r';

string[WORDSINLINE-1]='\n';

fwrite(string,sizeof(char),WORDSINLINE,pBigFile1);

}

for (i=0; i<NUMOFLINES; i++)

{

for (int j=10; j<WORDSINLINE-2; j++)//从第11个字节开始随机赋值

{

randNum = rand()%25;//随机产生0-25之间的数字

randChar = (char)(basicChar+randNum);

string[j]=randChar;

}

string[0]= ToChar(2);

string[1]=(char)('0'+(i/100000)%10 );

string[2]=(char)('0'+(i/10000)%10 );

string[3]=(char)('0'+(i/1000)%10 );

string[4]=(char)('0'+(i/100)%10 );

string[5]=(char)('0'+(i/10)%10 );

string[6]=(char)('0'+(i/1)%10 );

string[7]='-';

string[8]='-';

string[9]='-';





string[WORDSINLINE-2]='\r';

string[WORDSINLINE-1]='\n';

fwrite(string,sizeof(char),WORDSINLINE,pBigFile2);

}

clock_t time2 = clock();

clock_t take = time2-time1;

printf("%s--生成两个%d行的文件花费时间为: %d(毫秒)\n",MOSHI,NUMOFLINES,take);

/*

经验与总结:写文件的操作在Debug和Release下相差不大。

*/

fclose(pBigFile1);

fclose(pBigFile2);

pBigFile1 = NULL;

pBigFile2 = NULL;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: