代码:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sqlite3.h>
int main(int argc, const char *argv[])
{
//创建并打开一个数据库
sqlite3 *db=NULL;
if(sqlite3_open("./word.db",&db)!=SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_open failed:%d:%s\n",\
__LINE__,sqlite3_errcode(db),sqlite3_errmsg(db));
return-1;
}
printf("sqlite3_open success\n");
//创建一张表格,数据库中sql怎么写就怎么写
char sql[128]="create table if not exists word(word char,explain char);";
char *errmsg=NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,errmsg);
return-1;
}
printf("table stu create success\n");
//打开一个文件
FILE *fd=fopen("./dict.txt","r");
if(NULL==fd)
{
perror("fopen");
return -1;
}
printf("open success\n");
//指定的文件中格式化获取数据
//存储每一行数据
char buf[512]="";
char get_word[128]="";
char get_explain[128]="";
//循环读取每一行内容
while(1)
{
bzero(get_word,sizeof(get_word));
bzero(get_explain,sizeof(get_explain));
if(fgets(buf,sizeof(buf),fd)==NULL)
{
printf("读取完毕\n");
return -1;
}
buf[strlen(buf)-1]='\0';
for(int i=0;i<buf[i+2] ;i++)
{
if(buf[i]!=' ' && buf[i+1]==' ' && buf[i+2]==' ')
{
strncpy(get_word,buf,i+1);
}
else if(buf[i]==' ' && buf[i+1]==' ' && buf[i+2]!=' ')
{
strcpy(get_explain,buf+i+2);
break;
}
}
bzero(sql,sizeof(sql));
sprintf(sql,"insert into word values(\"%s\",\"%s\");",get_word,get_explain);
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,errmsg);
return-1;
}
}
//关闭数据库
if(sqlite3_close(db)!=SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_close failed:%d:%s\n",\
__LINE__,sqlite3_errcode(db),sqlite3_errmsg(db));
return-1;
}
//关闭文件描述符
fclose(fd);
return 0;
}
结果如下:
一共7987个四级单词