[英]sprintf doesn't add strings with escape character
I have this function which gets the given directory and filename and concat it by checking if the end of the directory contains / character and concatenating the string's for condition.我有这个 function,它获取给定的目录和文件名,并通过检查目录末尾是否包含 / 字符并连接字符串的 for 条件来连接它。 My problem is that when i give the function a directory name and filename if the filname has \ it does not concat the string correctly.
我的问题是,当我给 function 一个目录名和文件名时,如果文件名有 \,它不会正确连接字符串。 but when if the file does not contain any \ the output will be given.How can i fix the issue?.
但是当文件不包含任何\时,将给出 output。我该如何解决这个问题?。
Here is my C Code.这是我的 C 代码。
char * find_endwith_slash(char *dir_path, char *file_name)
{
char full_path[1024];
if (dir_path[strlen(dir_path) - 1] != '/')
{
sprintf(full_path, "%s/%s", dir_path, file_name);
}
else
{
sprintf(full_path, "%s%s", dir_path, file_name);
}
char * full_name = malloc(strlen(full_path) * sizeof(char));
full_name = strdup(full_path);
return full_name;
}
A more proper approach to conditionally concatenating path and file name:有条件地连接路径和文件名的更合适的方法:
char * find_endwith_slash_alt(const char *dir_path, const char *file_name) {
size_t d_length = strlen(dir_path);
size_t f_length = strlen(file_name);
if (d_length > 0 && dir_path[d_length-1] == `/`) {
d_length--;
}
char *both = malloc(d_length + 1 + f_length + 1);
if (both) {
memcpy(both, dir_path, d_length);
dir_path[d_length] = '/';
memcpy(both + d_length + 1, file_name, f_length + 1);
}
return both;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.