代码:主要是需要将文件中的单词与翻译分开存储
#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//创建数据库
sqlite3 *sq = NULL;
if(sqlite3_open("my.dl",&sq) != SQLITE_OK)
{
fprintf(stderr,"err_msg[%d] : %s line:%d\n",\
sqlite3_errcode(sq),sqlite3_errmsg(sq),__LINE__);
return -1;
}
printf("数据库打开成功\n");
//创建表
char sql[300] = "create table if not exists dict (word char,chin char);";
char *errmsg = NULL;
if(sqlite3_exec(sq,sql,NULL,NULL,&errmsg) != SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_exec failed:%s\n",__LINE__,errmsg);
return -1;
}
printf("table create success\n");
FILE *fp = fopen("./dict.txt","r");
if(NULL == fp)
{
fprintf(stderr,"文件打开失败\n");
perror("fopen");
return -1;
}
char word[50] = "";
char chin[50] = "";
int i = 0,count = 0;
while(1)
{
bzero(word,sizeof(word));
bzero(chin,sizeof(chin));
bzero(sql,sizeof(sql));
if(fgets(sql,sizeof(sql),fp) == NULL)//读取一行内容
{
printf("读取结束\n");
return 0;
}
for(i = 0;i < strlen(sql);i++)
{
if(sql[i] == ' '&& sql[i+1] == ' ')
{
break;
}
word[i] = sql[i];//将第一个字符串给单词数组
}
for(;i < strlen(sql);i++)
{
if(sql[i] != ' ')
{
break;
}
}
for(int j = 0;j < strlen(sql);j++)
{
if(sql[i] == 0)
{
break;
}
chin[j] = sql[i];
i++;
}
chin[strlen(chin)-1] = 0;
count++;
printf("[%d]word = %s ; chinese = %s\n",count,word,chin);
bzero(sql,sizeof(sql));
sprintf(sql,"%s\"%s\"%s\"%s\"%s","insert into dict values (",word,",",chin,");");
if(sqlite3_exec(sq,sql,NULL,NULL,&errmsg) != SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_exec failed:%s\n",__LINE__,errmsg);
return -1;
}
}
//释放数据库
if(sqlite3_close(sq) != SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_close failed\n",__LINE__);
return -1;
}
return 0;
}
实现效果: