C 实现读取txt文件 批量生成SQL语句

txt 文本内容:

/*data.txt*/

1 2 3
2 3 3
3 4 4
4 5 4

希望生成的语句:

--data_out.sql

INSERT INTO XXX VALUES('1','2','3');
INSERT INTO XXX VALUES('2','3','3');
INSERT INTO XXX VALUES('3','4','4');
INSERT INTO XXX VALUES('4','5','4');

代码:

含有的变量什么的,可以根据自己的需求改改就行。

#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
char ln[MAXLEN];
FILE *f,*fout;
int n,L;
char d1[30],d2[30],d3[30];
int main() {
    f=fopen("data.txt","r");
    fout=fopen("data_out.sql","w");
    if (NULL==f) {
        printf("Can not open file!\n");
        return 2;
    }
    n=0;
    while (1) {
        if (NULL==fgets(ln,MAXLEN,f)) break;
        L=strlen(ln);
        if ('\n'==ln[L-1]) {
            n++;
            if (3!=sscanf(ln,"%s%s%s",d1,d2,d3)) {
                printf("line %d:[%s] can not read 3 double numbers!\n",n,ln);
                break;
            } else {
                //use d1,d2,d3 of line n
                //fprintf(fout,"SELECT * from XXX where XX='%s' and XX='%s' and '%s' order by XX\n",d1,d2,d3);
                fprintf(fout,"INSERT INTO XXX VALUES('%s','%s','%s');\n",d1,d2,d3); 
            }
        }
    }
    fclose(f);
    fclose(fout);
    return 0;
}
发布了108 篇原创文章 · 获赞 48 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/larry1648637120/article/details/102573103