0

My overall goal is to copy bits from one file to another file. In fact, the code that I have written does work, except that it seems it always adds the byte "0xff" to the very end of the file.

Here is my code:

#include <iostream>
#include <filesystem> //reads file size
#include <fstream> //opens the file and other magic

using std::cout, std::cin, std::endl;
using std::ofstream, std::ifstream, std::ios;

int main() {
    ifstream inFile("/home/user/text.txt", ios::binary | ios::in);
    ofstream outFile("/home/user/text.output", ios::binary | ios::out);
    char byte;
    inFile.seekg(0);
    while (!inFile.eof()) {
        byte = inFile.get();
        outFile << byte;
    }
    inFile.close();
    outFile.close();
    return 0;
}

To see the byte difference, I put in the command hexdump /home/user/text.txt and then did hexdump /home/user/text.output. The only difference between the two files is the output file has 1 extra byte whos hex is 0xff.

I have tested this with multiple types of files, including regular text files and binary files. Both result the same.

I have no idea what could be causing this problem, as once the program has reached the end of file (eof), it writes nothing more to outFile, so I am lost as how anything could be writing to the file.

  • `eof()` is only set after a read fails, so in the last loop iteration `get()` fails and returns `EOF` (`-1` as `int`) and sets `eof()` to true, you write that `EOF` to `outFile` and loop ends. Use `if (inFile.get(byte))` instead. Also, you should probably use `outFile.put()` instead of `operator <<`, the latter may change `\n` into `\r\n` on Windows. – Yksisarvinen Apr 07 '22 at 22:07
  • One byte at a time? Really? There is an overhead to reading a file regardless of the transaction size. Overhead can consist of waiting for the hard drive motor to get up to speed, reading the directory on the hard drive, seeking the read head and write head to the proper locations. The transaction is more efficient with more data. One transaction of 1024 bytes is more efficient than 1024 transaction of 1 byte. – Thomas Matthews Apr 07 '22 at 22:34

0 Answers0