Search code examples
cfileio

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.


Solution

  • 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