1 #include <stdio.h>
2 #include <sqlite3.h>
3 #include <string.h>
4 int main(int argc, const char *argv[])
5 {
6 //创建数据库
7 sqlite3 *db = NULL;
8 if(sqlite3_open("./dict.db", &db) != SQLITE_OK)
9 {
10 printf("sqlite3_open failed:%s __%d__\n", sqlite3_errmsg(db), __LINE__);
11 return -1;
12 }
13 //创建表格
14 char sql[546] = "create table if not exists dict (word char, mean char);";
15 char* errmsg = NULL;
16 if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
17 {
18 printf("sqlite3_exec failed:%s __%d__\n", errmsg, __LINE__);
19 return -1;
20 }
21 //打开文件
22 FILE* fp = fopen("./dict.txt", "r");
23 if(NULL == fp)
24 {
25 perror("fopen");
26 return -1;
27 }
28 char buf[255] = "";
29 char word[128] = ""; //存放单词
30 char mean[128] = "";//存放单词意思
31 int i;
32 while(1)
33 {
34 if(fgets(buf, sizeof(buf), fp) == NULL)
35 break;
36 buf[strlen(buf)-1] = 0;
37 //分离单词和意思
38 bzero(word, sizeof(word));
39 bzero(mean, sizeof(mean));
40 for(i=0; i<strlen(buf)-2; i++)
41 {
42 //判断当前位置不是空格,下一个位置以及下下个位置是空格
43 if(buf[i] != ' ' && buf[i+1] == ' ' && buf[i+2]==' ')
44 {
45 strncpy(word, buf, i+1);
46 }
47 //判断当前位置以及下一个位置是空格,下下个位置不是空格
48 else if(buf[i]==' ' && buf[i+1]==' ' && buf[i+2]!=' ')
49 {
50 strcpy(mean, buf+i+2);
51 break;
52 }
53 }
54 //插入数据
55 sprintf(sql,"insert into dict values(\"%s\", \"%s\");", word, mean);
56
57 if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
58 {
59 printf("sqlite3_exec failed:%s __%d__\n", errmsg, __LINE__);
60 return -1;
61 }
62 }
63
64 //关闭文件
65 fclose(fp);
66 //关闭数据库
67 if(sqlite3_close(db) != SQLITE_OK)
68 {
69 printf("sqlite3_close failed:%s __%d__\n", sqlite3_errmsg(db), __LINE__);
70 return -1;
71 }
72 printf("slqite3 sq.db close success\n");
73
74 return 0;
75 }
结果: