title: How to send file and filename through socket in C?
body: <p>I am trying to send a file and its name through a socket in C.</p>
  <p>The relevant server code is:</p>
  <pre><code>char file[18];
      memset(file, 0, 18);
      file[17] = '\0';
      int recvd =  recv(newsock, file, 16, 0);
  
  char local_file_path[200];
  memset(local_file_path, 0, 200);
  
  if(recvd == -1 || recv == 0) {
      fprintf(stderr, &quot;File name not received&quot;);
      continue;
  }
  
  strcat(local_file_path, &quot;/home/ubuntu/results/&quot;);
  strcat(local_file_path, file);
  FILE* fp = fopen(local_file_path, &quot;wb&quot;);
  
  char buffer[4096];
  while(1)
  {
      recvd =  recv(newsock, buffer, 4096, 0);
      fwrite(buffer, sizeof(char), recvd, fp);
      if(recvd == -1 || recvd == 0) {
          fclose(fp);
          break;
      }
  }
  close(newsock);
  }
  close(servSock);
  </code></pre>
  <p>The relevant client code is:</p>
  <pre><code>char* my_16_long_fname = &quot;filename1234.txt&quot;
  int ret = send(sock, my_16_long_file_fname, strlen(my_16_long_fname), 0)
  </code></pre>
  <p>This code, however, has been creating lots of undefined behaviour such as:
  1.Receiving garbage filenames filled with garbage
  2.Receiving empty files (so a name with nothing inside - could be some other bug but possibly due to this)</p>
  <p>I have thought about a few solutions:</p>
  <p>1.Diferentiate file types by signature/header and generate a file name on the server side. Besides this being a cheap solution which doesn't teach me how to actually solve the problem, it doesn't work with the logic i'm using, where sometimes I send error codes instead of file names after opening the socket.</p>
  <p>2.Iterate over the recv'd buffer on the first call to recv until I encounter a '\0' character. Then write the remainder of the buffer as binary data and keep on receiving data as usual.</p>
  <p>Is this the most efficient/simplest and solid solution to this issue, which will prevent any undefined behaviour?</p>