手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2014-01-09] 来源:Linux社区  作者:Linux [字体:大 中 小]

第二个:

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

生成文件:

 

linux
相关资讯       C语言 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款