将dict.txt的内容导入到数据库中
#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//创建库
sqlite3 * seq_create()
{
sqlite3 *db=NULL;
if(sqlite3_open("./dict.db",&db) != SQLITE_OK)
{
printf("errno=%d\n",sqlite3_errcode(db));
printf("err_msg=%s\n",sqlite3_errmsg(db));
printf("__%d__ seqlite open fail\n",__LINE__);
return NULL;
}
printf("sqlite3_open success\n");
//创建一个表格
char sql[128] = "create table if not exists stu (word char,mean char);";
char * errmsg=NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!= SQLITE_OK)
{
printf("__%d__ sqlite3__exec %s\n",__LINE__,errmsg);
}
return db;
}
//插入数据
int insert_seq(sqlite3 *db,char *word,char *mean,int i)
{
char sql[128] = "";
sprintf(sql,"insert into stu values (\"%s\",'%s');",word,mean);
char * errmsg=NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!= SQLITE_OK)
{
printf("%d __%d__ sqlite3__exec %s\n",i,__LINE__,errmsg);
}
}
int main(int argc, const char *argv[])
{
//创建库
sqlite3 *db=seq_create();
//打开文件
int fd_r=open("./dict.txt",O_RDONLY);
if(fd_r<0)
{
perror("open");
return -1;
}
//循环读取文件
char c;
ssize_t res=0;
char temp[128]="";
char word[128]="";
char mean[128]="";
int i=0;
char *p;
int aa=1;
while(1)
{
res=read(fd_r,&c,1);
if(res<0)
{
perror("read");
return -1;
}else if(0==res)
{
printf("导入完成\n");
break;
}
//printf("%c",c);
//将读取到的信息写入temp,直到'\n'
if(c!='\n')
{
temp[i]=c;
i++;
}else
{
temp[i]='\0';
//定义一个指针
char *p=temp;
while(*p!='\0')
{
if(*p==' ' && *(p+1)==' ')
{
*p='\0';
break;
}
p++;
}
p++;
while(*p==' ')
{
p++;
}
sprintf(word,"%s",temp);
sprintf(mean,"%s",p);
insert_seq(db,word,mean,aa++);
bzero(temp,sizeof(temp));
bzero(word,sizeof(word));
bzero(mean,sizeof(mean));
i=0;
//break;
}
}
return 0;
}
