C 使用popen()构建带有fgets()的数组
我试图使用popen()构建字符串数组,但数组中的每个索引都是返回的最后一个字符串。我最终只是想把所有文件的目录列表放到一个数组中C 使用popen()构建带有fgets()的数组,c,C,我试图使用popen()构建字符串数组,但数组中的每个索引都是返回的最后一个字符串。我最终只是想把所有文件的目录列表放到一个数组中 #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\
#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]);
}
#包括
#包括
void main()
{
文件*fp;
fp=popen(“find~/-maxdepth 1-typef”,“r”);
如果(fp==NULL){printf(“无法运行命令”);退出;}
字符路径[999];
字符*原始数据[999];
int i=0;
while(fgets(path,sizeof(path)-1,fp)!=NULL){
rawdata[i]=path;//这不应该分配每个索引吗
i++;//另一个字符串?
}
pclose(fp);
/*下面,每个索引都是相同的字符串*/
printf(“\n%s”,原始数据[0]);
printf(“\n%s”,原始数据[1]);
printf(“\n%s”,原始数据[2]);
}
否。您正在存储路径
,该路径是数组的名称,因此会衰减为指向数组开头的指针。因此,实际上,rawdata
的所有元素都有相同的值,这就是数组路径的地址,它永远不会改变
要实际获取复制到rawdata
的路径的内容,需要在rawdata[i]
(malloc
)中为其分配内存,然后使用strcpy
。标准库中有一个快捷方式,名为strdup
:
...
while (fgets(path, sizeof(path)-1, fp) != NULL) {
rawdata[i] = strdup(path);
if (rawdata[i] == NULL)
goto exit_no_mem;
i++;
}
n = i;
...
/* in the end */
for (i = 0; i < n; ++i)
free(rawdata[i]);
return EXIT_SUCCESS;
exit_no_mem:
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
非常感谢。我还没有找到strdup(),也不会在任何合理的时间内清除“path”指针。由于您只是在执行dirtree遍历,您可能可以使用popen代替可能丢失的二进制文件,大多数系统都有find,但速度会慢一些
...
while (fgets(path, sizeof(path)-1, fp) != NULL) {
rawdata[i] = strdup(path);
if (rawdata[i] == NULL)
goto exit_no_mem;
i++;
}
n = i;
...
/* in the end */
for (i = 0; i < n; ++i)
free(rawdata[i]);
return EXIT_SUCCESS;
exit_no_mem:
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
while (i < 999 && fgets(path, sizeof(path)-1, fp) != NULL)