4月14日作业

该程序打开或创建一个名为my.db的SQLite3数据库,创建一个名为cihui的表,然后从dict.txt文件中读取单词和它们的释义,将数据插入到表中。如果遇到空格分隔的多个单词,会将它们合并为一个条目。最后,程序关闭数据库连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
    //如果数据库不存在则创建后打开
    //如果存在则直接打开
    sqlite3* db=NULL;
    if(sqlite3_open("./my.db",&db)!=0)
    {
        fprintf(stderr,"errcode:%d sqlite3_open:%s\n",sqlite3_errcode(db),sqlite3_errmsg(db));
        return -1;
    }
    printf("sqlite3_open successs\n");
    
    //创建一个表
    //注意:c代码中的sql语句与在数据库中编写的一致
    char sql[128]="create table if not exists cihui (单词 char,意思 char);";
    char* errmsg=NULL;
    if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=0)
    {
        fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,errmsg);
        return -1;
    }
    printf("create table stu successs\n");
    //打开单词表
    FILE* fd=fopen("./dict.txt","r");
    char buf[32]="";
    char buf1[32]="";
    char buf2[32]="";
    char c[3]="";
    while(1)
    {
        bzero(buf,sizeof(buf));
        bzero(buf1,sizeof(buf1));
        bzero(c,sizeof(c));
        fscanf(fd,"%s",buf);//获取每一行第一个单词
        if(buf[0]=='\0') //读到结尾退出
            break;

        fgets(c,3,fd);//读取后面2个字符
        if(strcmp(c,"  ")!=0) //如果其中有不为空格的
        {
            while(1)
            {
                bzero(buf2,sizeof(buf2));
                fseek(fd,-1,SEEK_CUR);  //向前偏移一个单位
                fscanf(fd,"%s",buf2);   //获取第二个单词
                strcat(buf," ");
                strcat(buf,buf2);         //拼接2个单词为一个单词
                fgets(c,3,fd);            //继续读取后面2个字符
                if(strcmp(c,"  ")==0)    //如果后面2个字符都为空格则退出循环
                    break;

            }

        }
            fseek(fd,1,SEEK_CUR);   //向后偏移一个单位
            fgets(buf1,32,fd); //获取单词的意思
            buf1[strlen(buf1)-1]='\0';
            char sql[128]="insert into cihui values (\""; //sql语句
            strcat(sql,buf);
            strcat(sql,"\",\"");
            strcat(sql,buf1);
            strcat(sql,"\");");    //拼接sql语句
            char* errmsg1=NULL;
            fprintf(stderr,"%s\n",sql);
            if(sqlite3_exec(db,sql,NULL,NULL,&errmsg1)!=0)   //执行sql语句
            {
                fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,errmsg1);
                return -1;
            }

    }
    fclose(fd);

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值