在C中读取和填充动态数组



我想从一个文件中读取并基于它创建一个动态数组(用于在上使用qsort((方法(。我有以下代码来获取文件中的行数(满足特定条件,但不知道如何填充数组的各个元素(。

FILE* file = fopen("$filename", "r");
int count = 0; // Count num lines in the file
char buffer[50];
while(fgets(buffer, 50, file)) {
count++;
}
char** myArray;
myArray = malloc(count * sizeof(char*));
for (int i = 0; i < count; i++) {
myArray[i] = malloc(sizeof(char) * 51); // to include space for terminating character
}
// Re-open the file
fclose(file);
fopen("$filename", "r");
int ctr = 0; // Indexing for the array.
while(fgets(buffer, 50, file)) {
char* word = malloc(sizeof(char) * (strlen(buffer) + 1));
strcpy(myArray[ctr], word);
ctr++;
free(word);
}
for (int i = 0; i < count; i++) {
printf("%sn", myArray[ctr]); // This just prints 7 new lines.
}

您可以简化代码:

  • 不需要分配指针数组中的所有行,只需在读取文件时分配行即可
  • 无需关闭并重新打开文件,只需rewind()流即可

这是一个修改后的版本:

char **read_file(const char *filename, int *countp) {
FILE *file = fopen(filename, "r");
int count = 0; // Count num lines in the file
char buffer[200];
while (fgets(buffer, sizeof buffer, file)) {
count++;
}

char **myArray = malloc(count * sizeof(char *));
if (myArray == NULL) {
fclose(file);
return NULL;
}

rewind(file);

int ctr = 0; // Indexing for the array.

while (ctr < count && fgets(buffer, sizeof, file)) {
// you might want to strip the trailing newline
//buffer[strcspn(buffer, "n")] = '';
myArray[ctr++] = strdup(buffer);
}
fclose(file);

for (int i = 0; i < ctr; i++) {
printf("%s", myArray[i]);
}
*countp = count;
return myArray;
}

相关内容

  • 没有找到相关文章