title: Copying a file in C with fwrite
body: <p>I am new to C and was trying to write a program just to copy a file so that I could learn the basics of files. My code takes a file as input, figures out its length by subtracting its start from its end using fseek and ftell. Then, it uses fwrite to write, based on what I could get from its man page, ONE element of data, (END - START) elements long, to the stream pointed to by OUT, obtaining them from the location given by FI. The problem is, although it does produce "copy output," the file is not the same as the original. What am I doing wrong? I tried reading the input file into a variable and then writing from there, but that didn't help either. What am I doing wrong? 
  Thanks</p>
  
  <pre><code>int main(int argc, char* argv[])
  { 
      FILE* fi = fopen(argv[1], "r"); //create the input file for reading
  
      if (fi == NULL)
          return 1; // check file exists
  
      int start = ftell(fi); // get file start address
  
      fseek(fi, 0, SEEK_END); // go to end of file
  
      int end = ftell(fi); // get file end address
  
      rewind(fi); // go back to file beginning
  
      FILE* out = fopen("copy output", "w"); // create the output file for writing
  
      fwrite(fi,end-start,1,out); // write the input file to the output file
  }
  </code></pre>
  
  <p>Should this work?</p>
  
  <pre><code>{
      FILE* out = fopen("copy output", "w");
      int* buf = malloc(end-start);  fread(buf,end-start,1,fi);
      fwrite(buf,end-start,1,out);
  }
  </code></pre>