// Datei kopieren und in Kleinschreibung verwandeln
//
// Aufruf: filelower infilename outfilename
//
// Klaus Kusche, 2011

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

using namespace std;

int main(int argc, const char *argv[])
{
  if (argc != 3) {
    cerr << "Aufruf: " << argv[0] << " infilename outfilename" << endl;
    exit(EXIT_FAILURE);
  }

  ifstream inf(argv[1]);
  if (!inf) {
    cerr << argv[0] << ": Cannot open " << argv[1] << " for reading" << endl;
    exit(EXIT_FAILURE);
  }

  ofstream outf(argv[2]);
  if (!outf) {
    cerr << argv[0] << ": Cannot open " << argv[2] << " for writing" << endl;
    exit(EXIT_FAILURE);
  }

  char c;
  // Returnwert von inf.get() ist der File inf, von outf.put() ist es outf
  // Ein File im if oder while zeigt Erfolg (true) oder Mißerfolg (false)
  // der letzten Operation auf dem File an
  while (inf.get(c)) {  
    if (!(outf.put(tolower(c)))) {
      cerr << argv[0] << ": Cannot write " << argv[2] << endl;
      exit(EXIT_FAILURE);
    }
  }

  // wenn fail() oder bad() true ist aber eof() nicht true ist
  // (d.h. das get schiefgegangen ist, obwohl der File noch nicht am Ende ist),
  // dann ist ein echter Fehler aufgetreten
  if (!inf.eof()) {
    cerr << argv[0] << ": Cannot read " << argv[1] << endl;
    exit(EXIT_FAILURE);
  }

  // ob bei exit die offenen Files automatisch geschlossen werden,
  // ist Glückssache (eher nein)
  // ==> vorsichtshalber vorher selbst schließen,
  // vor allem den outf, damit sicher alles geschrieben wird!
  // Bei Lese-Files muss das close nicht unbedingt auf Fehler geprüft werden,
  // bei Files, die geschrieben werden, schon!
  inf.close();
  outf.close();
  if (!outf) {
    cerr << argv[0] << ": Cannot write " << argv[2] << endl;
    exit(EXIT_FAILURE);
  }
  
  exit(EXIT_SUCCESS);
}
