我想用popen()構建一個字符串數組,但數組中的每個索引都是返回的最後一個字符串。我最終只是想將所有文件的目錄列表放到一個數組中。使用popen()構建一個包含fgets()的數組
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fp;
fp = popen("find ~/ -maxdepth 1 -type f", "r");
if (fp == NULL) { printf("Failed to run command\n"); exit; }
char path[999];
char* rawdata[999];
int i = 0;
while (fgets(path, sizeof(path)-1, fp) != NULL) {
rawdata[i] = path; // Shouldn't this assign every index
i++; // a different string ?
}
pclose(fp);
/* Below, every index is the same string ? */
printf("\n%s", rawdata[0]);
printf("\n%s", rawdata[1]);
printf("\n%s", rawdata[2]);
}
,因爲你只是在做你大概可以使用http://rosettacode.org/wiki/Walk_a_directory/Recursively#C上授予可能缺失二進制,而不是一個popen方法步行dirtree,大多數系統確實有找,但會更慢 – technosaurus