C Small Project--Electronic Dictionary

Source: Internet
Author: User
Tags fread rewind strcmp strtok

C Language Project--look up the dictionary


Purpose: The study of technology is limited, the spirit of sharing is unlimited.


"Project Requirements description"

First, the word query

Given the text file "Dict.txt", the file is used to store the thesaurus. Thesaurus for "English-Chinese", "Chinese-English" bilingual dictionary, each word and its interpretation of the format fixed, as follows:

#单词

Trans: Explain 1@ explain 2@ ... Explain n

Each new word starts with "#" and is separated by an "@" explanation. A word may have multiple interpretations, all of which are stored in a row, and the beginning of the line is fixed with "Trans:". The following is a typical example:

#abyssinian

Trans:a. Abyssinia's @n. a Abyssinia person; Isobians.

The term has two explanations, one is "a. Abyssinia" and the other is "N. Abyssinia person; Isobia person".

Requires the writer to read the Word library file into memory, accept the words entered by the user, look up the word in the dictionary, and output the interpretation to the screen. Users can enter them repeatedly until the user enters the "exit" dictionary program to exit.

The program execution format looks like this:

./app–text

-text means using a text thesaurus for Word lookup.

second, indexing, and using the index for Word query

A binary index is required to format the index as shown in the following figure. Converts the text file "Dict.txt" file to the index file "Dict.dat" shown in the previous illustration, using the index file to implement Word lookup. Program execution format is as follows:

./app–index

-index represents the use of text thesaurus Dict.txt to establish a binary index thesaurus Dict.dat

./app–bin

-bin represents the use of binary indexed thesaurus for Word lookup.

//============================================================================================================= ===

A, text file word query

1. Word Structure:

#单词

Trans: Explain 1@ explain 2@ ... Explain n

In the Dict.txt file, the word occupies a row, begins with "#", and the explanation begins with "Trans:" and the content is delimited by "@". Structure I use linked list. The specific structure is defined as follows:

Word list----The name of the word, the number of translations, the result of the word translation

typedef struct DICT

{

Char Word[target_word_max_size]; The word to enter, such as "#superstar"

uint8_t Mean_count; The number of words that can be interpreted as nouns or verbs,

Char Trans[target_word_meaning_count][target_word_max_translation]; Translation results, separated by @ (strtok split function)

struct Dict *next;

} word_t, *dict_t;

2. Interface definition

2.1, the total number of words in the file: to establish a single linked list, you need to know the length of a single linked list, so, to know the total number of words in the file, define the following interface:

uint32_t ListCount (FILE *FP); The number of words in the dictionary, that is, to create the length of the linked list

2.2, create a single linked list: from a document to read a word and its interpretation, filled into the word structure, creating a single linked list is the process of allocating memory and connecting nodes, define the interface as follows (count is the total number of words):

dict_t CreateList (dict_t head, FILE *FP, uint32_t count); Create a single linked list and return to the first node. Allocates memory.

2.3, look for words: From the list match to find the word, found on the output word interpretation, define the interface as follows:

void SearchList (dict_t head, uint32_t count); Find the word you entered

2.4, free Memory: Create a linked list of memory allocated at the end of the release, the definition interface is as follows:

void Destroylist (dict_t head); Free memory


ii. Establishment of index file Dict.data

1. Index structure

As shown in the figure above, contains the following: Index header word number (4 bytes), Word 1 word Length (4 bytes), Word 1 (word length byte), Word 1 Interpretation number (4 bytes), explain 1 length (4 bytes), explain 1 content (explain 1 length), explain 2 Length (4 bytes), Explain the content of 2 (explain the length of 2) ... In this format, the contents of the Dict.txt file are written to the Dict.dat index file. Structure is the same as the structure of the text query above.

2. Interface definition

The nodes in the list are written to the index file Dict.dat in the above format, written with the Fwrite function, and the interface is defined as follows:

Chain Header node Head, file name, chain table length

void Writeindexfile (dict_t head, const char *filename, uint32_t count);


Third, index file lookup word

The index file is established, and the contents of the text file are written to the index file in the format of the protocol, the word is read out from the index file to find the word, read by the Fread function, the interface is defined as follows:

void Readindexfile (dict_t head, const char *filename, uint32_t *count);


Specific implementation:

#ifndef _target_h_ #define _target_h_ #include <stdlib.h> #include <stdio.h> #include <string.h> typed
EF unsigned char uint8_t;

