通过文件迭代并向String Array添加信息 - C.

问题描述 投票:1回答:1

我正在尝试迭代几个文件,并将每行的信息放入动态分配的字符串数组中。我像这样分配了数组:

followerArr = malloc(sizeof(char *) * (followerCount + 1));
for (i = 0; i < followerCount; i++)
    followerArr[i] = malloc(sizeof(char) * 15);

这似乎完全正常。然后我浏览了文件,直到到达文件的末尾,并希望将用户名放入字符串数组中。其中一个文件看起来像这样:

4
user1
user2
user3
user4

第一个数字是文件中的用户数,在本例中为4.我的文件扫描代码是:

if (followerCount > 0) {
    fp3 = fopen(followerFile, "r");
    if (fp3 == NULL)
        printf("Error opening file\n");
    else {
        char line[1000];
        while (fgets(line, sizeof(line), fp3) != NULL) {
            if (i > 0)
                followerArr[i - 1] = line;
            i++;
        }
        fclose(fp3);
    }
}

我也在while循环中做了一个print语句,它正常打印出来,即它会打印出来

user1
user2
user3
user4

但是在while循环和关闭文件之后,它会打印出4次user4。为什么数组基本上会从while循环中的时间改变,然后一旦它在它之外?

c
1个回答
1
投票

我将再给你一个逐行读取文件的例子,也许它可以帮助你使用当前的代码。

char* line;
ssize_t len;
char** dest = malloc (sizeof(char*) * 15)
size_t read = 0;
while ((read = getline(&line, &len, fp)) != -1) {
    line[strlen(line) - 1] = '\0'; // Remove the newline
    dest[i] = malloc (strlen(line));
    strcpy(dest[i], line);
}

之后你需要释放每个元素和整个数组

© www.soinside.com 2019 - 2024. All rights reserved.