die Rückgabewerte prüfen fread und fwrite

#include <stdio.h>
#include <stdlib.h>

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)) > 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;
}

EDIT: ich habe aktualisiert, der code
ich habe einige Zweifel:

1) muss ich überprüfen den Rückgabewert von fread, weil - zum Beispiel - wenn Byte 0 werden aufgrund eines Fehlers, 0 geschrieben wird in die Datei kopiert.
Aber meine Frage ist: wie ist es zu tun? Da fread kann 0 zurück, sondern können sich auch wieder einen kurzen Wert ....

2) wie können, Lesen Sie gehen Sie durch die Datei? Wenn ich kopieren Sie eine 5 MB-Datei, wie kann fread bewegen sich von 1 MB in 1-MB-ohne etwas sagen zu Ihr "hey Sie haben, um Ihren offset von 1MB nach der 1MB hast du einfach nur kopiert"?

3) warum nicht, deaktivieren Sie den Puffer nach jedem Gebrauch? Ich meine so etwas wie:

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));
}
versuchen Sie die Speicherung in size_t statt eines int
stack-überlauf 🙁
Ich in der Regel verwenden Sie fread(buffer, Dateigröße, 1, file_to_copy), und überprüfen Sie die Rückgabe von fread, ob gleich 1

InformationsquelleAutor polslinux | 2012-06-15

Schreibe einen Kommentar