【问题标题】:How to get the arguments with the spaces from command line in C without garbage如何在没有垃圾的情况下从 C 中的命令行获取带有空格的参数
【发布时间】:2015-06-23 05:50:35
【问题描述】:

我正在尝试获取命令行参数以在 exec 中使用它 但我的代码无法正常工作,因为它返回垃圾作为输出。 (我是 ubuntu 用户)
到目前为止,这是我所做的:

    #include <stdio.h>
    #include <unistd.h>
    #include <string.h>

    int main(int argc,char *argv[]){

        char command[1024];
        int i;      
        fflush(stdin); // i try to empty the buffer  

         for ( i = 1; i < argc; ++i) {
            strcat(command, argv[i]);
            strcat(command," ") ; //here i try to copy the arguments
        }
            printf("%s\n",command);

    return 0;
    }

编译后在终端的输出是:

ubuntu-gnome@ubuntu-gnome:~/Desktop$ ./1 theo psallidas
����*theo psallidas

【问题讨论】:

  • fflush(stdin); 一方面你没有使用stdin,另一方面fflush 用于输出流。
  • 你没有初始化command,所以它的内容是垃圾。将argv[1]添加到数组后,其内容为garbage + argv[1]。

标签: c command arguments line


【解决方案1】:

您需要一个以NUL 结尾的字符串才能使用srtcat

strcat() 函数应附加一个由 指向的字符串的副本 s2(包括终止的空字节)到字符串的末尾 由 s1 指向。 s2 的初始字节覆盖空字节 s1 结束。 如果复制发生在重叠的对象之间, 行为未定义。

char command[1024];

应该是

char command[1024] = "";

fflush(stdin); 是未定义的行为(但您根本不需要这一行)。

【讨论】:

  • 哦,不!应该是""!或者,更有效的是,只需 char command[1024]; command[0] = 0;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 2021-01-27
  • 2014-04-05
相关资源
最近更新 更多