【发布时间】:2014-10-22 07:22:09
【问题描述】:
我正在尝试将 c 文件的每一行添加到数组中。 files.txt 的内容是
first.c
second.c
third.c
fourth.c
我希望我的代码打印这些行中的每一行,将行添加到我的数组中,然后打印出我的数组中的每个条目。现在它正在正确地执行第一部分,但它只是将第四个.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)吗? -
@gargankit
sizeof line也是正确的。 -
这一行:programs[i]=line;不会工作有两个原因。 1)指向 char 的 50 个指针的数组需要为这 50 个指针中的每一个分配所需的内存(以及指向该内存的指针的设置)。建议您使用 calloc() 以便将内存段预先设置为所有 '\0'。 2) 这行所做的就是将programs[i] 指针设置为指向数组line[]。真正需要的是:strcpy(programs[i], line);