文件读写

最近在做一个大数据模拟器的功能,数据达到上亿级别,但频繁插入SQL导致效率过低。优化MySQL的插入和查询效率,把for循环中的插入修改为一行进行插入多个记录可以大幅度优化速度。

Linux 查看文件大小

  • stat filepath
  • wc -c filename,得到字节数
  • du -b filepath 参数-b表示以字节计数;du -h filepath 直接得出人好识别的文件大小
  • ls -l filepath 第五列为文件字节数;ls -h filepath  -h参数得到人好读的文件大小

查询MySQL当前支持最大的字节数

show VARIABLES like '%max_allowed_packet%';

读写文件实例

/*  Copyright (C) 2019 * Ltd. All rights reserved.
 *      Create date : 2019-05-21 16:13:24
 *================================================*/

#include <stdio.h>
#include <string.h>
#include <time.h>

#define LENGTH 4*1024*1024

int STRTOK()
{
    //生成口令用户
    FILE *file;
    char line[300];
    char *p;
    int flag;
    int n1[10];
    file = popen("head -2 policy.csv | tail -1", "r");
    if (NULL != file)
    {
        while (fgets(line, 300, file) != NULL)
        {
           p=strtok((char *)line,",");
           printf("p = %s
", p);
           int h = 0;
           for(; h<1; ++h)
           {
               p = strtok(NULL, ",");
               n1[h] = atoi(p);
               printf("n1[%d]:%d
", h, n1[h]);
           }
           flag=atoi(p);
           printf("flag = %d
", flag);
        }
    }
    pclose(file);
    return 0;
}

int mysqlBat()
{
    FILE *fp = NULL;
    fp = fopen("./mysql.txt", "w");
    char line[LENGTH] = {0};
    char str[32] = "values('%s',%d,%d)";
    char m_str[32] = ", values('%s',%d,%d)";
   // snprintf(line, sizeof(LENGTH), "%s", m_str);
    strcat(line, str);
    printf("strlen(line) = %d
", strlen(line));
    int i;
    for(i=1;i<1000;i++)
    {
        printf("m_str= %s
", m_str);
        strcat(line, m_str);
        //snprintf(line+strlen(line), sizeof(LENGTH)-strlen(line), ", %s",  m_str);
    }
    printf("line = %s
", line);
    fprintf(fp, "%s", line);
    fclose(fp);
    return 0;
}

int main(int argc, char *argv[])
{
    mysqlBat();
    return 0;
}
View Code
作者:yusq77

-------------------------------------------

Wish you all the best and good health in 2021.

原文地址:https://www.cnblogs.com/yusq77/p/10919624.html