从UNIX返回int

问题描述:

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

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

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

+0

系统不会返回一个数字。你希望在你的案例中得到什么样的回报? – Sebastian 2013-03-05 03:39:44

+0

文件数量 – 2013-03-05 03:41:13

+1

请参阅:http://stackoverflow.com/questions/4324114/how-to-capture-process-output-in-c这解释了如何捕获输出并从中读取,就像文件一样。 – Keith 2013-03-05 03:42:55

您应该使用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

此外,检查scandir的返回值以确定成功/失败是明智的,如上面的opengroup链接所述。 – Sebivor 2013-03-05 04:06:56

如果你的问题是如何计算的文件,然后更好的C库FUNC:使用自定义选择器(和排序方法)目录如果可能的话,就像@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; 
}