【问题标题】:Read and check system call line by line within function在函数内逐行读取和检查系统调用
【发布时间】:2019-04-23 17:35:19
【问题描述】:

我正在我的主函数中运行系统调用,我想知道我是否可以在主函数中逐行读取系统调用的命令行输出。

我一直在网上寻找有关如何执行此操作的任何提示或想法,但我找不到任何提示或想法。需要注意的一点是,我不希望将输出写入文件然后从该文件中读取,而是逐行读取命令行输出。

int main(int argc, char const *argv[]) {
    system("ls -al");
    return 0;
}

例如,在上面的代码中,我想通过这个C函数打印当前目录下的所有文件。有了这些信息,我只想打印 4 月更新的那些(在第 6 列中以“Apr”区分)。我是否可以逐行读取输出,将行拆分为数组并检查指定的列是否为“Apr”,如果是,如何?任何和所有的帮助/建议将不胜感激。

【问题讨论】:

  • 现在的问题是 - 你想在你的系统 shell 中使用 system("ls -al | grep Apr | blabla") 进行过滤还是你想使用 popen("ls -al"); 并通过读取来自 FILE* 的行来过滤输出popen 使用一些 strstr 或类似方法返回的对象?无论如何,这太宽泛了。 |再想一想,我认为您只需搜索popen
  • 我很抱歉没有更清楚地说明。我想通过读取行​​来过滤输出,而不仅仅是 grep 它,因为我还想对具有整数输出的其他系统命令输出执行此操作,并比较这些整数输出是否大于给定数字。
  • 这听起来像是一个 XY 问题。也许你真的想list the contents of a directory 然后check the modification date of each file
  • 此类任务最好使用pythonshell 等脚本语言完成,而不是c
  • @balki 虽然在 Python 这样的语言中肯定容易得多,但我需要用 C 来完成。

标签: c


【解决方案1】:

你可以像这样使用popen:

#include <stdio.h>

int main()
{
    FILE * fp = popen("ls -l", "r");
    char buf[1024];
    while (fgets(buf, 1024, fp)) {
        printf("returned: \"%s\"\n", buf);
    }
    return 0;
}

这仅显示从命令中读取每一行,您仍然需要拆分文本以执行您想要的操作。

因为它很有趣,所以这里有一个从字符串缓冲区中抓取字段的简单函数:

char * get_field(char *buffer, int field)
{
    int white = 1; // simple state machine
    char *p;
    char *first = NULL;
    for (p=buffer; *p; p++) {
        if (white) {
            if (*p > ' ') {
                white = 0;
                first = p;
            }
        } else {
            if (*p <= ' ') {
                white = 1;
                field--;
                if (!field && first)
                    return strndup(first, p-first);
            }
        }
    }
    return NULL;
}

int main()
{
    FILE * fp = popen("ls -l", "r");
    char buf[1024];

    while (fgets(buf, 1024, fp)) {
        char *month = get_field(buf, 6);
        if (month) {
            printf("  month: \"%s\"\n", month);
            free(month);
        }
        char *file = get_field(buf, 9);
        if (file) {
            printf("  file: \"%s\"\n", file);
            free(file);
        }
    }
    return 0;
}

这是一种简单的暴力破解方法,适用于简单的程序,不提供典型的 split() 函数的功能。但它说明了在 C 中做这种事情的一种方法。

【讨论】:

  • 公平,更新的答案。但这只是为了简单地说明这个想法。
  • 你并没有真正解决任何问题。您的代码仍然处理最后一行两次。
  • 啊,我现在明白了。固定的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多