Search code examples
c++file-ioifstreamofstream

Text file I/O with fstream and ifstream


#include <iostream> 
#include <fstream> 
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[]) 
{ 
    ifstream is; 
    is.open(argv[1]);
    ofstream outfile;
    outfile.open(argv[2]);
    char ch; 
    while (1) 
    { 
         ch = is.get();   // this is where test.txt is supposed
         outfile.put(ch); // to be copied to test2.txt
         if (is.eof()) 
             break; 
         cout << ch;  //this shows
    }

    is.close();
    outfile.close();

    ifstream outfile2;
    outfile2.open(argv[2]); 
    char ch2; 
    while (1)
    { 
       ch2 = outfile2.get(); 
       if (outfile2.eof()) 
         break; 
       cout << ch2;  //this doesnt
    }        
        outfile2.close();

        system("PAUSE"); 
        return 0; 
    }

I run it through cmd giving it 2 arguments test.txt test2.txt and it outputs what i have written in test.txt in cmd but test2.txt remains empty for some reason?


Solution

  • for me its not coming blank but with some extra appended characters. this is because you are writing the character which you got from the old file to the new one before checking eof().

    the code for writing from one file to another should be changed as

    while (1) 
        { 
             ch = is.get();
             if (is.eof()) 
                 break; 
             outfile.put(ch);
             cout << ch;  //this shows
        }