Is there a way to read a text file into a one dimensional array in plain C? Here’s what I tried (I am writing hangman):
int main() {
printf("Welcome to hangman!");
char buffer[81];
FILE *dictionary;
int random_num;
int i;
char word_array[80368];
srand ( time(NULL) );
random_num = rand() % 80368 + 1;
dictionary = fopen("dictionary.txt", "r");
while (fgets(buffer, 80, dictionary) != NULL){
printf(buffer); //just to make sure the code worked;
for (i = 1; i < 80368; i++) {
word_array[i] = *buffer;
}
}
printf("%s, \n", word_array[random_num]);
return 0;
}
What’s wrong here?
Try changing a couple of things;
First; you’re storing a single char.
word_array[i] = *buffer;means to copy a single character (the first one on the line/in the buffer) into each (and every) single-char slot in word_array.Secondly, your array will hold 80K characters, not 80K words. Assuming that that’s the length of your dictionary file, you can’t fit it all in there using that loop.
If you want a one-dimensional array intentionally, for some reason, you’ll have to do one of three things:
pretend you’re on a mainframe, and use 80 chars for every word:
create a parallel array with indices to the start of each line in a huge buffer
switch to using an array of pointers to char, one word per slot.
I’d recommend the latter, as otherwise you have to guess at the max size or waste a lot of RAM while reading. (If your average word length is around 4-5 chars, as in English, you’re on average wasting 75 bytes per word.)
I’d also recommend dynamically allocating the word_array:
… which can lead you to a safer read, if your dictionary size ever were to change:
Sorry, this is posted in an hurry, so I haven’t tested the above. Caveat emptor.