C语言生成2000w行数据的两个实现

以下两个代码均在Linux下GCC测试通过

要求:

字符串长度为16
字符串只能包含大小写字母和数字
要求生成20000000行的TXT文本

/**********************************
* 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 <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(void)
{
    char array[]="QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
    char buff[170000];
    char *buff2 = buff;
    int file = open("test.txt", O_WRONLY|O_CREAT, S_IRWXU|S_IRGRP|S_IROTH);
    int i;
    int temp[4];
    char *p = (char *)temp;
    for(i = 0; i<20000000; i++)
    {
        temp[0] = rand();
        temp[1] = rand();
        temp[2] = rand();
        temp[3] = rand();

        buff2[0] = array[p[0]%(sizeof(array)-1)];
        buff2[1] = array[p[1]%(sizeof(array)-1)];
        buff2[2] = array[p[2]%(sizeof(array)-1)];
        buff2[3] = array[p[3]%(sizeof(array)-1)];

        buff2[4] = array[p[4]%(sizeof(array)-1)];
        buff2[5] = array[p[5]%(sizeof(array)-1)];
        buff2[6] = array[p[6]%(sizeof(array)-1)];
        buff2[7] = array[p[7]%(sizeof(array)-1)];

        buff2[8] = array[p[8]%(sizeof(array)-1)];
        buff2[9] = array[p[9]%(sizeof(array)-1)];
        buff2[10] = array[p[10]%(sizeof(array)-1)];
        buff2[11] = array[p[11]%(sizeof(array)-1)];

        buff2[12] = array[p[12]%(sizeof(array)-1)];
        buff2[13] = array[p[13]%(sizeof(array)-1)];
        buff2[14] = array[p[14]%(sizeof(array)-1)];
        buff2[15] = array[p[15]%(sizeof(array)-1)];

        buff2[16] = '\n';
        buff2 += 17;

        if(buff2 >= (buff+sizeof(buff)))
        {
            write(file, buff, sizeof(buff));
            buff2 = buff;
        }
    }
    close(file);
    return 0;
}

程序执行时间:

real 0m11.494s
user 0m7.860s
sys 0m0.296s

相关推荐