8.17作业

 1. 将dict.txt的内容导入到数据库中

#include<stdio.h>
#include<sqlite3.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
int main(int argc, const char *argv[])
{
	sqlite3 *db=NULL;
	if(sqlite3_open("./dict.db",&db)!=SQLITE_OK)
	{
		printf("err_code:%d\n",sqlite3_errcode(db));
		printf("err_msg:%s\n",sqlite3_errmsg(db));
		fprintf(stderr,"__%d__sqlite3_open failed\n",__LINE__);
		return -1;
	}
	printf("sqlite3_open success\n");

	//执行sql语句
	char *sql="create table if not exists dict (word char ,translate char);";
	char *errmsg=NULL;

	if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
	{
		fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
		return -1;
	}
	printf("sqlite3_exce success\n");

	char word[50]="";     //存储单词
	char translate[50];    //存储翻译
	char temp[50];        //存储临时的文字段
	//已读的方式打开文件
	FILE *fp=fopen("./dict.txt","r");
	if(fp==NULL)
	{
		fprintf(stderr,"line:%d ",__LINE__);
		perror("fopen");
		return -1;
	}

	int res=0;          //为EOF(即-1)时结束
	while(1)
	{
		int sflag=0;
		bzero(word,sizeof(word));
		bzero(translate,sizeof(translate));

		while(1)
		{
			bzero(temp,sizeof(temp));
		
			//读取有效文字段
			res=fscanf(fp,"%s",temp);
			if(res==-1)      //判断fscanf是否出错,以及文件是否读完;
			{
				if(errno==0)
				{
					fclose(fp);
					printf("字典传输完成\n");
					return 0;
				}
				else
				{
					fprintf(stderr,"line:%d ",__LINE__);
					perror("fscanf");
				}
			}
			int len=strlen(temp);

			//判断单词是否到翻译了
			if(sflag==0)
			{
				for(int i=0;i<len;i++)
				{
					if(temp[i]=='.')
					{
						sflag=1;
						break;
					}
				}
			}

			//写入不同的字符串(单词和翻译)
			if(sflag==0)
			{
				strcat(word,temp);
				strcat(word," ");
			}
			else if(sflag==1)
			{
				strcat(translate,temp);
				strcat(translate," ");			
			}

			char x;
			while(1)
			{
				x=fgetc(fp);
				if(x==' '||x==10)
					break;
			}
			if(x==10)
				break;

		}


		//执行sql语句
		char sql[128];
		sprintf(sql,"insert into dict values (\"%s\",\"%s\");",word,translate);

		char *errmsg=NULL;

		if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
		{
			fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
			return -1;
		}
		//printf("sqlite3_insert success\n");

	}

	//关闭文件
	fclose(fp);
	return 0;
}

效果运行图;

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值