c - 将文件中的数据放入C中的数组

标签 c arrays file

这是我的代码。

#include <stdlib.h>
#include <stdio.h>

int main() {
    //Vars
    FILE *fp;
    char word[9999],
        *arrayOfWords[9999];
    int wordCount = 0, i;
    //Actions
    fp = fopen("data.txt", "r");
    if(fp != NULL) {
        while(!feof(fp)) {
            fscanf(fp, "%s", word);
            arrayOfWords[wordCount] = word;
            wordCount++;
        }
        for(i = 0; i < wordCount; i++) {
            printf("%s \n", arrayOfWords[i]);
        }
    puts("");
    } else {
        puts("Cannot read the file!");
    }
    return 0;
}

我正在尝试从文本文件中读取一些数据并将其存储到数组中。 当我在循环中时一切都很好,但是当我离开循环时,我的数组中任何索引的任何值都被文件的最后一个单词填充。谁能帮我找出我做的错误?

数据文件:

Hello there, this is a new file.

结果:

file.
file.
file.
file.
file.
file.
file.
file.

如有任何帮助,我们将不胜感激!

最佳答案

您需要为数组的每个单独成员分配内存(使用 malloc 或通过提供数组的第二个维度并将其声明为 char 类型而不是 char*).你所做的类似于:

char *s;
scanf("%s", s);

这在 C 中是行不通的。实际上这里有 UB(未定义行为),因为指针未初始化。

编辑:你让数组中的所有字段指向你的数组 word 相反,一旦你读了 word 你应该为字符串分配新的内存然后 strcpy word 放入其中。

关于c - 将文件中的数据放入C中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14940633/

相关文章:

c - 使用 gdb 进行 fork() 系统调用

c - MPI_将素数数组收集到一个数组中

c - 为什么我们不在 scanf 中使用 '&' 作为 char 数组

arrays - Swift 4 排序有错误的元组

c - 是否可以在 C 中编写符合要求的 malloc 实现?

Java:计算(和 "removing")二维数组的最大/最小值

javascript - 初学者 : rolling a dice: frequency and if-else-if?

java - Apache Tika 和文件访问而不是 Java 输入流

java - 我应该用什么文件名来测试我的应用程序?

javascript - 如何在外部文件中创建选择菜单并将其嵌入到 html 中以显示菜单