title: Saving data sent from client to server into a file has invalid characters
body: <p>I am trying to send a file containing strings from a client to a server, and then have the server save the results received. So far, I have managed to send the data from the client to the server, but when the server saves the results in a text file, it contains invalid characters which are unreadable.  </p>
  
  <p>The contents of the file has around 10 lines of zeros like below (and is highlighted in red) with random characters in between:</p>
  
  <pre><code>POST /apikey=json&amp;command={"Parameter" : "Value"}\00\00\00\00\00\00\00\00\00ð|\00\00\00\00|'^O\00\00ÿÿÿÿ
  </code></pre>
  
  <p>I did a bit of research, and tried using binary mode: (fp = fopen( "testfile.txt" , "wb" ); but that didn't solve it.   </p>
  
  <p><strong>Server</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;signal.h&gt;
  
  #define PORT "3490"  // the port users will be connecting to
  
  #define BACKLOG 10     // how many pending connections queue will hold
  
  void sigchld_handler(int s)
  {
      while(waitpid(-1, NULL, WNOHANG) &gt; 0);
  }
  
  // get sockaddr, IPv4 or IPv6:
  void *get_in_addr(struct sockaddr *sa)
  {
      if (sa-&gt;sa_family == AF_INET) {
          return &amp;(((struct sockaddr_in*)sa)-&gt;sin_addr);
      }
  
      return &amp;(((struct sockaddr_in6*)sa)-&gt;sin6_addr);
  }
  
  int main(void)
  {
      int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
      struct addrinfo hints, *servinfo, *p;
      struct sockaddr_storage their_addr; // connector's address information
      socklen_t sin_size;
      struct sigaction sa;
      int yes=1;
      char s[INET6_ADDRSTRLEN];
      int rv;
  
      memset(&amp;hints, 0, sizeof hints);
      hints.ai_family = AF_UNSPEC;
      hints.ai_socktype = SOCK_STREAM;
      hints.ai_flags = AI_PASSIVE; // use my IP
  
      if ((rv = getaddrinfo(NULL, PORT, &amp;hints, &amp;servinfo)) != 0) {
          fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
          return 1;
      }
  
      // loop through all the results and bind to the first we can
      for(p = servinfo; p != NULL; p = p-&gt;ai_next) {
          if ((sockfd = socket(p-&gt;ai_family, p-&gt;ai_socktype,
                  p-&gt;ai_protocol)) == -1) {
              perror("server: socket");
              continue;
          }
  
          if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &amp;yes,
                  sizeof(int)) == -1) {
              perror("setsockopt");
              exit(1);
          }
  
          if (bind(sockfd, p-&gt;ai_addr, p-&gt;ai_addrlen) == -1) {
              close(sockfd);
              perror("server: bind");
              continue;
          }
  
          break;
      }
  
      if (p == NULL)  {
          fprintf(stderr, "server: failed to bind\n");
          return 2;
      }
  
      freeaddrinfo(servinfo); // all done with this structure
  
      if (listen(sockfd, BACKLOG) == -1) {
          perror("listen");
          exit(1);
      }
  
      sa.sa_handler = sigchld_handler; // reap all dead processes
      sigemptyset(&amp;sa.sa_mask);
      sa.sa_flags = SA_RESTART;
      if (sigaction(SIGCHLD, &amp;sa, NULL) == -1) {
          perror("sigaction");
          exit(1);
      }
  
      printf("server: waiting for connections...\n");
  
      while(1) {  // main accept() loop
          sin_size = sizeof their_addr;
          new_fd = accept(sockfd, (struct sockaddr *)&amp;their_addr, &amp;sin_size);
          if (new_fd == -1) {
              perror("accept");
              continue;
          }
  
          inet_ntop(their_addr.ss_family,
              get_in_addr((struct sockaddr *)&amp;their_addr),
              s, sizeof s);
          printf("server: got connection from %s\n", s);
  
  {
          char buf[1000];
          ssize_t len;
  
          len = recv(new_fd, buf, sizeof(buf) - 1, 0);
          if (len &gt; 0) {
                  buf[len] = '\0';
                  printf("buffer: %s len: %d\n\n", buf, (int)len);
  
                          /* save to file */              
                      FILE *fp;
                      fp = fopen( "testfile.txt" , "wb" ); //b for binary
                      fwrite(buf, 1, sizeof buf, fp);
                      fclose(fp);
  
              }
      }
  
  
  
          if (!fork()) { // this is the child process
              close(sockfd); // child doesn't need the listener
              if (send(new_fd, "I received your message\n", 23, 0) == -1)
                  perror("send");
              close(new_fd);
              exit(0);
          }
          close(new_fd);  // parent doesn't need this
      }
  
      return 0;
  }
  </code></pre>
  
  <p><strong>Client</strong>  </p>
  
  <pre><code>#include &lt;stdio.h&gt; /* printf, sprintf */
  #include &lt;stdlib.h&gt; /* read, write, close */
  #include &lt;string.h&gt; /* memcpy, memset */
  #include &lt;sys/socket.h&gt; /* socket, connect */
  #include &lt;netinet/in.h&gt; /* struct sockaddr_in, struct sockaddr */
  #include &lt;netdb.h&gt; /* struct hostent, gethostbyname */
  #include &lt;unistd.h&gt;
  
  void error(const char *msg) { perror(msg); exit(0); }
  
  int main(int argc,char *argv[])
  {
      /* first what are we going to send and where are we going to send it? */
      int portno =        3490; /* 3490 or 8080 */
      char *host =        "192.168.1.65"; /* localhost: 127.0.0.1 or 192.168.1.65 */
      char *message_fmt = "POST /apikey=%s&amp;command=%s HTTP/1.0\n\n";
  
      struct hostent *server;
      struct sockaddr_in serv_addr;
      int sockfd, bytes, sent, received, total;
      char message[1024],response[4096];
  
      //if (argc &lt; 3) { puts("Parameters: &lt;apikey&gt; &lt;command&gt;"); exit(0); }
  
      /* fill in the parameters */
      sprintf(message,message_fmt,argv[1],argv[2]);
      printf("Request:\n%s\n",message);
  
      /* create the socket */
      sockfd = socket(AF_INET, SOCK_STREAM, 0);
      if (sockfd &lt; 0) error("ERROR opening socket");
  
      /* lookup the ip address */
      server = gethostbyname(host);
      printf("ip address: %s\n\n", host);
      if (server == NULL) error("ERROR, no such host");
  
      /* fill in the structure */
      memset(&amp;serv_addr,0,sizeof(serv_addr));
      serv_addr.sin_family = AF_INET;
      serv_addr.sin_port = htons(portno);
      memcpy(&amp;serv_addr.sin_addr.s_addr,server-&gt;h_addr,server-&gt;h_length);
  
      /* connect the socket */
      if (connect(sockfd,(struct sockaddr *)&amp;serv_addr,sizeof(serv_addr)) &lt; 0)
          error("ERROR connecting");
  
      /* send the request */
  
  /********************************* reading input data and converting into JSOn format ***********************/
     FILE *file = stdin;
      char a[50], b[50];
          while(1 == fscanf(file," %[^,]",a) ) /* Read data until a comma is detected, */
              {
  
                 fgetc( file ); // Ignore , character
  
                 fscanf(file," %[^,]",b); /* Read data until a comma is detected, */
                 fgetc( file ); // Ignore , character
  
          printf("{\"%s\" : \"%s\"}\n",a,b); /* Display results into {"A":"B"} format */
      }
  
  
     ///sprintf(message,message_fmt,a[0],b[0]);
  
  
      //total = strlen(message);
  //printf("sending message %d\n",total);
  sprintf(a, message_fmt,"json","{\"Parameter\" : \"Value\"}\n");
  //total = strlen(a); // this takes the value of 'a' eg: 1, 2, 3, 4, - 'a' will be 1,3 while b=2,4
  total = strlen(message);
      sent = 0;
      do {
          bytes = write(sockfd,a+sent,total-sent);
          if (bytes &lt; 0)
              error("ERROR writing message to socket");
          if (bytes == 0)
              break;
          sent+=bytes;
      } while (sent &lt; total); //while (sent &lt; 0);
      printf("Post request sent \n");
  
      //receive the response
      printf("Receiving response \n");
      memset(response,0,sizeof(response));
      total = sizeof(response)-1;
      received = 0;
      do {
          bytes = read(sockfd,response-received,total-received);
          if (bytes &lt; 0)
              error("ERROR reading response from socket");
          if (bytes == 0)
              break;
          received+=bytes;
      } while(received &lt; total); //while (received &lt; 0);
      printf("Response received\n");
  
      if (received == total)
          error("ERROR storing complete response from socket");
  
      /* close the socket */
      close(sockfd);
  
      /* process response */
      printf("\nServer Response:\n%s\n\n",response);
  
      return 0;
  }
  </code></pre>
  
  <p><strong>Summary</strong><br>
  1- Send a string (eg. Hello World) from client to server<br>
  2- Server reads the string, saves it into a text file<br>
  3- But text file has invalid characters and zeroes instead</p>