#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//定义choice,创建单词,显示单词,查找单词,添加单词,删除单词。利用Switch语句以及break跳出循环。//
int main() {
int choice,create_wordlist(),show_wordlist(),search_wordlist(),add_word(),delete_word();
while (1) {
printf("1. Create wordlist\n");
printf("2. Show wordlist\n");
printf("3. Search wordlist\n");
printf("4. Add word to wordlist\n");
printf("5. Delete word from wordlist\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
create_wordlist();
break;
case 2:
show_wordlist();
break;
case 3:
search_wordlist();
break;
case 4:
add_word();
break;
case 5:
delete_word();
break;
case 6:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
//创造单词,创造一个文件添加单词,用while(1)进行无线循环,break跳出循环结构//
int create_wordlist() {
FILE *fp;
char word[20], meaning[50];
fp = fopen("wordlist.txt", "w");
if (fp == NULL) {
printf("Failed to create wordlist file.\n");
exit(1);
}
while (1) {
printf("Enter a word (or 'q' to quit): ");
scanf("%s", word);
if (strcmp(word, "q") == 0) {
break;
}
printf("Enter the meaning of the word: ");
scanf("%s", meaning);
fprintf(fp, "%s\t%s\n", word, meaning);
}
fclose(fp);
}
//显示单词,从创建的文件中显示出单词,fgets用来读取文件中的字符串的函数,line数组是存储了要读取的字符串,100是最大字符数。//
int show_wordlist() {
FILE *fp;
char line[100];
fp = fopen("wordlist.txt", "r");
if (fp == NULL) {
printf("Failed to open wordlist file.\n");
exit(1);
}
while (fgets(line, 100, fp) != NULL) {
printf("%s", line);
}
fclose(fp);
}
//查找单词,从文件中数组读取字符串,然后利用strstr函数搜索查找字符串。//
int search_wordlist() {
FILE *fp;
char word[20], line[100];
fp = fopen("wordlist.txt", "r");
if (fp == NULL) {
printf("Failed to open wordlist file.\n");
exit(1);
}
printf("Enter a word to search: ");
scanf("%s", word);
while (fgets(line, 100, fp) != NULL) {
if (strstr(line, word) != NULL) {
printf("%s", line);
}
}
fclose(fp);
}
//添加单词,通过fprintf格式化输出到一个流文件中,//
int add_word() {
FILE *fp;
char word[20], meaning[50];
fp = fopen("wordlist.txt", "a");
if (fp == NULL) {
printf("Failed to open wordlist file.\n");
exit(1);
}
printf("Enter a word to add: ");
scanf("%s", word);
printf("Enter the meaning of the word: ");
scanf("%s", meaning);
fprintf(fp, "%s\t%s\n", word, meaning);
fclose(fp);
}
//删除单词,ftell函数用来读取指针位置,获取数据,strlen函数用来计算字符串line的长度,fseek用来重新设置文件内部指针位置便于删除已写入的单词//
//fwrite函数用来将缓存区的数据写入文件,fflush函数用来更新缓存区//
int delete_word() {
FILE *fp;
char word[20], line[100];
long pos;
int len;
fp = fopen("wordlist.txt", "r+");
if (fp == NULL) {
printf("Failed to open wordlist file.\n");
exit(1);
}
printf("Enter a word to delete: ");
scanf("%s", word);
while (fgets(line, 100, fp) != NULL) {
if (strstr(line, word) != NULL) {
pos = ftell(fp) - strlen(line);
len = strlen(line);
fseek(fp, pos, SEEK_SET);
fwrite(line + len, 1, strlen(line + len), fp);
fflush(fp);
break;
}
}
fclose(fp);
}
就是这个单词路径