Kazumi411
Kazumi411

Reputation: 37

How to read in text files and copy them to a string array?

I'm trying to open a file called dictonary.txt and copy its contents to a string array. But I forget how to do it.

Here's what I have so far:

int main(int argc, char** argv) 
{
    char dict[999][15];
    FILE *fp;
    fp = fopen("dictionary.txt", "r");
    while(feof (fp))
    {
            
    }
}

Can someone help me with this?

EDIT: There are 999 words in the file and all of them have 15 characters or less.

Upvotes: 2

Views: 83

Answers (2)

anastaciu
anastaciu

Reputation: 23802

As stated in the comments while(!feof (fp)) will not work as intended, you are also missing the negator but that's beside the point, a simple way to do this is to use fgets and take advantage of its return value to detect the end of the file, as it returns NULL when there are no more lines to read:

#include <stdio.h>
#include <string.h>

int main()
{
    char dict[999][15];
    size_t ind; // store the index of last read line

    FILE *fp = fopen("dictionary.txt", "r");

    if (fp != NULL) // check if the file was succefully opened
    {
        // read each line until he end, or the array bound is reached
        for (ind = 0; fgets(dict[ind], sizeof dict[0], fp) && ind < sizeof dict / sizeof dict[0]; ind++)
        {
            dict[ind][strcspn(dict[ind], "\n")] = '\0'; // remove newline from the buffer, optional
        }

        for (size_t i = 0; i < ind; i++) // test print
        {
            puts(dict[i]);
        }
    }
    else
    {
        perror("Error opening file");
    }
}

Note that this will also read empty lines, i.e. lines with \n only or other blank characters.

Test sample

Upvotes: 3

Tetsuo Rulin
Tetsuo Rulin

Reputation: 3

#include <stdio.h>

int main()
{
    char dict[999][15];
    FILE * fp;
    fp = fopen("dictionary.txt", "r");

    int i = 0;
    while (fscanf(fp, "%s", dict[i]) != EOF)
            i++;

    // i is your length of the list now so you can print all words with
    int j;
    for (j = 0; j < i; j++)
            printf("%s ", dict[j]);

    fclose(fp);
    return 0;
}

Instead of != EOF, you can also do == 1 because fscanf returns a value of scanned things. So if you do:

fscanf(fp, "%s", dict[i]);

it will return 1 if a word is successfully scanned. And it won't when it reaches the end of the file. So you can do it that way too.

Upvotes: 0

Related Questions