赞
踩
#include <stdio.h>
#include <sqlite3.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//打开数据库
sqlite3 *db = NULL;
if(sqlite3_open("./dict.db",&db) != SQLITE_OK){
printf("sqlite3_open error: %s __%d__",sqlite3_errmsg(db),__LINE__);
return -1;
}
printf("create 数据库ok __%d__\n",__LINE__);
//创建表格
char sql[128] = "create table if not exists dict (word char,mean char);";
char* errmsg = NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK){
printf("sqlite3_exec error: %s __%d__\n",errmsg,__LINE__);
return -1;
}
printf("createe sql ok __%d__\n",__LINE__);
FILE* fp = fopen("./dict.txt","r");
if(NULL == fp){
perror("fopen");
return -1;
}
//读取dict.txt数据
char buf[256] = ""; //存数据
char word[32] = ""; //单词
char mean[200] = ""; //意思
while(1){
if(fgets(buf,sizeof(buf),fp) == NULL)
break; //从.txt中拿数据
buf[strlen(buf)-1] = 0;
bzero(word,sizeof(word));
bzero(mean,sizeof(mean)); //清零
//分离单词和意思
for(int i=0;i<strlen(buf)-2;i++){
//分离单词
if(buf[i] != ' ' && buf[i+1] == ' ' && buf[i+2] == ' '){
strncpy(word,buf,i+1); //判断当前位置不是空格,下个位置是空格 以及下下个位置是空格
}
else if(buf[i] == ' ' && buf[i+1] == ' ' && buf[i+2] != ' '){
strcpy(mean,buf+i+2);
break;
}
}
printf("获取数据成功 __%d__\n" ,__LINE__);
//插入数据库
sprintf(sql,"insert into dict values(\"%s\", \"%s\");",word,mean);
printf("spl=%s\n",sql);
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK){
printf("sqlite3_exec error: %s __%d__",errmsg,__LINE__);
return -1;
}
}
//关闭文件
fclose(fp);
//关闭数据库
sqlite3_close(db);
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。