【问题标题】:How to read in text files and copy them to a string array?如何读取文本文件并将它们复制到字符串数组?
【发布时间】:2021-06-24 06:56:33
【问题描述】:

我正在尝试打开一个名为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(file)) is always wrongwhile (feof(file)) 没有意义
  • 这将取决于输入文件的结构,但fgets()fscanf() or sscanf() 会很有用。
  • @pmg 这里其实是while(feof (fp))。没有!,情况更糟。
  • 您想要最多 999 个单词,每个单词少于 15 个字符...还是每个单词最多 15 个单词少于 999 个字符(如您的代码所示)?
  • @Kazumi411 它应该可以完美运行,我添加了更多代码来帮助您查明问题,我还添加了一个实时示例,检查它wandbox.org/permlink/TDDyZXswA07imf9a

标签: c file io


【解决方案1】:

正如 cmets 中所述,while(!feof (fp)) 将无法按预期工作,您也缺少否定符,但这不是重点,一个简单的方法是使用 fgets 并利用其返回值来检测文件末尾,因为当没有更多行要读取时,它返回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")] = '\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");
    }
}

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

Test sample

【讨论】:

  • 还要小心:fgets() 会将读取的换行符放入缓冲区,因此您可能需要在进一步处理之前将其删除。
  • @MikeCAT 添加了一个删除它的选项,同时注意 blank 行也将被解析。
  • 如果你想避免两次解析你的字符串,我刚刚发布了一个没有新行的 fgets 函数:codereview.stackexchange.com/questions/258772/… 欢迎你的见解! @MikeCAT 和 anastciu
  • 注意问题中更正数组维度顺序的编辑。
【解决方案2】:
#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;
}

您也可以使用 == 1 代替 != EOF,因为 fscanf 返回已扫描事物的值。所以如果你这样做:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多