Realize file copy with file operation function

  int nread=0;
   char buff[100];

   while(1)
     {
    
    
        memset(buff,0,sizeof(buff));
        if((nread=fread(buff,1,100,srcfp))==0)  break;

        fwrite(buff,1,nread,dstfp);
     }

  1. At the beginning, the program I wrote by myself was not defined

int nread;

  I originally intended to read 100 bytes from the source file and then write 100 bytes into the target file, but this is wrong. If the data read from the source file does not have 100 bytes, then I write 100 bytes to The target file may be wrong.
So how much should be read and how much should be written. At this time, a counter nread is used.

  2. char buff[100];
Can it be changed to other data types, such as

int buff[100];

  This is possible, because this is to apply for a piece of memory, and then put the read data block into this memory. In other words, the data block read is a string of 0110 (a string of binary numbers), which can be in integer or character type.
  Furthermore, the essence of defining the variable type is to apply for a piece of space from the memory, and put the read data into the applied memory, there is no difference.

  3. Thoughts on the difference between the two reading and writing methods

  3.1 The fread and fwrite functions
  read and write the contents of the file in binary form

  3.2. fprintf and fgets
  read and write the ASCII corresponding to the content of the file.

  In fact, there are no text files and binary files. For computers, they are all a series of binary numbers such as 0110, but what is the binary number stored in the file. It is the binary number corresponding to the data read and written, and the binary number corresponding to ASCII.
  If you use the fgets and fprintf functions to read and write, then the file buffer is the binary number corresponding to the ASCII corresponding to the read and write data.
  If you use the fwrite and fread functions to read and write, it is the binary number corresponding to the data read and written.

Guess you like

Origin blog.csdn.net/qq_43403759/article/details/113102576