typedef unsigned int uint32_t; #define TARGET_TEXT_NAME "./dict.txt" #define Target_index_name "./dict.dat" #define Target_word_max_          SIZE #define TARGET_WORD_MEANING_COUNT #define TARGET_WORD_MAX_TRANSLATION #define Target_word_buffer 1024//Word list----Word name, there are several translations of words, Word translation results typedef struct DICT {char word[target_word_max_size];//words to enter, such as "#supe  Rstar "uint8_t Mean_count; The number of words explained, such as can do nouns can also do verbs, with the @ separate char trans[target_word_meaning_count][target_word_max_translation];
Translation results struct dict *next;


} word_t, *dict_t; uint32_t ListCount (FILE *FP); The number of words in the dictionary is to create the length of the list dict_t createlist (dict_t head, FILE *FP, uint32_t count); Create a single linked list and return to the first node.
Allocates memory. void SearchList (dict_t head, uint32_t count); Find the entered word void Destroylist (dict_t head); Free memory void Writeindexfile (dict_t head, const char *filename, uint32_t count);

void Readindexfile (dict_t head, const char *filename, uint32_t *count); void Process (int argc, char **argv);
 Main process, main function call interface #endif/* _target_h_/*

Main.c

#include "target.h"

int 
main (int argc, char **argv)
{
  if (argc < 2)
  {
    fprintf (stderr, " Input params is too few!\n ");
  
    return 1;
  }

  Process (argc, argv);

  return 0;
}

PROCESS.C:

#include "target.h"

static const char PARAMS[][15] = {"-text", "-index", "-bin", "-test1-f", "-test2-f"};

