第二个:
/**********************************
* Author: Ervin_Zhao(2012.6)
* Compile: gcc
* Create a file named test.txt, included 2000w line random string
* string have 16 num used A-Z, a-z, 0-9
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <time.h>
int main ( void )
{
int i, j;
const int cols = 16;
const int rows = 20000000;
const int size = ( cols + 1 ) * rows;
const char str[] = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
const char filename[] = "file.txt";
char * p = NULL;
char * pStart = NULL;
int fd;
p = pStart = (char *)malloc( size * sizeof(char) );
if ( p == NULL )
{
fprintf ( stderr, "内存申请失败。\n" );
return EXIT_FAILURE;
}
srand( time(NULL) );
for ( i = 0 ; i < rows; i ++ )
{
for ( j = 0 ; j < cols; j ++ )
{
*(p ++) = str[rand()%(62)];
}
*(p ++) = '\n';
}
fd = open( filename, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR );
if ( fd == -1 )
{
fprintf ( stderr, "文件打开错误。\n" );
return EXIT_FAILURE;
}
write ( fd, pStart, size );
free( pStart );
close(fd);
return EXIT_SUCCESS;
}
程序执行时间:
real 0m4.381s
user 0m3.108s
sys 0m0.336s
生成文件:

