我有两个相等的字符串,我需要删除其中一个的一部分,并将其存储在另一个字符串中。
我的代码无法正常工作:
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;
}
这是预期的输出:
./imgtools mysuperimage.img
mysuperimage.img
mysuperimage
这是实际输出:
./imgtools mysuperimage.img
mysuperimage
mysuperimage
我怎样才能解决这个问题?
您需要复制argv[1]
,如果您有两个指向同一字符串的指针,那么它们自然会打印出相同的内容:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句