SVN / public / code / vorlesung-07 / InputOutput.cpp

Revision 11340
Date
Committerhb1003
Download
// Copyright 2016, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Hannah Bast <bast@cs.uni-freiburg.de>.

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "./InputOutput.h"

// _____________________________________________________________________________
InputOutput::InputOutput() {
  _withLineNumbers = false;
}

// _____________________________________________________________________________
void InputOutput::parseCommandLineArguments(int argc, char** argv) {
  struct option options[] = {
    { "with-line-numbers", 0, NULL, 'l' },
    { NULL, 0, NULL, 0 }  // Null-terminated.
  };
  optind = 1;
  while (true) {
    char c = getopt_long(argc, argv, "l", options, NULL);
    if (c == -1) break;
    if (c == '?') { exit(1); }
    if (c == 'l') _withLineNumbers = true;
  }
  if (optind + 1 != argc) {
    fprintf(stderr, "Usage: ./InputOutputMain <filename>\n");
    fprintf(stderr, "--with-line-numbers / -l : print with line numbers\n");
    exit(1);
  }
  _filename = argv[optind];
}

// _____________________________________________________________________________
void InputOutput::process() {
  FILE* file = fopen(_filename, "r");
  if (file == NULL) { perror("InputOutput::process"); exit(1); }
  int lineNumber = 0;
  int maxLineLength = 1000;
  char* line = new char[maxLineLength + 1];
  while (true) {
    fgets(line, maxLineLength + 1, file);
    if (feof(file)) break;
    if (_withLineNumbers) printf("%3d. ", ++lineNumber);
    printf("%s", line);
  }
  fclose(file);
  delete[] line;
}