【问题标题】:returning an int from UNIX从 UNIX 返回一个 int
【发布时间】:2013-03-05 03:35:40
【问题描述】:

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

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

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

【问题讨论】:

  • 系统确实返回了一个数字。在您的案例中,您希望得到什么作为返回值?
  • 见:stackoverflow.com/questions/4324114/… 这解释了如何捕获输出并像文件一样读取它。
  • 文件数是您正在运行的命令的输出而不是它的返回值。 system()返回命令的返回值

标签: c unix


【解决方案1】:

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

【讨论】:

  • 此外,明智的做法是检查 scandir 的返回值以确定成功/失败,如上面的 opengroup 链接所述。
【解决方案2】:

如果您的问题是关于计数文件,那么最好使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2020-10-31
    • 2012-06-21
    • 2011-06-21
    • 2010-12-05
    • 2015-08-28
    • 2014-06-28
    相关资源
    最近更新 更多