c - 将 linux.words (/usr/share/dict/words) 中的前 10 个单词写入数组

标签 c arrays list

因此 linux.words 文件是一个 \n 分隔的单词列表。我尝试使用 fopen 访问它,如下所示:

{
    FILE* words;

    words = fopen("~/usr/share/dict/words", "r");
    char* dictionary[10];
    if (words != NULL)
    {
        for (int i = 0; i < 10; i++)
        {
            fscanf(words, "%s", dictionary[i]); 
            printf("%s", dictionary[i])
        }
    }
}

我遇到了很多麻烦。我怀疑这可能与我需要在其中放入有关 \n 的内容有关,而且也许我没有正确打开该文件。

最佳答案

您没有为从文件中读取的单词分配空间。

char* dictionary[10];

...
// for each word
dictionary[i]= malloc(WORD_SIZE); 
...

关于c - 将 linux.words (/usr/share/dict/words) 中的前 10 个单词写入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19895811/

相关文章:

c++ - Linux X-Server 编程资源

python - 如何删除数组中最小的数字,如果有多个最小数字,则删除第一个

javascript - 基于另一个数组并组合过滤数组

java - 循环中每个用户输入的新变量

javascript - 导航时列表项淡入淡出

python - 根据另一个数组中的所有值查找一个数组的最近索引 - Python/NumPy

c - 打开文件进行编辑

add/sub/div/mul 的 C 解析器程序。读取用户的输入想要在分号处终止我的程序而不是按回车

c - fmemopen 不写入 c 字符串

c# - 序列化 XML 时更改元素的顺序