hiredis存储二进制文件,比如char数组的方法,例如:
char value[20]={0}
value[0]=’a’
value[15]=’b’
这种情况直接调用redisCommand(c, “set key %s”,value),是不可行的,因为遇到结束符’/0’会停止,但redis是二进制安全的,hiredis也提供了二进制安全的方法,即redisCommand(c, “set key %b”,value,20),一个%b对应一个char指针加缓存的长度,下面给出完整代码:
#include <stdio.h>
#include <string.h>
#include “hiredis.h”
int main()
{
redisContext *c = redisConnect(“127.0.0.1”, 9600);
redisReply *reply = (redisReply *)redisCommand(c, “AUTH %s”, “123456”);
char value[20]={0};
value[0]=’a’;
value[19]=’b’;
reply = redisCommand(c, “set %b %b”, “keyb”,(size_t) 4,value,(size_t) 20);
reply = redisCommand(c, “get keyb”);
for(int i=0;i<reply->len;i++)
{
if(*(reply->str+i)==0)
printf(“//x00”);
else
printf(“%c”,*(reply->str+i));
}
print(“/n”)
freeReplyObject(reply);
redisFree(c);
return 0;
}
输出结果:
a/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00b
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/288507.html