如何在System()命令中使用String

时间:2014-03-07 12:18:42

标签: c char wget strcpy strcat

我想为wget制作一个程序,询问你要从哪个URL下载然后下载,但我不知道如何添加字符串“wget”和url并将其放入系统()命令。我知道有几种可能性来添加字符串,但没有什么对我有用。请你帮助我好吗? (代码应如下所示:)

char url[32];
char wget[32];
scanf("%s", &url);
strcpy(wget, "wget");
strcat(wget, url);
system(wget);

3 个答案:

答案 0 :(得分:1)

scanf("%s", &url);&&符号,因为它不是必需的。 url本身是scanf()所需数组的基址。

数组基本上衰减为指针,因此不需要在数组上使用&运算符来获取指针。如果你认为你有一个数组但实际上有一个指针,那就太危险了。

答案 1 :(得分:1)

其他人已经比我更快地指出了丢失的空间,但是你的代码实际上有更多的“错误”,所以如果你原谅我,我将转换到教程模式一两分钟。

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

// The maximum allowed length of an input line, including the newline.
// Longer lines result in an error message.
const size_t INPUTMAXSIZE = 32;

int main()
{
    // You can change the command at will. Length is dynamic.
    // Do not forget the space at the end.
    char * command = "wget ";

    char parameter[INPUTMAXSIZE];
    char * ptr;

    // Using fgets, which allows us to avoid buffer overflow.
    if ( fgets( parameter, INPUTMAXSIZE, stdin ) == NULL )
    {
        puts( "Error while reading input." );
        exit( EXIT_FAILURE );
    }

    // fgets stores the newline as well
    if ( ( ptr = strchr( parameter, '\n' ) ) != NULL )
    {
        // Replace newline with terminating null
        *ptr = 0;
    }
    else
    {
        // Input longer than INPUTMAXSIZE
        puts( "URL too long." );
        exit( EXIT_FAILURE );
    }

    // Allocating the buffer memory dynamically allows us to avoid
    // a second magic number. Re-using 'ptr'.
    if ( ( ptr = malloc( strlen( command ) + strlen( parameter ) + 1 ) ) == NULL )
    {
        puts( "Memory allocation failed." );
        exit( EXIT_FAILURE );
    }

    sprintf( ptr, "%s%s", command, parameter );

    printf( "system( \"%s\" ) returned %d.\n", ptr, system( ptr ) );

    free( ptr );

    return( EXIT_SUCCESS );
}
  • 始终以完整,可编辑的形式提供代码。
  • 尽可能减少“魔术数字”的使用。
  • 尽可能使用常量。
  • 面对意外/格式错误的输入,使代码稳定。失败是错误的,倾销核心不是。
  • 执行检查您正在使用的可能失败的功能的返回代码。

我不是说上面的代码是完美的,但我认为那里有一两节课。我希望它有所帮助。

答案 2 :(得分:0)

您需要wgeturl之间的空格,因此请使用strcat,而不是使用sprintf,如下所示:

  int main ()
    {
        char url[32];
        scanf("%s", url);
        int len=strlen(url)+4+2; //4 for wget and 2 for space and safe
        char buffer[len];
        sprintf(buffer,"wget %s",url);
        system(buffer);
    }

如果我输入网址www.google.com,那么strcat之后的最终命令将成为

wgetwww.google.com

无效,但应为wget www.google.com

相关问题