0

So I am trying to copy a word by word from file1 to file2 , but my code fails in opening file2 (the output file)

void myFile::printWords(string inFile, string outFile)
{
ifstream file;
ofstream file2;
file.open(inFile);
file2.open(outFile);
if (!file.is_open() && !file2.is_open()){
    string word;
    while (!file.eof()){
        file >> word;
        file2 << word << '\n';
    }
}
else{
    cout << "error" << endl;
}
file.close();
file2.close();
}

Any idea why?

XEvans
  • 31
  • 4

5 Answers5

0

Note that you only copy words, if both files failed to open, not if both of them succeeded to open:

if (!file.is_open() && !file2.is_open()){

Replace it with:

if (file.is_open() && file2.is_open()){
Ishamael
  • 11,336
  • 4
  • 28
  • 46
0
if (!file.is_open() && !file2.is_open())

Means if file is not open and file2 is not open. So you will try to read from the files if they are not open and is not you execute cout << "error" << endl;.

Your if condition should be

if (file.is_open() && file2.is_open())

Also if you want to copy one file to another than you can use

file2 << file.rdbuf();

Instead of a while loop.

NathanOliver
  • 150,499
  • 26
  • 240
  • 331
0

if (!file.is_open() && !file2.is_open())

if file is not open and file2 is not open

this logic will not copy file to file2 if your testing to see if both files are not open.

Sterling Archer
  • 20,452
  • 15
  • 77
  • 107
sillar
  • 1
0

Problem 1

if (!file.is_open() && !file2.is_open()){

It should be

if (file.is_open() && file2.is_open()){

Problem 2

while (!file.eof()){
    file >> word;
    file2 << word << '\n';
}

That is wrong. It should be:

while ( file >> word ){
    file2 << word << '\n';
}

To understand why, see Why is iostream::eof inside a loop condition considered wrong?.

Community
  • 1
  • 1
R Sahu
  • 196,807
  • 13
  • 136
  • 247
0

The tests of the form !file.is_open() shouldn't have the not operator and could be simplified even more by relying on the operator bool() member function. It's also rarely correct to loop on the eof() condition.

Taking those two things in mind I've rewritten your function, I think it's simpler and more correct this way.

void myFile::printWords(const string &inFile, const string &outFile)
{
    ifstream file(inFile);
    ofstream file2(outFile);
    if (file && file2) {
        string word;
        while (file >> word) {
            file2 << word << '\n';
        }
    } else {
        cout << "error" << endl;
    }
}

Note: the streams will be closed automatically when they're destroyed at the end of this function.

Blastfurnace
  • 17,441
  • 40
  • 50
  • 66