所以我有类似
的东西system("(find . -type f | wc -l)");
如何将(找到。-type f | wc -l)的结果存储在C中的变量中?
答案 0 :(得分:5)
你做不到。在那你可以将输出重定向到一个文件。使用该文件后,您可以从中获取该值。
system("find . -type f | wc -l >output.txt");
然后使用open()
或fopen()
打开该文件。获取该命令的输出。 open和fopen.
否则您可以使用popen()
。
代码使用popen()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *pfp;
int i;
if ((pfp = popen("find . -type f | wc -l", "r")) == NULL) {
perror("popen");
return 10;
}
if (fscanf(pfp,"%d\n",&i) != 1)
{
perror("fscanf");
return 2;
}
printf("%d\n",i);
pclose(pfp);
return 0;
}
代码使用fopen()
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
FILE *fp;
int i;
if (system("find . -type f | wc -l >output.txt") != 0)
{
perror("system");
return 10;
}
if ((fp = fopen("output.txt", "r")) == NULL)
{
perror("fopen");
return 10;
}
if ( fscanf(pfp,"%d\n",&i) != 1 )
{
perror("fscanf");
return 2;
}
printf("%d\n",i);
fclose(fp);
return 0;
}