title: Replace string in binary file
body: <p>I am trying to write a *nix program that copies itself and replaces a string inside the binary. The copy process doesn't seem to work though.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;fcntl.h&gt;
  
  #define BUFSIZE 10
  #define FILENAME "token"
  
  void findstring(const char *exe, const char* str)
  {
      char buf[BUFSIZE];
      int line_num = 1;
      int i = 0, find_result = 0;
      FILE *fp = fopen(exe, "rb");
      if(fp == NULL)
          exit(-1);
  
      FILE *out = fopen("out", "wb");
      if(out == NULL)
          exit(-1);
  
      while(fgets(buf, BUFSIZE, fp) != NULL) {
          if((strstr(buf, str)))
          {
              printf("A match found on line: %d\n", line_num);
              printf("\n%s\n", buf);
              find_result++;
  
              // reverse "token" string in the output
              for(i = 0; i&lt; BUFSIZE; i++)
              {
                  if(strstr(&amp;buf[i], "t") != NULL)
                      buf[i] = 'n';
                  else if(strstr(&amp;buf[i], "o") != NULL)
                      buf[i] = 'e';
                  else if(strstr(&amp;buf[i], "k") != NULL)
                      buf[i] = 'k';
                  else if(strstr(&amp;buf[i], "e") != NULL)
                      buf[i] = 'o';
                  else if(strstr(&amp;buf[i], "n") != NULL)
                      buf[i] = 't';
              }
          }
          line_num++;
  
          fputs(buf, out);
      }
  
      if(find_result == 0) {
          printf("\nSorry, couldn't find a match.\n");
      }
  
      fclose(fp);
      fclose(out);
  }
  
  int main(int argc, char **argv, char **envp)
  {
  //    argv[1] = FILENAME;
  
      char buf[1024];
      int fd, rc;
  
      findstring(argv[0], "token");
  
      if(argc == 1) {
          printf("\n\n%s [file to read]\n\n", argv[0]);
          exit(1);
      }
  
      printf("FILENAME macro = %s", FILENAME);
  
      if(strstr(argv[1], "token") != NULL) {
          printf("\n\nYou may not access '%s'\n\n", argv[1]);
          exit(2);
      }
  
      fd = open(argv[1], O_RDONLY);
      if(fd == -1) {
          printf("\n\nUnable to open %s\n\n", argv[1]);
          exit(3);
      }
  
      rc = read(fd, buf, sizeof(buf));
  
      if(rc == -1) {
          printf("\n\nUnable to read fd %d\n\n", fd);
          exit(4);
      }
  
      write(1, buf, rc);
  
      return 0;
  }
  </code></pre>
  
  <p>"Token" string should be reversed in the output binary ("nekot"), with the <em>findstring</em> function responsible of performing this task.
  It is also worth noting that the number of matches found strictly depends on the BUFSIZE constant.</p>
  
  <p>What is this code missing?
  Thanks</p>