Split string without affecting the source

How do I strtok filename so that the original string won't get affected?

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

Answers


You don't need strtok, strrchr can find the last occurrence of the delimiter character:

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

You copy it first. Then you run strtok on it which replaces occurrences of the delimter character with nulls.

If you want to get the parts of the string out without modifying the original, or copying it (I assume you want to copy the pieces into a destination string however) then you simply iterator over it until you reach the next delimiter, keeping track of the start and end positions and copy those.

You cannot point to the first half of the original string, and expect to get a partial result out without modifying or copying it.


Need Your Help

Using drag and drop to build an image

javascript jquery ajax html5 drag-and-drop

I'm trying to build a cake dragging some items to it, and then that I can download the image with all of the items dragged, But I don't want the image of the item disappears , I want that count every