此段代码的作用是替换掉user_playerinfo.csv文件中的电话号码为模拟生成的新号码,原以为使用C代码来实现速度会非常快,实际测试效果并不太理想,先把这些辛苦写出的源码收藏起来吧,等之后水平提高一些了再来看这个问题,是否有更好的写法。
user_playerinfo.csv的文件内容格式:
xxx,xxxxxx,xxx,xxxx,xxxx,xxxx,xx,xxx,xxx,x,xx,xx,x
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
long phone_num_fun(int argc);
int main(int argc, char** argv) {
int fd = open("/root/tools/user_playerinfo.csv", O_RDWR);
if (fd < 0)
{
printf("open failed!\n");
return EXIT_FAILURE;
}
char str_buf = '\0';
int j = 0, catch = 0, count_columns = 0, line = 0, i = 0;
char new_phone_num[16] = { '\0' };
sprintf(new_phone_num, "%ld", phone_num_fun(line));
while ((read(fd, &str_buf, 1))) {
if (str_buf == '\n')
{
line++;
sprintf(new_phone_num, "%ld", phone_num_fun(line));
}
//判断是否为电话号码所在的位置
if (str_buf == ',') {
count_columns++;
}
if (catch == 0 && count_columns % 9 == 1) catch = 1;
if (str_buf >= '0' && str_buf <= '9' && count_columns % 9 == 1 && catch) {
printf("%c", new_phone_num[j++]);
}
else
{
if (count_columns % 9 == 4 && str_buf >= '0' && str_buf <= '9')
{
printf("%c", new_phone_num[i++]);
}
else
{
printf("%c", str_buf);
}
}
if (catch && count_columns % 9 == 1 && str_buf == ',') {
catch = 0;
j = 0;
i = 0;
}
}
close(fd);
return 0;
}
long phone_num_fun(int argc) {
long head[41] = { 134,135,136,137,138,139,147,150,151,152,157,158,159,182,183,184,187,188,178,133,149,153,173,177,180,181,189,199,130,131,132,145,155,156,166,171,175,176,185,186,166 };
long rand_num = 0;
long tail = 0;
unsigned long var = 0;
var = argc;
while (100000000 > rand_num) {
srand((unsigned)time(NULL) + var);
// sleep(1);
rand_num = rand();
}
rand_num %= 100000000;
while (rand_num < 10000000) rand_num *= 10;
// printf("%ld\n", (head[rand_num%40])*100000000);
// printf("%ld\n", rand_num);
tail = head[rand_num % 40] * 100000000 + rand_num;
// printf("%ld\n", tail);
return tail;
}