我如何strtok
文件名,以便原始字符串不会受到影响?
void generate_header(int sock, char* filename, int response_code) {
char buffer[BUFLEN];
// For Content-Type generation
char *file_format;
const char delimiter[2] = ".";
file_format = strtok(filename, delimiter);
file_format = strtok(NULL, delimiter);
// Generate response code
/*
........ ommited ..........
*/
// Generate Content-Type
if (strcmp(file_format, "html") == 0 || strcmp(file_format, "htm") == 0) {
strncat(buffer, "Content-Type: text/html\n", sizeof(buffer) - strlen(buffer) - 1);
}
else if (strcmp(file_format, "txt") == 0) {
strncat(buffer, "Content-Type: text/plain\n", sizeof(buffer) - strlen(buffer) - 1);
}
else if (strcmp(file_format, "jpg") == 0 || strcmp(file_format, "jpeg") == 0) {
strncat(buffer, "Content-Type: image/jpeg\n", sizeof(buffer) - strlen(buffer) - 1);
}
else if (strcmp(file_format, "gif") == 0) {
strncat(buffer, "Content-Type: image/gif\n", sizeof(buffer) - strlen(buffer) - 1);
} else {
strncat(buffer, "Content-Type: application/octet-stream\n", sizeof(buffer) - strlen(buffer) - 1);
}
// End
strncat(buffer, "Connection: close\n", sizeof(buffer) - strlen(buffer) - 1);
// Push
write(sock, buffer, strlen(buffer));
}
答案 0 :(得分:1)
您不需要strtok
,strrchr
可以找到最后一个分隔符字符:
if((file_format = strrchr(filename, '.')) == NULL)
file_format = ""; /* no delimiter present */
else
++file_format; /* step over the delimiter */
答案 1 :(得分:0)
首先复制它。然后在其上运行strtok,用空值替换分隔符的出现。
如果你想在没有修改原始文件的情况下获取字符串的部分,或者复制它(我假设你想将这些部分复制到目标字符串中),那么你只需将它迭代到它直到你到达下一个分隔符,跟踪开始和结束位置并复制它们。
您不能指向原始字符串的前半部分,并且期望在不修改或复制它的情况下获得部分结果。