c - returning an int from UNIX



我需要在我的C程序中找到目录中的文件数量,但我无法保存该数字。我正在使用系统命令,但没有任何运气

n = system( " ls | wc -l " ) ;

系统似乎没有返回一个数字,所以我有点卡在这一点上。什么好主意吗?

你应该使用scandir POSIX函数。

http://pubs.opengroup.org/onlinepubs/9699919799/functions/scandir.html

一个例子
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
struct dirent **namelist;
int n;
n = scandir(".", &namelist, 0, alphasort);
printf("%d filesn", n);

当你使用Unix函数编写C代码时,POSIX函数是实现这一点的标准方法。你可以用一种标准的方式实现你自己的ls函数。

享受吧!

注意:你可以定义一个选择器在scandir中使用,例如,只获取非目录的结果

int selector (struct dirent * entry)
{
   return (entry->d_type != 4);
}

更多选项类型,请访问:http://www.gsp.com/cgi-bin/man.cgi?topic=dirent

然后你可以使用自定义选择器(和排序方法)扫描你的目录:

n = scandir(".", &namelist, selector, alphasort);

如果你的问题是关于文件计数的,那么最好使用C库函数,如果可能的话,就像@Arnaldog所演示的那样。

然而,如果你的问题是关于从执行的子进程中检索输出,popen(3)/pclose(3)(符合POSIX.1-2001)是你的朋友。函数popen()返回FILE指针,你可以像fopen()返回一样使用,只需要记住使用pclose()关闭流,以避免资源泄漏。

简单的说明:

#include <stdio.h>
int main(void)
{
    int n;
    FILE * pf = popen("ls | wc -l", "r");
    if (pf == (FILE *) 0) {
         fprintf(stderr, "Error with popen - %mn");
         pclose(pf);
         return -1;
    }
    if (fscanf(pf, "%d", &n) != 1) {
         fprintf(stderr, "Unexpected output from pipe...n");
         pclose(pf);
         return -1;
    }
    printf("Number of files: %dn", n);
    pclose(pf);
    return 0;
}

最新更新