使用换行符在C中编码URL?

时间:2016-07-23 01:52:51

标签: c url-encoding

我已经在互联网上找到了这个网址编码器并进行了一些小改动,但是当我做这样的事情的时候:

char encodedWord[100];
const char* word = "Stack\nOverflow";

urlencode(encodedWord, word);

输出将是这样的: " Stack0X8.51EE00001674P-1022Overflow"而不是堆栈溢出之间的x0A。

为什么要输出?我假设因为" EE0000 "部分出现问题,字符转换为字符。

如何让我的编码器对特殊字符更加友好?即" \ n,\ r,\ r"。

功能

int urlencode(char *dest, const char *src)
{
    /* urlencode all non-alphanumeric characters in the C-string 'src'
       store result in the C-string 'dest'
       return the length of the url encoded C-string
    */
    char *d;
    int i;
    for(i=0, d=dest; src[i]; i++) {
        if(isalnum(src[i]) || isdigit(src[i])) {
            *(d++) = src[i];
        } else {
            snprintf(d, 4, "%%%02X", src[i]);
            d += 3;
        }
    }   
    *d = 0;
    return d-dest;
}

系统

Windows 10 32位 Mingw32(gcc 5.1.0)

制作文件

#OBJS specifies which files to compile as part of the project

OBJS = $(wildcard ./src/*.c)

#CC specifies which compiler we're using
CC = gcc

#INCLUDE_PATHS specifies the additional include paths we'll need
INCLUDE_PATHS = 

#LIBRARY_PATHS specifies the additional library paths we'll need
LIBRARY_PATHS = 

#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
# -Wl,-subsystem,windows gets rid of the console window
COMPILER_FLAGS = -Wall -Wl,-subsystem,console -std=c99

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lmingw32 -lws2_32 -lwininet -s -lshlwapi

#OBJ_NAME specifies the name of our executable
OBJ_NAME = project

#This is the target that compiles our executable
all : clean build

build:
    cls
    $(CC) $(OBJS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(COMPILER_FLAGS) $(LINKER_FLAGS) -o $(OBJ_NAME)

clean:
    del -f $(OBJ_NAME).exe

1 个答案:

答案 0 :(得分:3)

urlencode函数运行正常,问题在于如何打印输出。我正在写作

  

0X8.51EE00001674P-1022是一个十六进制浮点数,是您期望从%A printf说明符中看到的。

当我看到正确的输出在该确切位置有%0A时。这意味着您错误地将非常量字符串作为printf的第一个参数传递。不要做printf(encodedWord);你应该使用printf("%s", encodedWord)代替。