1. 将dict.txt的内容导入到数据库中
#include<stdio.h>
#include<sqlite3.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
int main(int argc, const char *argv[])
{
sqlite3 *db=NULL;
if(sqlite3_open("./dict.db",&db)!=SQLITE_OK)
{
printf("err_code:%d\n",sqlite3_errcode(db));
printf("err_msg:%s\n",sqlite3_errmsg(db));
fprintf(stderr,"__%d__sqlite3_open failed\n",__LINE__);
return -1;
}
printf("sqlite3_open success\n");
//执行sql语句
char *sql="create table if not exists dict (word char ,translate char);";
char *errmsg=NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
return -1;
}
printf("sqlite3_exce success\n");
char word[50]=""; //存储单词
char translate[50]; //存储翻译
char temp[50]; //存储临时的文字段
//已读的方式打开文件
FILE *fp=fopen("./dict.txt","r");
if(fp==NULL)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("fopen");
return -1;
}
int res=0; //为EOF(即-1)时结束
while(1)
{
int sflag=0;
bzero(word,sizeof(word));
bzero(translate,sizeof(translate));
while(1)
{
bzero(temp,sizeof(temp));
//读取有效文字段
res=fscanf(fp,"%s",temp);
if(res==-1) //判断fscanf是否出错,以及文件是否读完;
{
if(errno==0)
{
fclose(fp);
printf("字典传输完成\n");
return 0;
}
else
{
fprintf(stderr,"line:%d ",__LINE__);
perror("fscanf");
}
}
int len=strlen(temp);
//判断单词是否到翻译了
if(sflag==0)
{
for(int i=0;i<len;i++)
{
if(temp[i]=='.')
{
sflag=1;
break;
}
}
}
//写入不同的字符串(单词和翻译)
if(sflag==0)
{
strcat(word,temp);
strcat(word," ");
}
else if(sflag==1)
{
strcat(translate,temp);
strcat(translate," ");
}
char x;
while(1)
{
x=fgetc(fp);
if(x==' '||x==10)
break;
}
if(x==10)
break;
}
//执行sql语句
char sql[128];
sprintf(sql,"insert into dict values (\"%s\",\"%s\");",word,translate);
char *errmsg=NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
return -1;
}
//printf("sqlite3_insert success\n");
}
//关闭文件
fclose(fp);
return 0;
}
效果运行图;