add a dot to a string using C
i want to add "/." to a file name, for example,
i have file name "abc", i want to get a name "abc/.abc", how to do it in C? strcpy("/.",name) and strcat("开发者_StackOverflow中文版/.",name) returned segmentation fault.Thanks
The first parameter to strcat
must be a modifiable string with enough space allocated to hold the resulting string and the terminating zero byte. The first parameter to strcpy
must point to allocated, modifiable memory with sufficient space to hold the resulting copy of the string and the terminating zero byte. In both of your examples, you have passed a constant as the first parameter.
Here's some example code to do what you want:
char* SlashDotter(const char* in)
{ // turn <string> into <string>/.<string> -- caller must free returned string
char *out = malloc(strlen(in)*2 + 3); // two copies of input, /, ., and nul
strcpy(out, in);
strcat(out, "/.");
strcat(out, in);
return out;
}
asprintf() can be used to allocate a string and fill it's contents.
on linux systems "man asprintf" will give you a description of how the function works otherwise use google to get help from other places.
精彩评论