仅打印出所需长度的指针
我有一个像这样的 C 函数..
func(uint8_t *key,uint8_t keylen) {
FILE *fk;
fk=fopen("akey","wb");
fwrite((char *)key,keylen,1,fk);
puts((char *)key); // for testing
fclose(fk);
sprintf(sstring,"... \"%s\" ... ",(char *)key);
// ...other irrelevant stuff for here
system(sstring);
}
我希望将作为输入提供的密钥用于 将标记为 \"%s\"
的位置放入 sprintf
命令中
输入:
Key=qwerty
输出:
$cat akey
qwerty
以及 puts 的输出((char *)key)
是 -
qwerty�
// include newline character as well
建议我这样做,我尝试过这个(在代码中各自的位置) 但出现分段错误
char *p;
memcpy(p,(char *)key,keylen);
puts((char *)p);
I hava a C function like this ..
func(uint8_t *key,uint8_t keylen) {
FILE *fk;
fk=fopen("akey","wb");
fwrite((char *)key,keylen,1,fk);
puts((char *)key); // for testing
fclose(fk);
sprintf(sstring,"... \"%s\" ... ",(char *)key);
// ...other irrelevant stuff for here
system(sstring);
}
I want the key provided as input to be used at the
place marked \"%s\"
in sprintf
command
Input :
Key=qwerty
Output :
$cat akey
qwerty
and output of puts((char *)key)
is -
qwerty�
// include newline character as well
Suggest me on this , I tried with this (at their respective position in the code)
but getting segmentation fault
char *p;
memcpy(p,(char *)key,keylen);
puts((char *)p);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
%.*s
形式将其打印出来:这里是 关于
printf
的维基百科条目:注意:使用 8 位类型 (
uint8_t
) 表示长度将字符串的长度限制为 255 个字符。更好的是使用size_t
。You could use the form
%.*s
to print it out:Here an extract from the Wikipedia entry on
printf
:NOTE: Using an 8-bit type (
uint8_t
) to represent the length limits the length of the string to 255 characters. Better is to usesize_t
.您需要以空终止字符串(添加尾随“\0”字节)或使用 %ns(如 qwerty 的“%.5s”)。首选空终止。
You need to null-terminate your string (add a trailing '\0' byte) or use %ns (like "%.5s" for qwerty. Null termination is preferred.
sprintf
需要一个以 0 结尾的字符串。您的应用程序中可能并非如此。关于使用 memcpy - 您需要首先分配内存。还要确保检查错误,例如是否fk != NULL
内存分配示例:
sprintf
expects a 0-terminated string. That might not be the case in your application. With regard to using memcpy - you need to allocate memory first. Also make sure you check for errors, e.g. whetherfk != NULL
Memory allocation example: