strtok() を使用して簡単な URL パーサーを作成しました。ここにコードがあります
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *protocol;
char *host;
int port;
char *path;
} aUrl;
void parse_url(char *url, aUrl *ret) {
printf("Parsing %s\n", url);
char *tmp = (char *)_strdup(url);
//char *protocol, *host, *port, *path;
int len = 0;
// protocol agora eh por exemplo http: ou https:
ret->protocol = (char *) strtok(tmp, "/");
len = strlen(ret->protocol) + 2;
ret->host = (char *) strtok(NULL, "/");
len += strlen(ret->host);
//printf("char at %d => %c", len, url[len]);
ret->path = (char *)_strdup(&url[len]);
ret->path = (char *) strtok(ret->path, "#");
ret->protocol = (char *) strtok(ret->protocol, ":");
// host agora é por exemplo address.com:8080
//tmp = (char *)_strdup(host);
//strtok(tmp, ":");
ret->host = (char *) strtok(ret->host, ":");
tmp = (char *) strtok(NULL, ":");
if(tmp == NULL) {
if(strcmp(ret->protocol, "http") == 0) {
ret->port = 80;
} else if(strcmp(ret->protocol, "https") == 0) {
ret->port = 443;
}
} else {
ret->port = atoi(tmp);
}
//host = (char *) strtok(NULL, "/");
}
/*
*
*/
int main(int argc, char** argv) {
printf("hello moto\n");
aUrl myUrl;
parse_url("http://teste.com/Teste/asdf#coisa", &myUrl);
printf("protocol is %s\nhost is %s\nport is %d\npath is %s\n", myUrl.protocol, myUrl.host, myUrl.port, myUrl.path);
return (EXIT_SUCCESS);
}
ご覧のとおり、私は strtok() をよく使うので、URL を「スライス」できます。http や https 以外の URL をサポートする必要はないので、この方法ですべての問題が解決します。私の懸念は(これは組み込みデバイスで実行されています)-メモリを無駄にしていますか?のようなものを書くとき
ret->protocol = (char *) strtok(tmp, "/");
そして、後で呼び出します
ret->protocol = (char *) strtok(ret->protocol, ":");
最初に保持されたポインタ ret->protocol はメモリに残りますか? 最初の呼び出しを tmp ポインターに設定し、ret->protocol を文字列の右側の部分に指定して strtok を呼び出し (2 番目の呼び出し)、次に free(tmp) を呼び出す必要があるのではないかと考えました。
strtok を使用する最良の方法は何ですか?