如何读取文本文件并将它们复制到字符串数组?

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

我正在尝试打开一个名为 dictonary.txt 的文件并将其内容复制到一个字符串数组。但是忘记怎么做了

这是我目前的情况:

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

有人可以帮我解决这个问题吗?

编辑:文件中有 999 个单词,所有单词的长度都在 15 个或更少。

如评论中所述,while(!feof (fp)) 不会按预期工作,您还缺少否定符,但这不是重点,一个简单的方法是使用 fgets 并利用它的 return 值来检测文件的结尾,因为它 returns NULL 当没有更多行要读取时:

#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")] = '[=10=]'; // remove newline from the buffer, optional
        }

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

请注意,这也将读取空行, 仅包含 \n 或其他空白字符的行。

Test sample

#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;
}

除了 != EOF,您还可以使用 == 1,因为 fscanf return 是扫描对象的值。所以如果你这样做:

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

如果一个词扫描成功,它会return1。当它到达文件末尾时它不会。所以你也可以这样做。