1

Right now I have a simple program that copies a file and outputs the content of the file into whatever file I name so when I type ./file text.txt output.txt it copies the content correctly but creates a new line at the end of output.txt when I try diffing it. can anyone tell me why and how to solve it

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
    ifstream fin;
    fin.open(argv[1], ios::in);

    ofstream fout;
    fout.open(argv[2], ios::out);
    char getChar;

    while (!fin.eof())
    {
        fin.get(getChar);
        fout << getChar;
    }

    fin.close();
    fout.close();

    return 0;
}
  • `ofstream` and `ios::out`, `ifstream` and `ios::in`... you really don't trust your library, do you? – Kerrek SB Oct 22 '14 at 22:45
  • Looping on `eof()` is usually wrong: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Galik Oct 22 '14 at 23:00
  • 2
    @KerrekSB What do you mean. .eof() means until the end of the file. Keep reading. – Janna Westbrook Oct 22 '14 at 23:55
  • @JannaWestbrook: No. Don't guess. Look it up and make sure you understand what it actually does, not just what you wish it to mean. – Kerrek SB Oct 23 '14 at 00:09
  • @KerrekSB EOF is an indicator that is returned by several STDIO functions to indicate that the current file position is the end of the file. – Janna Westbrook Oct 23 '14 at 06:35
  • 1
    @JannaWestbrook: Again wrong. EOF is returned by several stdio functions *when you attempt to read past the end* of the file. You can only witness the EOF condition by actually trying to move past the end. You have *not* reached EOF just after reading the last character. That's why inspecting the EOF state is *not* a guarantee that a *future* operation will succeed -- that's the core of the error in your code. In summary, you always have to operate I/O as "try, check result, consume if OK", in that order. Success is never guaranteed. – Kerrek SB Oct 23 '14 at 08:44

1 Answers1

3

The problem is likely that you are looping on eof().

Looping on eof() is usually wrong: Why is iostream::eof inside a loop condition considered wrong?

Try this:

char c;
while(fin.get(c)) // tests if read succeeded
    fout.put(c);
Community
  • 1
  • 1
Galik
  • 42,526
  • 3
  • 76
  • 100