Reputation: 89
I have two equal strings, I need to delete a portion of one of them, and store it in another.
My code is not working:
int main(int argc, char *argv[])
{
char *imagetmp = argv[1];
char *imagefile = imagetmp;
char *unpackdir = imagetmp;
// Remove substring from char imagefile
char * pch;
pch = strstr (imagefile,".img");
strncpy (pch,"",6);
// Print strings
puts (imagefile);
puts (unpackdir);
return 0;
}
Here is the expected output:
./imgtools mysuperimage.img
mysuperimage.img
mysuperimage
Here is the actual output:
./imgtools mysuperimage.img
mysuperimage
mysuperimage
How can I fix this?
Upvotes: 1
Views: 74
Reputation: 23792
You will need to make a copy of argv[1]
, if you have two pointers to the same string they will naturally print the same:
int main(int argc, char *argv[])
{
char imagefile[100];
if(argc < 2) {
puts("Too few arguments");
return 1;
}
strncpy(imagefile, argv[1], sizeof(imagefile) - 1);
//char *unpackdir = argv[1]; you can use argv[1] directly
// Remove substring from char imagefile
char * pch;
if((pch = strstr (argv[1],".img")))
*pch = 0; //or '\0', just null terminate the string, it's simpler
else
puts("Extension not found");
// Print strings
puts (imagefile);
puts (argv[1]);
return 0;
}
Upvotes: 2