我想读取一个文件并将每一行存储在指针数组中。该文件有 4 行,每行有 4 个字符。我使用 fgets 读取每一行并将该行分配给我的指针数组。在分配时,我可以正确写行,但在循环之后(用于读取文件)结果不正确。NUM_VOWELS 为 4,MAX_SIZE 为 20,它们被定义为宏
我的主要是:
int main(void)
{
FILE *file_vowels;
int i, line_count = 0;
char *vowels[NUM_VOWELS]; // my array of pointer
char line[MAX_SIZE], *status;
file_vowels = fopen(FILE_VOWELS, "r");
for(
status = fgets(line, MAX_SIZE, file_vowels);
status != NULL;
status = fgets(line, MAX_SIZE, file_vowels)
)
{
if(line[strlen(line) -1] == '\n')
line[strlen(line) -1] = '\0';
vowels[line_count] = line;
printf("vowels[%d] : %s\n", line_count, vowels[line_count]);
line_count++;
}
printf("=====================\n");
for(i = 0; i < NUM_VOWELS; ++i)
printf("vowels[%d] : %s\n", i, vowels[i]);
return 0;
}
这是结果:
这是示例文件: