url
Linux C语言实现urlencode和urldecode
urlencode编码的基本规则
- 字符"a"-“z”,“A”-“Z”,“0”-“9”,“.”,“-”,“*”,和"_" 都不被编码,维持原值;
- 空格" “被转换为加号”+"。
- 其他每个字节都被表示成"%XY"格式的由3个字符组成的字符串,编码为UTF-8(特别需要注意: 这里是大写形式的hexchar)。
urlencode编码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
static unsigned char hexchars[] = "0123456789ABCDEF";
/**
* @brief URLEncode : encode the base64 string "str"
*
* @param str: the base64 encoded string
* @param strsz: the str length (exclude the last \0)
* @param result: the result buffer
* @param resultsz: the result buffer size(exclude the last \0)
*
* @return: >=0 represent the encoded result length
* <0 encode failure
*
* Note:
* 1) to ensure the result buffer has enough space to contain the encoded string, we'd better
* to set resultsz to 3*strsz
*
* 2) we don't check whether str has really been base64 encoded
*/
int URLEncode(const char *str, const int strsz, char *result, const int resultsz)
{
int i, j;
char ch;
if(strsz < 0 || resultsz < 0)
return -1;
for(i = 0, j = 0; i < strsz && j < resultsz; i++)
{
ch = *(str + i);
if((ch >= 'A' && ch <= 'Z') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= '0' && ch <= '9') ||
ch == '.' || ch == '-' || ch == '*' || ch == '_')
result[j++] = ch;
else if(ch == ' ')
result[j++] = '+';
else
{
if(j + 3 <= resultsz)
{
result[j++] = '%';
result[j++] = hexchars[(unsigned char)ch >> 4];
result[j++] = hexchars[(unsigned char)ch & 0xF];
}
else
{
return -2;
}
}
}
if(i == 0)
return 0;
else if(i == strsz)
return j;
return -2;
}
// return < 0: represent failure
int main(int argc, char *argv[])
{
int fd = -1;
char buf[1024], result[1024 * 3];
int ret;
int i = 0;
if(argc != 2)
{
printf("please input the encoding filename\n");
return -1;
}
if((fd = open(argv[1], O_RDONLY)) == -1)
{
printf("open file %s failure\n", argv[1]);
return -2;
}
while((ret = read(fd, buf, 1024)) >= 0)
{
if(ret == 0)
break;
ret = URLEncode(buf, ret, result, 1024 * 3);
if(ret < 0)
break;
for(i = 0; i < ret; i++)
printf("%c", result[i]);
}
if(ret < 0)
{
printf("encode data failure\n");
}
close(fd);
return ret;
}
urldecode解码

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



