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

3
我将尝试将c文件的每一行添加到一个数组中。文件.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;
}

你是不是想说 sizeof(line) - CinCout
@gargankit sizeof line 也是正确的。 - Jabberwocky
这一行代码:programs[i]=line; 有两个问题。1)50个指向字符的指针数组需要为每个指针分配所需的内存(并将指针设置为该内存)。建议您使用calloc(),以便内存段预先设置为所有'\0'。2)这行代码只是将programs[i]指针设置为指向数组line[]。实际需要的是类似于:strcpy(programs[i], line); - user3629249
4个回答

3

你需要更改

programs[i]=line; 

为了

programs[i]=strdup(line); 

否则,programs 数组中的所有指针都将指向同一个位置(即 line)。
顺便说一下:如果 files.txt 包含超过 50 行,你将遇到麻烦。

1
  1. 这里不需要 i,并且为了将所有行的指针保存在数组中,您必须使用 strdup()。就像这样:

    programs[numProgs++] = strdup(line);

  2. 在第二个循环条件中,必须是 j < numProgs

  3. 在 while 循环中添加附加条件以防止写入超出数组末尾:

    while(fgets(line, sizeof line, file)!=NULL && numProgs < 50)


0

你需要为每一行分配新的存储空间,否则你只有一个行缓冲区来存储文件名,所以只有最后一个会显示出来,在 while 循环中执行以下操作:

programs[i] = calloc(strlen(line)+1, 1);
strcpy(programs[i], line);

0

当声明 char *programs[50] 时,它们不是有效的指针。因此,您必须根据每行大小为每个指针分配内存。所以,尝试这个..(这里我使用了 malloc 和 strcpy)

    #include <stdio.h>
    #include <stdlib.h>
    #include<string.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]=malloc(sizeof(line));
    strcpy(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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接