void
Process (int argc, char **argv)
{
  FILE *fp;
  dict_t head;
  uint32_t count;

  if (fp = fopen (Target_text_name, "r") = = NULL)
  {
    fprintf (stderr, "Open file failure!\n");
    Exit (1);
  }
  Count = ListCount (FP);

  printf ("Count:%d\n", count);
  printf ("Open sucess!\n");

  if ((strcmp (argv[1], params[0]) = = 0)
  {head
    = createlist (head, FP, count);
    SearchList (head, count);
    Fclose (FP);
    Destroylist (head);

  if ((strcmp (argv[1], params[1]) = = 0)
  {head
    = createlist (head, FP, count);
    Fclose (FP);
    Writeindexfile (Head, Target_index_name, count);
    Destroylist (head);

  if (strcmp (argv[1], params[2]) = = 0)
  {head
    = createlist (head, FP, count);
    Readindexfile (Head, Target_index_name, &count);
    SearchList (head, count);
    Fclose (FP);
    Destroylist (head);
  }


Find_word_from_text.c

#include "target.h" static char file_exist;
  The number of uint32_t ListCount (FILE *fp)//Word is the length of the linked list {uint32_t count = 0;

  Char buffer[100];
    while (fgets (buffer, sizeof (buffer), FP)) {if (' # ' = = Buffer[0]) {++count; } rewind (FP);
This step must be done so that the file pointer points to the header return count;
  } dict_t createlist (dict_t head, FILE *FP, uint32_t count)//Create a linked list, return header node {dict_t new, pointer;
  Char Buf[target_word_buffer];
  uint8_t word_size, trans_size, Mean_count = 1, *str;

  uint32_t I, j = 0;  Head = (dict_t) malloc (sizeof (word_t));
    Allocate node space if (NULL = head) {fprintf (stderr, "malloc failure!\n");
  Exit (1);

  printf ("Head success!\n");
    if (Count > 0) {memset (buf, 0, sizeof (BUF));
    Fgets (buf, sizeof (BUF), FP);
    Word_size = strlen (BUF);
    Buf[word_size-1] = ' the ';

    strcpy (Head->word, buf);
    memset (buf, 0, sizeof (BUF));
    Fgets (buf, sizeof (BUF), FP);
    Trans_size = strlen (BUF);

    Buf[trans_size-1] = ' the '; str = strtok (buf, "@");

    strcpy (head->trans[j++], str + 6);
      while (str = strtok (NULL, "@")) {strcpy (head->trans[j++], str);
    ++mean_count;

    } head->mean_count = Mean_count; Head->next = NULL;

    So far the first node is populated, and the next node of the first node is pointed to the null pointer = head;
      for (i = 0; i < count-1; ++i)//link back (count-1) to the first node after {mean_count = 1; New = (dict_t) malloc (sizeof (word_t));
      Allocate node space memset (buf, 0, sizeof (BUF));
      Fgets (buf, sizeof (BUF), FP);
      Word_size = strlen (BUF);
      Buf[word_size-1] = ' the ';

      strcpy (New->word, buf);
      memset (buf, 0, sizeof (BUF));
      Fgets (buf, sizeof (BUF), FP);
      Trans_size = strlen (BUF);
      Buf[trans_size-1] = ' the ';
      for (j = 0; J < count;)
        {str = strtok (buf, "@");

        strcpy (new->trans[j++], str + 6);
          while (str = strtok (NULL, "@")) {strcpy (new->trans[j++], str);
        ++mean_count; }} New->mean_count =Mean_count;

      New->next = NULL;
      Pointer->next = new;
    pointer = new;

  } rewind (FP);
return head;
  } void Printlist (dict_t head) {dict_t pointer;

  pointer = head; while (pointer!= NULL) {printf ("Pointer->word =%s, Pointer->mean_count =%d\n", Pointer->word, POINTER-&G
    T;mean_count);
  pointer = pointer->next;
  } void SearchList (dict_t head, uint32_t count)//looks up the word {dict_t pointer from the list;
  Char Str[target_word_max_size];

  uint32_t i;
    while (1) {file_exist = 0;
    pointer = head;
    printf ("Please input a word:");
    Fgets (str, target_word_max_size, stdin);

    Str[strlen (str)-1] = ';
    if (strcmp (str, "exit") = = 0) {exit (1); (pointer!= NULL) {if (strcmp (Pointer->word, str) = = 0) {for (i = 0; i < point er->mean_count;
          ++i) {file_exist = 1;
        fprintf (stdout, "trans%d:%s\n", i + 1, pointer->trans[i]);
  }      Break
    } pointer = pointer->next; } if (file_exist = = 0) {
    This determines that the word does not exist, you can choose to add, you can choose to exit;
      //printf ("No find!\n");
      printf ("Do your want to add a new word?:( y/n) \ n ");
      scanf ("%c", &new_word);
      if (New_word = = ' Y ' | | | new_word = = ' Y ')
      {
        addwordtotext (head, Target_custom_text);
      } *
      /exit (1)
    ;

}}} void
destroylist (dict_t head) 
{
  dict_t pointer;

  while (pointer!= NULL)
  {
    pointer = head;
    Head = head->next;

    free (pointer);
  }


Find_word_from_index.c

#include "target.h" void Writeindexfile (dict_t head, const char *filename, uint32_t count)//indexed, written to file in the protocol format {files *st
  Ream;
  uint32_t I, Word_size, Trans_size, Mean_count;
  Uint8_t J;

  dict_t pointer = head;
    if (stream = fopen (filename, "wb") = = NULL) {fprintf (stderr, "Cannot open output file.\n");
  Exit (1);

  } fwrite (&count, 4, 1, stream);
    while (pointer!= NULL) {word_size = strlen (Pointer->word);

    Mean_count = pointer->mean_count;
    Fwrite (&word_size, 4, 1, stream);
    Fwrite (Pointer->word, 1, word_size, stream);

    Fwrite (&mean_count, 4, 1, stream);
      for (j = 0; j < Mean_count; ++j) {trans_size = strlen (pointer->trans[j));
      Fwrite (&trans_size, 4, 1, stream);
    Fwrite (Pointer->trans[j], 1, trans_size, stream);
  } pointer = pointer->next;
} fclose (stream);
  } void Readindexfile (dict_t head, const char *filename, uint32_t *count)//Read the word contents from the file {file *stream; Uint8_t i;
  uint32_t word_size, Trans_size, Mean_count;

  dict_t pointer = head;

  printf ("enter...\n");
    if (stream = fopen (filename, "rb") = = NULL) {fprintf (stderr, "Cannot open output file.\n");
  Exit (1);
  //printf ("Read file success!... \ n");
  Fread (Count, 4, 1, stream);
  printf ("Count =%d\n", *count);
   while (pointer!= NULL) {fread (&word_size, 4, 1, stream);

    printf ("word_size =%d\n", word_size);
    Fread (Pointer->word, 1, word_size, stream);
    Pointer->word[word_size] = ' the ';

    Fread (&pointer->mean_count, 4, 1, stream);
    printf ("Pointer->word =%s\n", Pointer->word);
    printf ("Pointer->mean_count =%d\n", pointer->mean_count);
      for (i = 0; i < pointer->mean_count; ++i) {memset (Pointer->trans[i], 0, sizeof (pointer->trans[i)));
      Fread (&trans_size, 4, 1, stream);
      Fread (Pointer->trans[i], 1, trans_size, stream);
      Pointer->trans[i][trans_size] = ' the '; PriNTF ("trans_size =%d\n", trans_size);
    printf ("Pointer->trans =%s\n", pointer->trans[i]);
  } pointer = pointer->next;

  }//fclose (stream);
printf ("Read over!\n");
 }

Compile the executable app with GCC, then execute the text query, index build and index query separately.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.