简体   繁体   中英

Copy part of file in C++

I'm currently busy with a project in which I have to copy a part from a file to another file, so I made a code for that using fread and fwrite. But I came across a problem: for testing purposes I made a code which should copy a whole file, but somehow the code creates copies that are larger than the original file. See the code I made below

             FILE *base_file;
             FILE *new_file;
             fpos_t curpos;
             int tmp;

             // Open the base file
             fopen_s(&base_file, "C:/base.dat", "rb");
             // Open the file which should contain the copy
             fopen_s(&new_file, "C:/new.dat", "w");

             // Get the filesize
             fseek(base_file, 0, SEEK_END);
             fgetpos(base_file, &curpos);
             fseek(base_file, 0, SEEK_SET);

             //Read and copy (it seems to go wrong here)
             for(int i = 0; i < curpos; i++){
                 fread (&tmp, 1, 1, base_file);
                 fwrite(&tmp, 1, 1, new_file);
             }

             fclose(base_file);
             fclose(new_file);

The base file is 525 kb, and the newfile is 527kb. As far as I could see the parts where this problem occurs is after parts where there are 7 nullbytes, and the copy somehow has added a '0D'(in Hex) after these parts. In ascii the '0D' character is a 'carriage return'. I was wondering what could be the reason that my copy code adds carriage returns into the file? As far as I know this script should just work as I just read the basefile, and directly copy it to the newfile, and the basefile doesn't contain these carriage returns.

You're opening the destination file in text mode, instead of binary mode, so the newline translation happens behind your back. Change the mode to "wb" .

Other notes:

  1. Use streams rather than stdio.
  2. Don't write byte-for-byte. Use a larger buffer, your method will take forever for larger files.

可以用“ wb”代替“ w”吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM