从UNIX返回一个int

时间:2013-03-05 03:35:40

标签: c unix

我需要使用我的C程序查找目录中的文件数,但是我在保存数字时遇到了问题。我正在使用系统命令而没有运气。

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

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

2 个答案:

答案 0 :(得分:3)

你应该使用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 files\n", 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);

答案 1 :(得分:1)

如果您的问题是关于计算文件,那么最好使用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 - %m\n");
         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: %d\n", n);
    pclose(pf);
    return 0;
}