day7 电子词典文件的导入

该程序打开并读取名为dict.txt的单词文件,将单词及其解释逐条插入到名为word.db的SQLite3数据库中的worddata表。如果数据库不存在,程序会先创建它,然后创建表结构。导入完成后,数据库关闭。
摘要由CSDN通过智能技术生成

代码:

#include<stdio.h>
#include<sqlite3.h>
#include<stdlib.h>
#include<string.h>

//将单词导入到数据库
int sqlite3_word(sqlite3* db)
{
    char sql[128]="";
    char *errmsg=NULL;
    
    //打开单词文件
    FILE *fd =fopen("./dict.txt","r");
    if(NULL==fd)
    {
        perror("fopen");
        return -1;
    }
    printf("词典导入中请稍后..\n");

    char buf[512]="",word[128]="",explain[128]="";

    //循环读取文件的每一行内容
    while(1)
    {
        bzero(word,sizeof(word));
        bzero(explain,sizeof(explain));

        if(fgets(buf,sizeof(buf),fd)==NULL)
        {
            printf("词典导入完毕\n");
            return -1;
        }
        buf[strlen(buf)-1]=0;

        //将单词和解释分开
        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(explain,(buf+i+2));
                break;
            }
        }

        //插入数据库
        sprintf(sql,"insert into worddata values(\"%s\",\"%s\");",word,explain);

        if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
        {
            fprintf(stderr,"__%d__sqlite3_exec:%s\n",__LINE__,errmsg);
            return -1;
        }
    }
    fclose(fd);
}
int main(int argc,const char *argv[])
{
    //如果数据库不存在,则创建后打开
    //如果存在则直接打开
    sqlite3* db=NULL;
    if(sqlite3_open("./word.db",&db)!=SQLITE_OK)
    {
        fprintf(stderr,"sqlite3_open: %s errorde:%d\n",sqlite3_errmsg(db),sqlite3_errcode(db));
        return -1;
    }
    printf("sqlite3_open success\n");

    //创建一个表
    //注意:C代码中编写的sql语句与在数据库中编写的一致
    
    char sql[128]="create table if not exists worddata (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("create table worddata success\n");

    //将单词导入数据库
    sqlite3_word(db);

    //关闭数据库
    if(sqlite3_close(db)!=SQLITE_OK)
    {
        fprintf(stderr,"sqlite3_open: %s errorde:%d\n",sqlite3_errmsg(db),sqlite3_errcode(db));
        return -1;
    }
    return 0;
}

运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值