Reputation: 39
i wanted to make a program for wget which asks you from which URL you want do download and then download, but i don't know how to add the string "wget" and the url and put it in the system() command. I know there are several possibilities to add strings, but nothing worked for me. Could you please help me? (The code should look like this:)
char url[32];
char wget[32];
scanf("%s", &url);
strcpy(wget, "wget");
strcat(wget, url);
system(wget);
Upvotes: 0
Views: 468
Reputation: 25905
You require a space between wget
and url
, so rather than use strcat
just use sprintf
as follows:
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);
}
In your case if i enter url www.google.com
then final command after strcat
become
wgetwww.google.com
which is not valid but it should be wget www.google.com
Upvotes: 0
Reputation: 70372
Others have pointed out the missing space faster than I did, but there is actually much more "wrong" with your code, so if you excuse me I'll switch to tutorial mode for a minute or two.
#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 );
}
I don't say my code above is perfect, but I think there's a lesson or two in there. I hope it helps.
Upvotes: 1
Reputation: 12658
scanf("%s", &url);
strip of &
ampersand as it is not required. url
itself is base address of the array needed for scanf().
Arrays basically decays to pointers, so there is no need to use the &
operator on an array to get a pointer. It can be dangerous if you think you have an array but actually have a pointer.
Upvotes: 1