所以我正在编写代码来根据名称创建文件路径。
sprintf(FilePath, "%s/%s", DirPath, FileName);
和
strcpy(FilePath, DirPath);
strcat(FilePath, "/");
strcat(FilePath, FileName);
哪个更快/我应该使用哪个?在这两种情况下,我都分配了足够的内存。
最佳答案
- 不要对任何字符串多次调用
strlen()
- 相反:记住长度并重复使用
- 计算您在字符串中的位置
- 请记住,
strcat()
每次都需要重新扫描目标字符串,只是为了找到其当前结尾 leading to quadratic behaviour
static char *construct_path(char*pathname,char*filename)
{
char *result;
size_t plen, flen;
plen = strlen(pathname);
flen = strlen(filename);
result= malloc(plen+flen+2);
if(!result)return NULL;
memcpy(result, pathname, plen);
result[plen]='/';
memcpy(result+plen+1, filename, flen);
result[plen+1+flen] = 0;
return result;
}
<小时/>
通常,调用者可能已经知道strlen()
,例如常量路径。
关于c - 如果我正在创建文件路径,哪个应该更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55561107/