网络编程作业(0817-林雪阵)

将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;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林某某..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值