将四级词典转换为数据库
代码段
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sqlite3.h> //sqlite3数据库的头文件
/*
程序要求:单词表转数据库
*/
int transition(sqlite3 *db); // 单词转数据库函数
int main(int argc, const char *argv[])
{
// 打开数据库
sqlite3 *db = NULL;
if (sqlite3_open("word.db", &db) != SQLITE_OK)
{
printf("数据库打开失败: %s %d\n", sqlite3_errmsg(db), sqlite3_errcode(db));
return -1;
}
printf("打开数据库成功\n");
// 创建表格
char buf[128] = "create table if not exists stu(English char,Chinese char);";
char *errmsg = NULL;
if (sqlite3_exec(db, buf, NULL, NULL, &errmsg) != SQLITE_OK)
{
printf("表格创建失败:%s\n", errmsg);
return -1;
}
printf("打开表格成功\n");
transition(db); // 单词转换
return 0;
}
int transition(sqlite3 *db) // 单词转数据库函数
{
FILE *fd = fopen("./dict.txt", "r");
if (NULL == fd)
{
perror("fopen:");
return -1;
}
char buf[256] = ""; // 用于sqlite3命令
char head[100] = ""; // 英文字段
char end[100] = ""; // 中文字段
char *p = NULL; // 用于获取每次分割完毕的字符串
char *errmsg = NULL;
int number = 0; // 当前行数计数器
while (fgets(buf, sizeof(buf), fd) != NULL)
{
/*分割文本,查找空格隔开的文本*/
p = strtok(buf, " ");
strcpy(head, p);
strcpy(end, ""); // 每次清空字符串
while (p != NULL)
{
p = strtok(NULL, " ");
if (NULL != p)
strcat(end, p);
}
*(end + strlen(end) - 1) = 0;
/*向表格写入数据*/
sprintf(buf, "insert into stu values (\"%s\",\"%s\");", head, end);
if (sqlite3_exec(db, buf, NULL, NULL, &errmsg) != SQLITE_OK)
{
printf("增加项失败:%s\n", errmsg);
fclose(fd); // 关闭单词文本
return -1;
}
system("clear");
printf("当前行数%d\n", ++number);
}
printf("转换完成\n");
fclose(fd); // 关闭单词文本
return 0;
}