gpt4 book ai didi

c - 分割字符串而不影响源

转载 作者:行者123 更新时间:2023-11-30 15:37:25 26 4
gpt4 key购买 nike

如何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));
}

最佳答案

你不需要strtokstrrchr可以找到最后一次出现的分隔符:

if((file_format = strrchr(filename, '.')) == NULL)
file_format = ""; /* no delimiter present */
else
++file_format; /* step over the delimiter */

关于c - 分割字符串而不影响源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22238076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com