Skip to content

Instantly share code, notes, and snippets.

@yukioc
Created August 14, 2010 13:33
Show Gist options
  • Select an option

  • Save yukioc/524304 to your computer and use it in GitHub Desktop.

Select an option

Save yukioc/524304 to your computer and use it in GitHub Desktop.
duplicate and deescape string
char* destrndup(const char*s, size_t n){
if (s==NULL)return NULL;
char *ret(new char[n+1]),*t(ret),*p;
const char *e(&s[n]);
for(;*s!='\0'&&s!=e&&n>0;--n,++s,++t){
// printf("estrndup: s=%c\n",*s);
if(*s=='\\'){
++s;--n;
switch(*s){
case 'a':*t='\a';break;
case 'b':*t='\b';break;
case 'f':*t='\f';break;
case 'n':*t='\n';break;
case 'r':*t='\r';break;
case 't':*t='\t';break;
case 'v':*t='\v';break;
case '?':*t='\?';break;
case '\\':*t='\\';break;
case '\'':*t='\'';break;
case '\"':*t='\"';break;
case 'x':*t=(char)strtol(s+1,&p,16);s=p-1;break;
default:
if(*s>='0'&&*s<='7'){ *t=strtol(s,&p,8);s=p-1;break; }
else {
delete ret;
throw std::logic_error("estrndup: contained wrong escaped character");
}
}
}else if(*s=='"'){
delete ret;
throw std::logic_error("estrndup: contained un-escaped '\"'");
}else{
*t=*s;
}
}
*t='\0';
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment