1

I created a Thesaurus program in C. In my program user can insert a word and the synonym for that. Another function is searching for a word and then displays the synonyms for that word.

My question is how can I keep the words I have inserted and still retrieve them when I run the program again? Is file handling a solution? How will I do it?

tshepang
  • 12,111
  • 21
  • 91
  • 136
moondrums
  • 21
  • 3

2 Answers2

1

A program cannot reliably keep information in memory between runs*, so it has to store such information in a file. Files are designed to store information between runs of a program.

As to how you'll do it, that's your decision. Most likely, you'll choose a simple and readable format with, for example, the head word at the start of a line, followed by a colon, then a list of semi-colon separated synonyms:

head: skull; cranium; noggin; noodle
head: aptitude; faculty; talent; gift; capacity; ability; mind; brain

This is flexible and allows you to use phrases (even phrases containing commas) in the synonym lists. You can sort the data before you write it out for convenience when reading in, but it is generally best to validate that the data is still sorted when you read it back in (at the start of the next run) because someone may have hand-edited the file and not preserved sorted order.


* If the process uses System V shared memory IPC, then you could store the data in a shared memory segment that would exist between runs of the program. However, it is not a particularly sensible idea to try doing that. A file has better durability; it will (usually) survive reboots, and could be placed on a distributed file system whereas shared memory is restricted to a single machine.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

You need to design a simple file format which could describe your data, then write code to write to that format, and code to read from that format and handle errors properly.

As a simple example, you could have a file which stored lines like:

happy:joyful
happy:exuberant

In this case you would also need to make sure that users can't enter blank lines or colons as word input, so that the syntax is unambiguous.

codebeard
  • 2,356
  • 2
  • 13
  • 15