Randomly choosing a word from a text file in C

I'm quite new at programming and I'm trying to code Hangman. I have 10 words saved in a textfile in the same folder as the code and I want the program to randomly choose a word and save that word into a character array.

I've googled and looked around but I can't seem to figure out how to do it. Do I use something like fopen() and rand()?

Answers


assuming the words are written one per line , here's a small piece of code that'll do that :

FILE* fp = NULL;
char words[20];
int i = 0 , ran = 0;
srand(time(NULL));
fp = fopen("path" , "r+");
for(; fgets(words , sizeof(words) , fp) ; i++)
          ;
ran = rand() % i;
rewind(fp);
for(i = 0 ; i < ran ; i++)
    fgets(words , sizeof(words) , fp);

 printf("%s\n" , words);

beware of not having a new line character at the end of you file because it will be considered as a word and will sometimes be returned to you


It depends on how these words are saved in a file. My first thought is to choose random number and then read a word which is written in a line that has chosen number. But your words have to be written one per line.


You can do this in three steps:

  1. Read all words from file to char words[N][100] (here N=10). In C, you can do this as follows:

    char words[10][100];
    int i = 0;
    while(10>i && fgets( words[i++], 100, file) );
    
  2. Generate a random number i within [0,N-1].

    int i = rand() % 10;
    
  3. Return words[i][].


Need Your Help

AIX- Does not install shared lib

install shared-libraries aix

I am able to build the shared object successfully using the holy native compiler "xlc" on AIX.It does build the shared object library but does not install the shared object library.

Delete all text in a file between two strings without importing any modules

python string python-2.7 text-processing

Due to restrictions I can't use any import modules like re, sys or os etc.