使用安全function将字符串添加到C中的字符串
我想将文件名复制到字符串并将“.cpt”附加到它。 但我无法使用安全函数(strcat_s)执行此操作。 错误:“字符串未终止!”。 我确实设置’\ 0’,如何使用安全function解决这个问题?
size = strlen(locatie); size++; nieuw = (char*)malloc(size+4); strcpy_s(nieuw, size, locatie); nieuw[size] = '\0'; strcat_s(nieuw, 4, ".cpt"); // <-- crash puts(nieuw);
_s函数的size
参数是目标缓冲区的大小,而不是源的大小。 该错误是因为第一个字符中的nieuw
中没有空终止符。 试试这个:
size = strlen(locatie); size++; int nieuwSize = size + 4; nieuw = (char*)malloc(nieuwSize ); strcpy_s(nieuw, nieuwSize, locatie); nieuw[size] = '\0'; strcat_s(nieuw, nieuwSize, ".cpt"); // <-- crash puts(nieuw);
为什么不
size = strlen(locatie); size++; nieuw = (char*)malloc(size+6); strcpy_s(nieuw, size, locatie); strcat_s(nieuw, 4, ".cpt"); puts(nieuw); nieuw[size + 5] = '\0';
看看asprintf
。 它允许您打印到像printf这样的字符串
size = strlen(locatie); size++; nieuw = (char*)malloc(size+4); strcpy_s(nieuw, size, locatie); nieuw[size] = '\0'; strcat_s(nieuw, size, ".cpt"); puts(nieuw)
;
也许一些标准解决方案
const char * const SUFFIX = ".cpt"; size = strlen(locatie) + strlen(SUFFIX) + 1; // +1 for NULL nieuw = (char*)malloc(size); snprintf(nieuw, size, "%s%s", locatie, SUFFIX);
#include #include #include int main(void) { char old[] = "hello"; size_t size = strlen(old) + 5;; char *new_name = (char*)malloc(size); new_name[size-1] = '\0'; strcpy_s(new_name, size, old); strcat_s(new_name, size, ".cpp"); printf("%s\n", new_name); return 0; }