Put data from file to array in C

2020-06-23 05:54发布

here's my code.

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

I am trying to read some data from a text file and store it into an array. Everything is fine while I'm in the loop, but when I get out of there, any value of any index in my array is filled with the last word of the file. Could anyone help me find out mistakes I am doing?

Data file:

Hello there, this is a new file.

Result:

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

Any help would be appreciated!

标签: c arrays file
3条回答
放荡不羁爱自由
2楼-- · 2020-06-23 06:38

This:

arrayOfWords[wordCount] = word;

does not copy the current word into separate storage, it merely assigns another pointer to point to the same piece of storage that word does. So you end up with an array of pointers to the same word array. You need to separately allocate memory for each word and copy the characters that make up each word (and the NULL terminator), rather than the pointer.

查看更多
We Are One
3楼-- · 2020-06-23 06:50

There are atleast 2 points of concern in your code. char word[9999], *arrayOfWords[9999]; defines arrayOfWords to be an array of 9999 char pointers. This is one point of concern.

Another point is arrayOfWords[wordCount] = word;. Here to store the newly read word, you need to allocate space as arrayOfWords is an array of pointers. Please find your modified code as below.

int main() {
//Vars
FILE *fp;
char arrayOfWords[30];
int wordCount = 0, i;
//Actions
fp = fopen("data.txt", "r");
if(fp != NULL) {
    while(!feof(fp)) {
        fscanf(fp, "%s", &arrayOfWords[wordCount]);
        wordCount++;
    }
    puts("");
    for(i = 0; i < (wordCount - 1); i++) {
        puts(arrayOfWords[i]);
    }
puts("");
} else {
    puts("Cannot read the file!");
}
return 0;
}
查看更多
forever°为你锁心
4楼-- · 2020-06-23 06:57

You need to allocate memory for each individual member of your array(using malloc or by giving a second dimension of the array and declaring it of type char instead of char*). What you do is similar to:

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

And this can not work in C. In fact here you have UB(undefined behavior), because the pointer is not initialized.

EDIT: you get all the fields in the array to point to your array word instead, once you have read word you should allocate new memory for the string and then strcpy word into it.

查看更多
登录 后发表回答