c - 从 c 文件中读取行并将字符串放入数组中

标签 c arrays file-io

我正在尝试将 c 文件的每一行添加到一个数组中。 files.txt的内容是

first.c
second.c
third.c
fourth.c

我希望我的代码打印每一行,将这些行添加到我的数组中,然后打印出数组中的每个条目。现在它正确地完成了第一部分,但它只是将 fourth.c 添加到数组中。有人可以告诉我我的代码有什么问题吗?

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

int main(void) {
    int i=0;
    int numProgs=0;
    char* programs[50];
    char line[50];

    FILE *file;
    file = fopen("files.txt", "r");

    while(fgets(line, sizeof line, file)!=NULL) {
        //check to be sure reading correctly
        printf("%s", line);
        //add each filename into array of programs
        programs[i]=line; 
        i++;
        //count number of programs in file
        numProgs++;
    }

    //check to be sure going into array correctly 
    for (int j=0 ; j<numProgs+1; j++) {
        printf("\n%s", programs[j]);
    }

    fclose(file);
    return 0;
}

最佳答案

你需要改变

programs[i]=line; 

programs[i]=strdup(line); 

否则 programs 数组中的所有指针都将指向同一位置(即 line)。

顺便说一句:如果 files.txt 包含超过 50 行,您就会遇到麻烦。

关于c - 从 c 文件中读取行并将字符串放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502236/

相关文章:

c - 函数末尾出现段错误

c - 从 []byte 到 char*

c - 如何在 C 中的父进程和子进程之间共享结构数组?

file-io - 如何使用 "compress/gzip"包来 gzip 文件?

python - 如何将数据随机拆分为训练集和测试集?

c++ - Eclipse helios(Windows 7 64 位)中 Unresolved inclusion : <stdio. h>

python - 将 C 缓冲区的内容复制到 numpy 数组

ios - 无效的 CfStringRef plist(字典数组)iOS

php - 用特定的方案分割字符串,这是一个不好的做法吗?

javascript - 如何处理 Electron 中的本地文件上传?