title: check return value fread and fwrite
body: <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(int argc, char *argv[]){
  
    if(argc != 3){
      printf("Usage: ./copy filename newfile\n");
      exit(1);
    }
  
    int bytes;
    long file_size, file_copied_size;
    FILE *file_to_copy, *new_file;
  
    if((file_to_copy = fopen(argv[1], "rb")) == NULL){
      printf("File cannot be opened - read\n");
      exit(1);
    }
    if((new_file = fopen(argv[2], "wb")) == NULL){
      printf("File cannot be opened - write\n");
      exit(1);
    }
  
    fseek(file_to_copy, 0, SEEK_END);
    file_size = ftell(file_to_copy);
    rewind(file_to_copy);
  
    char *buffer = malloc(1024 * 1024); /* Imposto un buffer di 1MB per maggiore efficienza */ 
    if(!buffer){
      printf("Errore allocazione memoria\n");
      fclose(file_to_copy);
      fclose(new_file);
      exit(1);
    }
  
     /* In questo modo copio file grandi 1MB alla volta così il trasferimento è più veloce ed efficiente inoltre fread() ritorna 0 quando c'è un errore o quando incontra EOF */
    //while ((bytes=fread(buffer, 1, sizeof(buffer), file_to_copy)) &gt; 0){
    while (!feof(file_to_copy)){
      bytes = fread(buffer, 1, sizeof(buffer), file_to_copy);
      fwrite(buffer, 1, bytes, new_file);
      if(ferror(new_file)){
        perror("Errore scrittura"); /* perror printa anche l'errore che ferror ha incontrato */
        fclose(file_to_copy);
        fclose(new_file);
        exit(1);
      }
    }
  
    fseek(new_file, 0, SEEK_END);
    file_copied_size = ftell(new_file);
    rewind(new_file);
    if(file_size != file_copied_size){
      printf("Il file %s non è stato copiato correttamente\n", argv[2]);
    }
    else{
      printf("File successfully copied :)\n");
    }  
    fclose(file_to_copy);
    fclose(new_file);
    free(buffer);
  
    return EXIT_SUCCESS;
  }
  </code></pre>
  
  <p><strong>EDIT: i've updated the code</strong><br>I have some doubts:<br>
  1) I have to check the return code of fread because - for example - if bytes become 0 due to an error, 0 will be written into the copied file.<br>But my question is: how to do it?  Because fread <em>can</em> return 0 but can also return <em>a short value</em> ....<br>
  2) how can read go throught the file? If i copy a 5MB file how can fread move from 1MB in 1MB without something that say to it "hey you have to put your offset 1MB after the 1MB you've just copied"?<br>
  3) why not to clear the buffer after every use? I mean something like:</p>
  
  <pre><code>while (!feof(file_to_copy)){
          bytes = fread(buffer, 1, sizeof(buffer), file_to_copy);
          fwrite(buffer, 1, bytes, new_file);
          memset(buffer, 0, sizeof(buffer));
  }
  </code></pre>