// Append counter & error info:

        ostringstream out;

        out << buf << " // (" << ++counter << ") "

            << "Chapter " << CHAP

            << " File: " << FNAME

            << " Line " << linecount << endl;

        edited << out.str();

        errlines << out.str(); // Append error file

      }

      else

        edited << buf << "\n"; // Just copy

      linecount++;

    }

  }

  void saveFiles() {

    ofstream outfile(FNAME.c_str()); // Overwrites

    assure(outfile, FNAME.c_str());

    outfile << edited.rdbuf();

    ofstream count(ERRNUM.c_str()); // Overwrites

    assure(count, ERRNUM.c_str());

    count << counter; // Save new counter

  }

};

int main(int argc, char* argv[]) {

  const string ERRCOUNT("../errnum.txt"),

    ERRFILE("../errlines.txt");

  requireMinArgs(argc, 1, usage.c_str());

  if(argv[1][0] == '/' || argv[1][0] == '-') {

    // Allow for other switches:

    switch(argv[1][1]) {

      case 'r': case 'R':

        cout << "reset counter" << endl;

        remove(ERRCOUNT.c_str()); // Delete files

        remove(ERRFILE.c_str());

        return 0;

      default:

        cerr << usage << endl;

        return 1;

    }

  }

  if (argc == 3) {

    Showerr s(argv[1], ERRCOUNT, ERRFILE, atoi(argv[2]));

    s.replaceErrors();

    s.saveFiles();

  }

} ///:~

You can replace the marker with one of your choice.

Each file is read a line at a time, and each line is searched for the marker appearing at the head of the line; the line is modified and put into the error line list and into the string stream, edited. When the whole file is processed, it is closed (by reaching the end of a scope), it is reopened as an output file, and edited is poured into the file. Also notice the counter is saved in an external file. The next time this program is invoked, it continues to sequence the counter.

<p>A simple data logger</p>

This example shows an approach you might take to log data to disk and later retrieve it for processing. It is meant to produce a temperature-depth profile of the ocean at various points. To hold the data, a class is used:.

//: C04:DataLogger.h

// Datalogger record layout

#ifndef DATALOG_H

#define DATALOG_H

#include

#include

#include

using std::ostream;

struct Coord {

  int deg, min, sec;

  Coord(int d = 0, int m = 0, int s = 0)

    : deg(d), min(m), sec(s) {}

  std::string toString() const;

};

ostream& operator<<(ostream&, const Coord&);

class DataPoint {

  std::time_t timestamp; // Time & day

  Coord latitude, longitude;

  double depth, temperature;

public:

  DataPoint(std::time_t ts, const Coord& lat,

            const Coord& lon, double dep, double temp)

    : timestamp(ts), latitude(lat), longitude(lon),

      depth(dep), temperature(temp) {}

  DataPoint() : timestamp(0), depth(0), temperature(0) {}

  friend ostream& operator<<(ostream&, const DataPoint&);

};

#endif // DATALOG_H ///:~

A DataPoint consists of a time stamp, which is stored as a time_t value as defined in , longitude and latitude coordinates, and values for depth and temperature. We use inserters for easy formatting. Here’s the implementation file:.

//: C04:DataLogger.cpp {O}

// Datapoint implementations

#include "DataLogger.h"

#include

#include

#include

#include

using namespace std;

ostream& operator<<(ostream& os, const Coord& c) {

  return os << c.deg << '*' << c.min << '\''

            << c.sec << '"';

}

string Coord::toString() const {

  ostringstream os;

  os << *this;

  return os.str();

}

ostream& operator<<(ostream& os, const DataPoint& d) {

  os.setf(ios::fixed, ios::floatfield);

  char fillc = os.fill('0'); // Pad on left with '0'

  tm* tdata = localtime(&d.timestamp);

  os << setw(2) << tdata->tm_mon + 1 << '\\'

     << setw(2) << tdata->tm_mday << '\\'

     << setw(2) << tdata->tm_year+1900 << ' '

     << setw(2) << tdata->tm_hour << ':'

     << setw(2) << tdata->tm_min << ':'

     << setw(2) << tdata->tm_sec;

  os.fill(' '); // Pad on left with ' '

  streamsize prec = os.precision(4);

  os << " Lat:" << setw(9) << d.latitude.toString()

     << ", Long:" << setw(9) << d.longitude.toString()

     << ", depth:" << setw(9) << d.depth

     << ", temp:" << setw(9) << d.temperature;

  os.fill(fillc);

  os.precision(prec);

  return os;

} ///:~

The Coord::toString( ) function is necessary because the DataPoint inserter calls setw( ) before it prints the latitude and longitude. If we used the stream inserter for Coord instead, the width would only apply to the first insertion (that is, to Coord::deg), since width changes are always reset immediately. The call to setf( ) causes the floating-point output to be fixed-precision, and precision( ) sets the number of decimal places to four. Notice how we restore the fill character and precision to whatever they were before the inserter was called.

To get the values from the time encoding stored in DataPoint::timestamp, we call the function std::localtime( ), which returns a static pointer to a tm object. The tm struct has the following layout:

struct tm {

  int tm_sec; // 0-59 seconds

  int tm_min; // 0-59 minutes

  int tm_hour; // 0-23 hours

  int tm_mday; // Day of month

  int tm_mon; // 0-11 months

  int tm_year; // Years since 1900

  int tm_wday; // Sunday == 0, etc.

  int tm_yday; // 0-365 day of year

  int tm_isdst; // Daylight savings?

};

<p>Generating test data</p>
Перейти на страницу:

Похожие книги