1

I have tried two different while loops. I think they have a similar problem. Neither of them terminate or give any output.

The task is to copy (byte for byte) one file into another. The file does not have to have endlines, nor does it have to be a .txt file (it could be .exe...).

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;


int main(int argc, char *argv[])
{
char c, c1, c2;
ifstream inFile;
ofstream outFile;

inFile.open("blackbird.txt");

if (inFile.fail())
{
    cout << "\nThe file was not successfully opened for reading."
    << "\nPlease check that the file currently exists.\n\n";
    exit(1);
}

cout << "\nThe file has been successfully opened for reading.\n\n";


outFile.open("blackbird_copy.txt");

if (outFile.fail())
{
    cout << "The file was not successfully opened for writing" << endl;
    exit(1);
}

cout << "The file has been successfully opened for writing.\n\n";


//outFile << "Hello";

// 1) this loop doesn't terminate. 2) the computer doesn't know what c1     is.
/*
while (inFile.get(c1))
{
    outFile << c1;
    cout << c1;
}
*/



// This one is no better
/*
while (inFile.good())
{
    inFile.get(c);
    outFile << c;
}
*/


inFile.close();
outFile.close();


// read contents of blackbird_copy to check our work.

inFile.open("blackbird_copy.txt");

while (inFile.get(c2))
{
    cout << c2;
}

cout << endl << endl;
return 0;
}
beefheart
  • 21
  • 3
  • 2
    Possible duplicate of [Copy a file in a sane, safe and efficient way](http://stackoverflow.com/questions/10195343/copy-a-file-in-a-sane-safe-and-efficient-way) – Barmar Dec 09 '15 at 21:46

1 Answers1

0

inFile.get(c1) Reads one character and stores it to c1 if available. Otherwise, leaves ch unmodified and sets failbit and eofbit.

You can use inFile.eof() to check whether the end of the file has been reached.

sapensadler
  • 386
  • 5
  • 11