【问题标题】:String Parsing in C with an argument given in main使用 main 中给出的参数在 C 中进行字符串解析
【发布时间】:2015-02-03 01:19:59
【问题描述】:

我在 main 中传递了一个参数,并希望将该参数包含在其中一行代码中。我很难将它整合到代码中。 这是代码:

   int main(char *argv[])
   {
       FILE *in;
       char buff[512];
       // char temp [512];

       // /nfs/engfs/haquresh/Desktop -> should be argument given in main
       // " find argv[] -type f | wc -l", "r" this is want i want stored in a char temp
       if (!(in = popen("find /nfs/engfs/haquresh/Desktop -type f | wc -l", "r")))
       {

        return 1;
       }

它应该是 C 中的基本字符操作,我只是很难用它。任何帮助,将不胜感激。

【问题讨论】:

  • 您错误地声明了main() - int main(int argc, char *argv[])。第一个参数告诉有多少字符串参数传递给它。第二个参数指向的第一个字符串通常是可执行文件的文件名。
  • 嗨哈桑。我看到您是 Stack Overflow 的新手。收到好的答案后,您应该将喜欢的答案标记为问题的最佳答案。

标签: c linux string char


【解决方案1】:

请记住,将任意参数作为代码调用的程序可能是一个严重的安全问题。

/* popen1.c */
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
    FILE* fin;
    int i;
    char cmd[ 4096 ];

    if (argc < 2) {
        printf("Must specify arguments\n");
        return -1;
        }
    sprintf(cmd, "find %s |wc -l", argv[1]);

    fin = popen(cmd, "r");
    if (!fin) {
        perror("popen");
        return -1;
        }
    while(!feof(fin)) {
        if (fgets(line, sizeof(line), fin) != NULL)
            printf("%s", line);
        }
    pclose(fin);

    return 0;
}

编译为cc -opopen1 popen1.c

这样跑:./popen1 /nfs/engfs/haquresh/Desktop

【讨论】:

  • 这段代码如何给 fopen 这个参数 "find /nfs/engfs/haquresh/Desktop -type f | wc -l", "r" ?
  • 我只希望这是 /nfs/engfs/haquresh/Desktop 的参数。
  • @hasanqureshi 你输入的任何参数。
  • @user590028:请将len = snprintf(cmd, sizeof cmd, "find %s |wc -l", argv[1]); if (len &lt; 1 || (size_t)len &gt;= sizeof cmd) { printf("Path %s is too long.\n", argv[1]); return EXIT_FAILURE; }int len; 一起设置,这样就不会有缓冲区溢出的风险。
  • 然后,备份整个$HOME,然后在阅读code injection 上的维基页面时运行./popen1 "$HOME; rm -rf $HOME"
【解决方案2】:

我会避免从您的 C 程序运行任何 find 进程,因为您可以(并且可能应该)使用 nftw(3) 函数来搜索您的树。

使用nftw 在内部进行搜索将避免进程。顺便说一句,| wc -l 的功能用 C 编程也很简单。

如果您坚持运行管道,则无需编写 C 程序;你可以制作一个像

这样的shell脚本
#!/bin/sh
find $* -type f | wc -l

这比你的 C 程序更短(但不慢);在 C 中编写动态构建的命令字符串时要害怕code injection(对于systempopen

关于 C 中的字符串操作,了解 snprintf(3)(但避免使用 sprintf),或者在带有 glibc 的 Linux 上,了解 asprintf(3)

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多